SimplifyCFG.cpp 231 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095
  1. //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
  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. // Peephole optimize the CFG.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SetOperations.h"
  19. #include "llvm/ADT/SetVector.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/Analysis/AssumptionCache.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/Analysis/EHPersonalities.h"
  27. #include "llvm/Analysis/InstructionSimplify.h"
  28. #include "llvm/Analysis/TargetTransformInfo.h"
  29. #include "llvm/Transforms/Utils/Local.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/Attributes.h"
  32. #include "llvm/IR/BasicBlock.h"
  33. #include "llvm/IR/CFG.h"
  34. #include "llvm/IR/CallSite.h"
  35. #include "llvm/IR/Constant.h"
  36. #include "llvm/IR/ConstantRange.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/GlobalValue.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/IRBuilder.h"
  44. #include "llvm/IR/InstrTypes.h"
  45. #include "llvm/IR/Instruction.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/IntrinsicInst.h"
  48. #include "llvm/IR/Intrinsics.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/MDBuilder.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/NoFolder.h"
  54. #include "llvm/IR/Operator.h"
  55. #include "llvm/IR/PatternMatch.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/Use.h"
  58. #include "llvm/IR/User.h"
  59. #include "llvm/IR/Value.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/KnownBits.h"
  65. #include "llvm/Support/MathExtras.h"
  66. #include "llvm/Support/raw_ostream.h"
  67. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  68. #include "llvm/Transforms/Utils/ValueMapper.h"
  69. #include <algorithm>
  70. #include <cassert>
  71. #include <climits>
  72. #include <cstddef>
  73. #include <cstdint>
  74. #include <iterator>
  75. #include <map>
  76. #include <set>
  77. #include <tuple>
  78. #include <utility>
  79. #include <vector>
  80. using namespace llvm;
  81. using namespace PatternMatch;
  82. #define DEBUG_TYPE "simplifycfg"
  83. // Chosen as 2 so as to be cheap, but still to have enough power to fold
  84. // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
  85. // To catch this, we need to fold a compare and a select, hence '2' being the
  86. // minimum reasonable default.
  87. static cl::opt<unsigned> PHINodeFoldingThreshold(
  88. "phi-node-folding-threshold", cl::Hidden, cl::init(2),
  89. cl::desc(
  90. "Control the amount of phi node folding to perform (default = 2)"));
  91. static cl::opt<bool> DupRet(
  92. "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  93. cl::desc("Duplicate return instructions into unconditional branches"));
  94. static cl::opt<bool>
  95. SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
  96. cl::desc("Sink common instructions down to the end block"));
  97. static cl::opt<bool> HoistCondStores(
  98. "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
  99. cl::desc("Hoist conditional stores if an unconditional store precedes"));
  100. static cl::opt<bool> MergeCondStores(
  101. "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
  102. cl::desc("Hoist conditional stores even if an unconditional store does not "
  103. "precede - hoist multiple conditional stores into a single "
  104. "predicated store"));
  105. static cl::opt<bool> MergeCondStoresAggressively(
  106. "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
  107. cl::desc("When merging conditional stores, do so even if the resultant "
  108. "basic blocks are unlikely to be if-converted as a result"));
  109. static cl::opt<bool> SpeculateOneExpensiveInst(
  110. "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
  111. cl::desc("Allow exactly one expensive instruction to be speculatively "
  112. "executed"));
  113. static cl::opt<unsigned> MaxSpeculationDepth(
  114. "max-speculation-depth", cl::Hidden, cl::init(10),
  115. cl::desc("Limit maximum recursion depth when calculating costs of "
  116. "speculatively executed instructions"));
  117. STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
  118. STATISTIC(NumLinearMaps,
  119. "Number of switch instructions turned into linear mapping");
  120. STATISTIC(NumLookupTables,
  121. "Number of switch instructions turned into lookup tables");
  122. STATISTIC(
  123. NumLookupTablesHoles,
  124. "Number of switch instructions turned into lookup tables (holes checked)");
  125. STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
  126. STATISTIC(NumSinkCommons,
  127. "Number of common instructions sunk down to the end block");
  128. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  129. namespace {
  130. // The first field contains the value that the switch produces when a certain
  131. // case group is selected, and the second field is a vector containing the
  132. // cases composing the case group.
  133. using SwitchCaseResultVectorTy =
  134. SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
  135. // The first field contains the phi node that generates a result of the switch
  136. // and the second field contains the value generated for a certain case in the
  137. // switch for that PHI.
  138. using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
  139. /// ValueEqualityComparisonCase - Represents a case of a switch.
  140. struct ValueEqualityComparisonCase {
  141. ConstantInt *Value;
  142. BasicBlock *Dest;
  143. ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
  144. : Value(Value), Dest(Dest) {}
  145. bool operator<(ValueEqualityComparisonCase RHS) const {
  146. // Comparing pointers is ok as we only rely on the order for uniquing.
  147. return Value < RHS.Value;
  148. }
  149. bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
  150. };
  151. class SimplifyCFGOpt {
  152. const TargetTransformInfo &TTI;
  153. const DataLayout &DL;
  154. SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
  155. const SimplifyCFGOptions &Options;
  156. bool Resimplify;
  157. Value *isValueEqualityComparison(Instruction *TI);
  158. BasicBlock *GetValueEqualityComparisonCases(
  159. Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
  160. bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
  161. BasicBlock *Pred,
  162. IRBuilder<> &Builder);
  163. bool FoldValueComparisonIntoPredecessors(Instruction *TI,
  164. IRBuilder<> &Builder);
  165. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  166. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  167. bool SimplifySingleResume(ResumeInst *RI);
  168. bool SimplifyCommonResume(ResumeInst *RI);
  169. bool SimplifyCleanupReturn(CleanupReturnInst *RI);
  170. bool SimplifyUnreachable(UnreachableInst *UI);
  171. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  172. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  173. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
  174. bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
  175. bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
  176. IRBuilder<> &Builder);
  177. public:
  178. SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
  179. SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
  180. const SimplifyCFGOptions &Opts)
  181. : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
  182. bool run(BasicBlock *BB);
  183. bool simplifyOnce(BasicBlock *BB);
  184. // Helper to set Resimplify and return change indication.
  185. bool requestResimplify() {
  186. Resimplify = true;
  187. return true;
  188. }
  189. };
  190. } // end anonymous namespace
  191. /// Return true if it is safe to merge these two
  192. /// terminator instructions together.
  193. static bool
  194. SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
  195. SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
  196. if (SI1 == SI2)
  197. return false; // Can't merge with self!
  198. // It is not safe to merge these two switch instructions if they have a common
  199. // successor, and if that successor has a PHI node, and if *that* PHI node has
  200. // conflicting incoming values from the two switch blocks.
  201. BasicBlock *SI1BB = SI1->getParent();
  202. BasicBlock *SI2BB = SI2->getParent();
  203. SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  204. bool Fail = false;
  205. for (BasicBlock *Succ : successors(SI2BB))
  206. if (SI1Succs.count(Succ))
  207. for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
  208. PHINode *PN = cast<PHINode>(BBI);
  209. if (PN->getIncomingValueForBlock(SI1BB) !=
  210. PN->getIncomingValueForBlock(SI2BB)) {
  211. if (FailBlocks)
  212. FailBlocks->insert(Succ);
  213. Fail = true;
  214. }
  215. }
  216. return !Fail;
  217. }
  218. /// Return true if it is safe and profitable to merge these two terminator
  219. /// instructions together, where SI1 is an unconditional branch. PhiNodes will
  220. /// store all PHI nodes in common successors.
  221. static bool
  222. isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
  223. Instruction *Cond,
  224. SmallVectorImpl<PHINode *> &PhiNodes) {
  225. if (SI1 == SI2)
  226. return false; // Can't merge with self!
  227. assert(SI1->isUnconditional() && SI2->isConditional());
  228. // We fold the unconditional branch if we can easily update all PHI nodes in
  229. // common successors:
  230. // 1> We have a constant incoming value for the conditional branch;
  231. // 2> We have "Cond" as the incoming value for the unconditional branch;
  232. // 3> SI2->getCondition() and Cond have same operands.
  233. CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
  234. if (!Ci2)
  235. return false;
  236. if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
  237. Cond->getOperand(1) == Ci2->getOperand(1)) &&
  238. !(Cond->getOperand(0) == Ci2->getOperand(1) &&
  239. Cond->getOperand(1) == Ci2->getOperand(0)))
  240. return false;
  241. BasicBlock *SI1BB = SI1->getParent();
  242. BasicBlock *SI2BB = SI2->getParent();
  243. SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  244. for (BasicBlock *Succ : successors(SI2BB))
  245. if (SI1Succs.count(Succ))
  246. for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
  247. PHINode *PN = cast<PHINode>(BBI);
  248. if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
  249. !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
  250. return false;
  251. PhiNodes.push_back(PN);
  252. }
  253. return true;
  254. }
  255. /// Update PHI nodes in Succ to indicate that there will now be entries in it
  256. /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
  257. /// will be the same as those coming in from ExistPred, an existing predecessor
  258. /// of Succ.
  259. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  260. BasicBlock *ExistPred) {
  261. for (PHINode &PN : Succ->phis())
  262. PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
  263. }
  264. /// Compute an abstract "cost" of speculating the given instruction,
  265. /// which is assumed to be safe to speculate. TCC_Free means cheap,
  266. /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
  267. /// expensive.
  268. static unsigned ComputeSpeculationCost(const User *I,
  269. const TargetTransformInfo &TTI) {
  270. assert(isSafeToSpeculativelyExecute(I) &&
  271. "Instruction is not safe to speculatively execute!");
  272. return TTI.getUserCost(I);
  273. }
  274. /// If we have a merge point of an "if condition" as accepted above,
  275. /// return true if the specified value dominates the block. We
  276. /// don't handle the true generality of domination here, just a special case
  277. /// which works well enough for us.
  278. ///
  279. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  280. /// see if V (which must be an instruction) and its recursive operands
  281. /// that do not dominate BB have a combined cost lower than CostRemaining and
  282. /// are non-trapping. If both are true, the instruction is inserted into the
  283. /// set and true is returned.
  284. ///
  285. /// The cost for most non-trapping instructions is defined as 1 except for
  286. /// Select whose cost is 2.
  287. ///
  288. /// After this function returns, CostRemaining is decreased by the cost of
  289. /// V plus its non-dominating operands. If that cost is greater than
  290. /// CostRemaining, false is returned and CostRemaining is undefined.
  291. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  292. SmallPtrSetImpl<Instruction *> &AggressiveInsts,
  293. unsigned &CostRemaining,
  294. const TargetTransformInfo &TTI,
  295. unsigned Depth = 0) {
  296. // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
  297. // so limit the recursion depth.
  298. // TODO: While this recursion limit does prevent pathological behavior, it
  299. // would be better to track visited instructions to avoid cycles.
  300. if (Depth == MaxSpeculationDepth)
  301. return false;
  302. Instruction *I = dyn_cast<Instruction>(V);
  303. if (!I) {
  304. // Non-instructions all dominate instructions, but not all constantexprs
  305. // can be executed unconditionally.
  306. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  307. if (C->canTrap())
  308. return false;
  309. return true;
  310. }
  311. BasicBlock *PBB = I->getParent();
  312. // We don't want to allow weird loops that might have the "if condition" in
  313. // the bottom of this block.
  314. if (PBB == BB)
  315. return false;
  316. // If this instruction is defined in a block that contains an unconditional
  317. // branch to BB, then it must be in the 'conditional' part of the "if
  318. // statement". If not, it definitely dominates the region.
  319. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  320. if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
  321. return true;
  322. // If we have seen this instruction before, don't count it again.
  323. if (AggressiveInsts.count(I))
  324. return true;
  325. // Okay, it looks like the instruction IS in the "condition". Check to
  326. // see if it's a cheap instruction to unconditionally compute, and if it
  327. // only uses stuff defined outside of the condition. If so, hoist it out.
  328. if (!isSafeToSpeculativelyExecute(I))
  329. return false;
  330. unsigned Cost = ComputeSpeculationCost(I, TTI);
  331. // Allow exactly one instruction to be speculated regardless of its cost
  332. // (as long as it is safe to do so).
  333. // This is intended to flatten the CFG even if the instruction is a division
  334. // or other expensive operation. The speculation of an expensive instruction
  335. // is expected to be undone in CodeGenPrepare if the speculation has not
  336. // enabled further IR optimizations.
  337. if (Cost > CostRemaining &&
  338. (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0))
  339. return false;
  340. // Avoid unsigned wrap.
  341. CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
  342. // Okay, we can only really hoist these out if their operands do
  343. // not take us over the cost threshold.
  344. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  345. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
  346. Depth + 1))
  347. return false;
  348. // Okay, it's safe to do this! Remember this instruction.
  349. AggressiveInsts.insert(I);
  350. return true;
  351. }
  352. /// Extract ConstantInt from value, looking through IntToPtr
  353. /// and PointerNullValue. Return NULL if value is not a constant int.
  354. static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
  355. // Normal constant int.
  356. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  357. if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
  358. return CI;
  359. // This is some kind of pointer constant. Turn it into a pointer-sized
  360. // ConstantInt if possible.
  361. IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
  362. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  363. if (isa<ConstantPointerNull>(V))
  364. return ConstantInt::get(PtrTy, 0);
  365. // IntToPtr const int.
  366. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  367. if (CE->getOpcode() == Instruction::IntToPtr)
  368. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  369. // The constant is very likely to have the right type already.
  370. if (CI->getType() == PtrTy)
  371. return CI;
  372. else
  373. return cast<ConstantInt>(
  374. ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  375. }
  376. return nullptr;
  377. }
  378. namespace {
  379. /// Given a chain of or (||) or and (&&) comparison of a value against a
  380. /// constant, this will try to recover the information required for a switch
  381. /// structure.
  382. /// It will depth-first traverse the chain of comparison, seeking for patterns
  383. /// like %a == 12 or %a < 4 and combine them to produce a set of integer
  384. /// representing the different cases for the switch.
  385. /// Note that if the chain is composed of '||' it will build the set of elements
  386. /// that matches the comparisons (i.e. any of this value validate the chain)
  387. /// while for a chain of '&&' it will build the set elements that make the test
  388. /// fail.
  389. struct ConstantComparesGatherer {
  390. const DataLayout &DL;
  391. /// Value found for the switch comparison
  392. Value *CompValue = nullptr;
  393. /// Extra clause to be checked before the switch
  394. Value *Extra = nullptr;
  395. /// Set of integers to match in switch
  396. SmallVector<ConstantInt *, 8> Vals;
  397. /// Number of comparisons matched in the and/or chain
  398. unsigned UsedICmps = 0;
  399. /// Construct and compute the result for the comparison instruction Cond
  400. ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
  401. gather(Cond);
  402. }
  403. ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
  404. ConstantComparesGatherer &
  405. operator=(const ConstantComparesGatherer &) = delete;
  406. private:
  407. /// Try to set the current value used for the comparison, it succeeds only if
  408. /// it wasn't set before or if the new value is the same as the old one
  409. bool setValueOnce(Value *NewVal) {
  410. if (CompValue && CompValue != NewVal)
  411. return false;
  412. CompValue = NewVal;
  413. return (CompValue != nullptr);
  414. }
  415. /// Try to match Instruction "I" as a comparison against a constant and
  416. /// populates the array Vals with the set of values that match (or do not
  417. /// match depending on isEQ).
  418. /// Return false on failure. On success, the Value the comparison matched
  419. /// against is placed in CompValue.
  420. /// If CompValue is already set, the function is expected to fail if a match
  421. /// is found but the value compared to is different.
  422. bool matchInstruction(Instruction *I, bool isEQ) {
  423. // If this is an icmp against a constant, handle this as one of the cases.
  424. ICmpInst *ICI;
  425. ConstantInt *C;
  426. if (!((ICI = dyn_cast<ICmpInst>(I)) &&
  427. (C = GetConstantInt(I->getOperand(1), DL)))) {
  428. return false;
  429. }
  430. Value *RHSVal;
  431. const APInt *RHSC;
  432. // Pattern match a special case
  433. // (x & ~2^z) == y --> x == y || x == y|2^z
  434. // This undoes a transformation done by instcombine to fuse 2 compares.
  435. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
  436. // It's a little bit hard to see why the following transformations are
  437. // correct. Here is a CVC3 program to verify them for 64-bit values:
  438. /*
  439. ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
  440. x : BITVECTOR(64);
  441. y : BITVECTOR(64);
  442. z : BITVECTOR(64);
  443. mask : BITVECTOR(64) = BVSHL(ONE, z);
  444. QUERY( (y & ~mask = y) =>
  445. ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
  446. );
  447. QUERY( (y | mask = y) =>
  448. ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
  449. );
  450. */
  451. // Please note that each pattern must be a dual implication (<--> or
  452. // iff). One directional implication can create spurious matches. If the
  453. // implication is only one-way, an unsatisfiable condition on the left
  454. // side can imply a satisfiable condition on the right side. Dual
  455. // implication ensures that satisfiable conditions are transformed to
  456. // other satisfiable conditions and unsatisfiable conditions are
  457. // transformed to other unsatisfiable conditions.
  458. // Here is a concrete example of a unsatisfiable condition on the left
  459. // implying a satisfiable condition on the right:
  460. //
  461. // mask = (1 << z)
  462. // (x & ~mask) == y --> (x == y || x == (y | mask))
  463. //
  464. // Substituting y = 3, z = 0 yields:
  465. // (x & -2) == 3 --> (x == 3 || x == 2)
  466. // Pattern match a special case:
  467. /*
  468. QUERY( (y & ~mask = y) =>
  469. ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
  470. );
  471. */
  472. if (match(ICI->getOperand(0),
  473. m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
  474. APInt Mask = ~*RHSC;
  475. if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
  476. // If we already have a value for the switch, it has to match!
  477. if (!setValueOnce(RHSVal))
  478. return false;
  479. Vals.push_back(C);
  480. Vals.push_back(
  481. ConstantInt::get(C->getContext(),
  482. C->getValue() | Mask));
  483. UsedICmps++;
  484. return true;
  485. }
  486. }
  487. // Pattern match a special case:
  488. /*
  489. QUERY( (y | mask = y) =>
  490. ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
  491. );
  492. */
  493. if (match(ICI->getOperand(0),
  494. m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
  495. APInt Mask = *RHSC;
  496. if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
  497. // If we already have a value for the switch, it has to match!
  498. if (!setValueOnce(RHSVal))
  499. return false;
  500. Vals.push_back(C);
  501. Vals.push_back(ConstantInt::get(C->getContext(),
  502. C->getValue() & ~Mask));
  503. UsedICmps++;
  504. return true;
  505. }
  506. }
  507. // If we already have a value for the switch, it has to match!
  508. if (!setValueOnce(ICI->getOperand(0)))
  509. return false;
  510. UsedICmps++;
  511. Vals.push_back(C);
  512. return ICI->getOperand(0);
  513. }
  514. // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
  515. ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
  516. ICI->getPredicate(), C->getValue());
  517. // Shift the range if the compare is fed by an add. This is the range
  518. // compare idiom as emitted by instcombine.
  519. Value *CandidateVal = I->getOperand(0);
  520. if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
  521. Span = Span.subtract(*RHSC);
  522. CandidateVal = RHSVal;
  523. }
  524. // If this is an and/!= check, then we are looking to build the set of
  525. // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
  526. // x != 0 && x != 1.
  527. if (!isEQ)
  528. Span = Span.inverse();
  529. // If there are a ton of values, we don't want to make a ginormous switch.
  530. if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
  531. return false;
  532. }
  533. // If we already have a value for the switch, it has to match!
  534. if (!setValueOnce(CandidateVal))
  535. return false;
  536. // Add all values from the range to the set
  537. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  538. Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
  539. UsedICmps++;
  540. return true;
  541. }
  542. /// Given a potentially 'or'd or 'and'd together collection of icmp
  543. /// eq/ne/lt/gt instructions that compare a value against a constant, extract
  544. /// the value being compared, and stick the list constants into the Vals
  545. /// vector.
  546. /// One "Extra" case is allowed to differ from the other.
  547. void gather(Value *V) {
  548. Instruction *I = dyn_cast<Instruction>(V);
  549. bool isEQ = (I->getOpcode() == Instruction::Or);
  550. // Keep a stack (SmallVector for efficiency) for depth-first traversal
  551. SmallVector<Value *, 8> DFT;
  552. SmallPtrSet<Value *, 8> Visited;
  553. // Initialize
  554. Visited.insert(V);
  555. DFT.push_back(V);
  556. while (!DFT.empty()) {
  557. V = DFT.pop_back_val();
  558. if (Instruction *I = dyn_cast<Instruction>(V)) {
  559. // If it is a || (or && depending on isEQ), process the operands.
  560. if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
  561. if (Visited.insert(I->getOperand(1)).second)
  562. DFT.push_back(I->getOperand(1));
  563. if (Visited.insert(I->getOperand(0)).second)
  564. DFT.push_back(I->getOperand(0));
  565. continue;
  566. }
  567. // Try to match the current instruction
  568. if (matchInstruction(I, isEQ))
  569. // Match succeed, continue the loop
  570. continue;
  571. }
  572. // One element of the sequence of || (or &&) could not be match as a
  573. // comparison against the same value as the others.
  574. // We allow only one "Extra" case to be checked before the switch
  575. if (!Extra) {
  576. Extra = V;
  577. continue;
  578. }
  579. // Failed to parse a proper sequence, abort now
  580. CompValue = nullptr;
  581. break;
  582. }
  583. }
  584. };
  585. } // end anonymous namespace
  586. static void EraseTerminatorAndDCECond(Instruction *TI) {
  587. Instruction *Cond = nullptr;
  588. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  589. Cond = dyn_cast<Instruction>(SI->getCondition());
  590. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  591. if (BI->isConditional())
  592. Cond = dyn_cast<Instruction>(BI->getCondition());
  593. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  594. Cond = dyn_cast<Instruction>(IBI->getAddress());
  595. }
  596. TI->eraseFromParent();
  597. if (Cond)
  598. RecursivelyDeleteTriviallyDeadInstructions(Cond);
  599. }
  600. /// Return true if the specified terminator checks
  601. /// to see if a value is equal to constant integer value.
  602. Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
  603. Value *CV = nullptr;
  604. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  605. // Do not permit merging of large switch instructions into their
  606. // predecessors unless there is only one predecessor.
  607. if (SI->getNumSuccessors() * pred_size(SI->getParent()) <= 128)
  608. CV = SI->getCondition();
  609. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  610. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  611. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
  612. if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
  613. CV = ICI->getOperand(0);
  614. }
  615. // Unwrap any lossless ptrtoint cast.
  616. if (CV) {
  617. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
  618. Value *Ptr = PTII->getPointerOperand();
  619. if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
  620. CV = Ptr;
  621. }
  622. }
  623. return CV;
  624. }
  625. /// Given a value comparison instruction,
  626. /// decode all of the 'cases' that it represents and return the 'default' block.
  627. BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
  628. Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
  629. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  630. Cases.reserve(SI->getNumCases());
  631. for (auto Case : SI->cases())
  632. Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
  633. Case.getCaseSuccessor()));
  634. return SI->getDefaultDest();
  635. }
  636. BranchInst *BI = cast<BranchInst>(TI);
  637. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  638. BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
  639. Cases.push_back(ValueEqualityComparisonCase(
  640. GetConstantInt(ICI->getOperand(1), DL), Succ));
  641. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  642. }
  643. /// Given a vector of bb/value pairs, remove any entries
  644. /// in the list that match the specified block.
  645. static void
  646. EliminateBlockCases(BasicBlock *BB,
  647. std::vector<ValueEqualityComparisonCase> &Cases) {
  648. Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
  649. }
  650. /// Return true if there are any keys in C1 that exist in C2 as well.
  651. static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
  652. std::vector<ValueEqualityComparisonCase> &C2) {
  653. std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
  654. // Make V1 be smaller than V2.
  655. if (V1->size() > V2->size())
  656. std::swap(V1, V2);
  657. if (V1->empty())
  658. return false;
  659. if (V1->size() == 1) {
  660. // Just scan V2.
  661. ConstantInt *TheVal = (*V1)[0].Value;
  662. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  663. if (TheVal == (*V2)[i].Value)
  664. return true;
  665. }
  666. // Otherwise, just sort both lists and compare element by element.
  667. array_pod_sort(V1->begin(), V1->end());
  668. array_pod_sort(V2->begin(), V2->end());
  669. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  670. while (i1 != e1 && i2 != e2) {
  671. if ((*V1)[i1].Value == (*V2)[i2].Value)
  672. return true;
  673. if ((*V1)[i1].Value < (*V2)[i2].Value)
  674. ++i1;
  675. else
  676. ++i2;
  677. }
  678. return false;
  679. }
  680. // Set branch weights on SwitchInst. This sets the metadata if there is at
  681. // least one non-zero weight.
  682. static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
  683. // Check that there is at least one non-zero weight. Otherwise, pass
  684. // nullptr to setMetadata which will erase the existing metadata.
  685. MDNode *N = nullptr;
  686. if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
  687. N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
  688. SI->setMetadata(LLVMContext::MD_prof, N);
  689. }
  690. // Similar to the above, but for branch and select instructions that take
  691. // exactly 2 weights.
  692. static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
  693. uint32_t FalseWeight) {
  694. assert(isa<BranchInst>(I) || isa<SelectInst>(I));
  695. // Check that there is at least one non-zero weight. Otherwise, pass
  696. // nullptr to setMetadata which will erase the existing metadata.
  697. MDNode *N = nullptr;
  698. if (TrueWeight || FalseWeight)
  699. N = MDBuilder(I->getParent()->getContext())
  700. .createBranchWeights(TrueWeight, FalseWeight);
  701. I->setMetadata(LLVMContext::MD_prof, N);
  702. }
  703. /// If TI is known to be a terminator instruction and its block is known to
  704. /// only have a single predecessor block, check to see if that predecessor is
  705. /// also a value comparison with the same value, and if that comparison
  706. /// determines the outcome of this comparison. If so, simplify TI. This does a
  707. /// very limited form of jump threading.
  708. bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
  709. Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
  710. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  711. if (!PredVal)
  712. return false; // Not a value comparison in predecessor.
  713. Value *ThisVal = isValueEqualityComparison(TI);
  714. assert(ThisVal && "This isn't a value comparison!!");
  715. if (ThisVal != PredVal)
  716. return false; // Different predicates.
  717. // TODO: Preserve branch weight metadata, similarly to how
  718. // FoldValueComparisonIntoPredecessors preserves it.
  719. // Find out information about when control will move from Pred to TI's block.
  720. std::vector<ValueEqualityComparisonCase> PredCases;
  721. BasicBlock *PredDef =
  722. GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
  723. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  724. // Find information about how control leaves this block.
  725. std::vector<ValueEqualityComparisonCase> ThisCases;
  726. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  727. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  728. // If TI's block is the default block from Pred's comparison, potentially
  729. // simplify TI based on this knowledge.
  730. if (PredDef == TI->getParent()) {
  731. // If we are here, we know that the value is none of those cases listed in
  732. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  733. // can simplify TI.
  734. if (!ValuesOverlap(PredCases, ThisCases))
  735. return false;
  736. if (isa<BranchInst>(TI)) {
  737. // Okay, one of the successors of this condbr is dead. Convert it to a
  738. // uncond br.
  739. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  740. // Insert the new branch.
  741. Instruction *NI = Builder.CreateBr(ThisDef);
  742. (void)NI;
  743. // Remove PHI node entries for the dead edge.
  744. ThisCases[0].Dest->removePredecessor(TI->getParent());
  745. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  746. << "Through successor TI: " << *TI << "Leaving: " << *NI
  747. << "\n");
  748. EraseTerminatorAndDCECond(TI);
  749. return true;
  750. }
  751. SwitchInst *SI = cast<SwitchInst>(TI);
  752. // Okay, TI has cases that are statically dead, prune them away.
  753. SmallPtrSet<Constant *, 16> DeadCases;
  754. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  755. DeadCases.insert(PredCases[i].Value);
  756. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  757. << "Through successor TI: " << *TI);
  758. // Collect branch weights into a vector.
  759. SmallVector<uint32_t, 8> Weights;
  760. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  761. bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
  762. if (HasWeight)
  763. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  764. ++MD_i) {
  765. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  766. Weights.push_back(CI->getValue().getZExtValue());
  767. }
  768. for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
  769. --i;
  770. if (DeadCases.count(i->getCaseValue())) {
  771. if (HasWeight) {
  772. std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
  773. Weights.pop_back();
  774. }
  775. i->getCaseSuccessor()->removePredecessor(TI->getParent());
  776. SI->removeCase(i);
  777. }
  778. }
  779. if (HasWeight && Weights.size() >= 2)
  780. setBranchWeights(SI, Weights);
  781. LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  782. return true;
  783. }
  784. // Otherwise, TI's block must correspond to some matched value. Find out
  785. // which value (or set of values) this is.
  786. ConstantInt *TIV = nullptr;
  787. BasicBlock *TIBB = TI->getParent();
  788. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  789. if (PredCases[i].Dest == TIBB) {
  790. if (TIV)
  791. return false; // Cannot handle multiple values coming to this block.
  792. TIV = PredCases[i].Value;
  793. }
  794. assert(TIV && "No edge from pred to succ?");
  795. // Okay, we found the one constant that our value can be if we get into TI's
  796. // BB. Find out which successor will unconditionally be branched to.
  797. BasicBlock *TheRealDest = nullptr;
  798. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  799. if (ThisCases[i].Value == TIV) {
  800. TheRealDest = ThisCases[i].Dest;
  801. break;
  802. }
  803. // If not handled by any explicit cases, it is handled by the default case.
  804. if (!TheRealDest)
  805. TheRealDest = ThisDef;
  806. // Remove PHI node entries for dead edges.
  807. BasicBlock *CheckEdge = TheRealDest;
  808. for (BasicBlock *Succ : successors(TIBB))
  809. if (Succ != CheckEdge)
  810. Succ->removePredecessor(TIBB);
  811. else
  812. CheckEdge = nullptr;
  813. // Insert the new branch.
  814. Instruction *NI = Builder.CreateBr(TheRealDest);
  815. (void)NI;
  816. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  817. << "Through successor TI: " << *TI << "Leaving: " << *NI
  818. << "\n");
  819. EraseTerminatorAndDCECond(TI);
  820. return true;
  821. }
  822. namespace {
  823. /// This class implements a stable ordering of constant
  824. /// integers that does not depend on their address. This is important for
  825. /// applications that sort ConstantInt's to ensure uniqueness.
  826. struct ConstantIntOrdering {
  827. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  828. return LHS->getValue().ult(RHS->getValue());
  829. }
  830. };
  831. } // end anonymous namespace
  832. static int ConstantIntSortPredicate(ConstantInt *const *P1,
  833. ConstantInt *const *P2) {
  834. const ConstantInt *LHS = *P1;
  835. const ConstantInt *RHS = *P2;
  836. if (LHS == RHS)
  837. return 0;
  838. return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
  839. }
  840. static inline bool HasBranchWeights(const Instruction *I) {
  841. MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
  842. if (ProfMD && ProfMD->getOperand(0))
  843. if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
  844. return MDS->getString().equals("branch_weights");
  845. return false;
  846. }
  847. /// Get Weights of a given terminator, the default weight is at the front
  848. /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
  849. /// metadata.
  850. static void GetBranchWeights(Instruction *TI,
  851. SmallVectorImpl<uint64_t> &Weights) {
  852. MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
  853. assert(MD);
  854. for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
  855. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
  856. Weights.push_back(CI->getValue().getZExtValue());
  857. }
  858. // If TI is a conditional eq, the default case is the false case,
  859. // and the corresponding branch-weight data is at index 2. We swap the
  860. // default weight to be the first entry.
  861. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  862. assert(Weights.size() == 2);
  863. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  864. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  865. std::swap(Weights.front(), Weights.back());
  866. }
  867. }
  868. /// Keep halving the weights until all can fit in uint32_t.
  869. static void FitWeights(MutableArrayRef<uint64_t> Weights) {
  870. uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
  871. if (Max > UINT_MAX) {
  872. unsigned Offset = 32 - countLeadingZeros(Max);
  873. for (uint64_t &I : Weights)
  874. I >>= Offset;
  875. }
  876. }
  877. /// The specified terminator is a value equality comparison instruction
  878. /// (either a switch or a branch on "X == c").
  879. /// See if any of the predecessors of the terminator block are value comparisons
  880. /// on the same value. If so, and if safe to do so, fold them together.
  881. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
  882. IRBuilder<> &Builder) {
  883. BasicBlock *BB = TI->getParent();
  884. Value *CV = isValueEqualityComparison(TI); // CondVal
  885. assert(CV && "Not a comparison?");
  886. bool Changed = false;
  887. SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
  888. while (!Preds.empty()) {
  889. BasicBlock *Pred = Preds.pop_back_val();
  890. // See if the predecessor is a comparison with the same value.
  891. Instruction *PTI = Pred->getTerminator();
  892. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  893. if (PCV == CV && TI != PTI) {
  894. SmallSetVector<BasicBlock*, 4> FailBlocks;
  895. if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
  896. for (auto *Succ : FailBlocks) {
  897. if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
  898. return false;
  899. }
  900. }
  901. // Figure out which 'cases' to copy from SI to PSI.
  902. std::vector<ValueEqualityComparisonCase> BBCases;
  903. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  904. std::vector<ValueEqualityComparisonCase> PredCases;
  905. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  906. // Based on whether the default edge from PTI goes to BB or not, fill in
  907. // PredCases and PredDefault with the new switch cases we would like to
  908. // build.
  909. SmallVector<BasicBlock *, 8> NewSuccessors;
  910. // Update the branch weight metadata along the way
  911. SmallVector<uint64_t, 8> Weights;
  912. bool PredHasWeights = HasBranchWeights(PTI);
  913. bool SuccHasWeights = HasBranchWeights(TI);
  914. if (PredHasWeights) {
  915. GetBranchWeights(PTI, Weights);
  916. // branch-weight metadata is inconsistent here.
  917. if (Weights.size() != 1 + PredCases.size())
  918. PredHasWeights = SuccHasWeights = false;
  919. } else if (SuccHasWeights)
  920. // If there are no predecessor weights but there are successor weights,
  921. // populate Weights with 1, which will later be scaled to the sum of
  922. // successor's weights
  923. Weights.assign(1 + PredCases.size(), 1);
  924. SmallVector<uint64_t, 8> SuccWeights;
  925. if (SuccHasWeights) {
  926. GetBranchWeights(TI, SuccWeights);
  927. // branch-weight metadata is inconsistent here.
  928. if (SuccWeights.size() != 1 + BBCases.size())
  929. PredHasWeights = SuccHasWeights = false;
  930. } else if (PredHasWeights)
  931. SuccWeights.assign(1 + BBCases.size(), 1);
  932. if (PredDefault == BB) {
  933. // If this is the default destination from PTI, only the edges in TI
  934. // that don't occur in PTI, or that branch to BB will be activated.
  935. std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
  936. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  937. if (PredCases[i].Dest != BB)
  938. PTIHandled.insert(PredCases[i].Value);
  939. else {
  940. // The default destination is BB, we don't need explicit targets.
  941. std::swap(PredCases[i], PredCases.back());
  942. if (PredHasWeights || SuccHasWeights) {
  943. // Increase weight for the default case.
  944. Weights[0] += Weights[i + 1];
  945. std::swap(Weights[i + 1], Weights.back());
  946. Weights.pop_back();
  947. }
  948. PredCases.pop_back();
  949. --i;
  950. --e;
  951. }
  952. // Reconstruct the new switch statement we will be building.
  953. if (PredDefault != BBDefault) {
  954. PredDefault->removePredecessor(Pred);
  955. PredDefault = BBDefault;
  956. NewSuccessors.push_back(BBDefault);
  957. }
  958. unsigned CasesFromPred = Weights.size();
  959. uint64_t ValidTotalSuccWeight = 0;
  960. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  961. if (!PTIHandled.count(BBCases[i].Value) &&
  962. BBCases[i].Dest != BBDefault) {
  963. PredCases.push_back(BBCases[i]);
  964. NewSuccessors.push_back(BBCases[i].Dest);
  965. if (SuccHasWeights || PredHasWeights) {
  966. // The default weight is at index 0, so weight for the ith case
  967. // should be at index i+1. Scale the cases from successor by
  968. // PredDefaultWeight (Weights[0]).
  969. Weights.push_back(Weights[0] * SuccWeights[i + 1]);
  970. ValidTotalSuccWeight += SuccWeights[i + 1];
  971. }
  972. }
  973. if (SuccHasWeights || PredHasWeights) {
  974. ValidTotalSuccWeight += SuccWeights[0];
  975. // Scale the cases from predecessor by ValidTotalSuccWeight.
  976. for (unsigned i = 1; i < CasesFromPred; ++i)
  977. Weights[i] *= ValidTotalSuccWeight;
  978. // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
  979. Weights[0] *= SuccWeights[0];
  980. }
  981. } else {
  982. // If this is not the default destination from PSI, only the edges
  983. // in SI that occur in PSI with a destination of BB will be
  984. // activated.
  985. std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
  986. std::map<ConstantInt *, uint64_t> WeightsForHandled;
  987. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  988. if (PredCases[i].Dest == BB) {
  989. PTIHandled.insert(PredCases[i].Value);
  990. if (PredHasWeights || SuccHasWeights) {
  991. WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
  992. std::swap(Weights[i + 1], Weights.back());
  993. Weights.pop_back();
  994. }
  995. std::swap(PredCases[i], PredCases.back());
  996. PredCases.pop_back();
  997. --i;
  998. --e;
  999. }
  1000. // Okay, now we know which constants were sent to BB from the
  1001. // predecessor. Figure out where they will all go now.
  1002. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  1003. if (PTIHandled.count(BBCases[i].Value)) {
  1004. // If this is one we are capable of getting...
  1005. if (PredHasWeights || SuccHasWeights)
  1006. Weights.push_back(WeightsForHandled[BBCases[i].Value]);
  1007. PredCases.push_back(BBCases[i]);
  1008. NewSuccessors.push_back(BBCases[i].Dest);
  1009. PTIHandled.erase(
  1010. BBCases[i].Value); // This constant is taken care of
  1011. }
  1012. // If there are any constants vectored to BB that TI doesn't handle,
  1013. // they must go to the default destination of TI.
  1014. for (ConstantInt *I : PTIHandled) {
  1015. if (PredHasWeights || SuccHasWeights)
  1016. Weights.push_back(WeightsForHandled[I]);
  1017. PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
  1018. NewSuccessors.push_back(BBDefault);
  1019. }
  1020. }
  1021. // Okay, at this point, we know which new successor Pred will get. Make
  1022. // sure we update the number of entries in the PHI nodes for these
  1023. // successors.
  1024. for (BasicBlock *NewSuccessor : NewSuccessors)
  1025. AddPredecessorToBlock(NewSuccessor, Pred, BB);
  1026. Builder.SetInsertPoint(PTI);
  1027. // Convert pointer to int before we switch.
  1028. if (CV->getType()->isPointerTy()) {
  1029. CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
  1030. "magicptr");
  1031. }
  1032. // Now that the successors are updated, create the new Switch instruction.
  1033. SwitchInst *NewSI =
  1034. Builder.CreateSwitch(CV, PredDefault, PredCases.size());
  1035. NewSI->setDebugLoc(PTI->getDebugLoc());
  1036. for (ValueEqualityComparisonCase &V : PredCases)
  1037. NewSI->addCase(V.Value, V.Dest);
  1038. if (PredHasWeights || SuccHasWeights) {
  1039. // Halve the weights if any of them cannot fit in an uint32_t
  1040. FitWeights(Weights);
  1041. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  1042. setBranchWeights(NewSI, MDWeights);
  1043. }
  1044. EraseTerminatorAndDCECond(PTI);
  1045. // Okay, last check. If BB is still a successor of PSI, then we must
  1046. // have an infinite loop case. If so, add an infinitely looping block
  1047. // to handle the case to preserve the behavior of the code.
  1048. BasicBlock *InfLoopBlock = nullptr;
  1049. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  1050. if (NewSI->getSuccessor(i) == BB) {
  1051. if (!InfLoopBlock) {
  1052. // Insert it at the end of the function, because it's either code,
  1053. // or it won't matter if it's hot. :)
  1054. InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
  1055. BB->getParent());
  1056. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  1057. }
  1058. NewSI->setSuccessor(i, InfLoopBlock);
  1059. }
  1060. Changed = true;
  1061. }
  1062. }
  1063. return Changed;
  1064. }
  1065. // If we would need to insert a select that uses the value of this invoke
  1066. // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
  1067. // can't hoist the invoke, as there is nowhere to put the select in this case.
  1068. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  1069. Instruction *I1, Instruction *I2) {
  1070. for (BasicBlock *Succ : successors(BB1)) {
  1071. for (const PHINode &PN : Succ->phis()) {
  1072. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1073. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1074. if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
  1075. return false;
  1076. }
  1077. }
  1078. }
  1079. return true;
  1080. }
  1081. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
  1082. /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
  1083. /// in the two blocks up into the branch block. The caller of this function
  1084. /// guarantees that BI's block dominates BB1 and BB2.
  1085. static bool HoistThenElseCodeToIf(BranchInst *BI,
  1086. const TargetTransformInfo &TTI) {
  1087. // This does very trivial matching, with limited scanning, to find identical
  1088. // instructions in the two blocks. In particular, we don't want to get into
  1089. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  1090. // such, we currently just scan for obviously identical instructions in an
  1091. // identical order.
  1092. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  1093. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  1094. BasicBlock::iterator BB1_Itr = BB1->begin();
  1095. BasicBlock::iterator BB2_Itr = BB2->begin();
  1096. Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
  1097. // Skip debug info if it is not identical.
  1098. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  1099. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  1100. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  1101. while (isa<DbgInfoIntrinsic>(I1))
  1102. I1 = &*BB1_Itr++;
  1103. while (isa<DbgInfoIntrinsic>(I2))
  1104. I2 = &*BB2_Itr++;
  1105. }
  1106. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  1107. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
  1108. return false;
  1109. BasicBlock *BIParent = BI->getParent();
  1110. bool Changed = false;
  1111. do {
  1112. // If we are hoisting the terminator instruction, don't move one (making a
  1113. // broken BB), instead clone it, and remove BI.
  1114. if (I1->isTerminator())
  1115. goto HoistTerminator;
  1116. // If we're going to hoist a call, make sure that the two instructions we're
  1117. // commoning/hoisting are both marked with musttail, or neither of them is
  1118. // marked as such. Otherwise, we might end up in a situation where we hoist
  1119. // from a block where the terminator is a `ret` to a block where the terminator
  1120. // is a `br`, and `musttail` calls expect to be followed by a return.
  1121. auto *C1 = dyn_cast<CallInst>(I1);
  1122. auto *C2 = dyn_cast<CallInst>(I2);
  1123. if (C1 && C2)
  1124. if (C1->isMustTailCall() != C2->isMustTailCall())
  1125. return Changed;
  1126. if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
  1127. return Changed;
  1128. if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
  1129. assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
  1130. // The debug location is an integral part of a debug info intrinsic
  1131. // and can't be separated from it or replaced. Instead of attempting
  1132. // to merge locations, simply hoist both copies of the intrinsic.
  1133. BIParent->getInstList().splice(BI->getIterator(),
  1134. BB1->getInstList(), I1);
  1135. BIParent->getInstList().splice(BI->getIterator(),
  1136. BB2->getInstList(), I2);
  1137. Changed = true;
  1138. } else {
  1139. // For a normal instruction, we just move one to right before the branch,
  1140. // then replace all uses of the other with the first. Finally, we remove
  1141. // the now redundant second instruction.
  1142. BIParent->getInstList().splice(BI->getIterator(),
  1143. BB1->getInstList(), I1);
  1144. if (!I2->use_empty())
  1145. I2->replaceAllUsesWith(I1);
  1146. I1->andIRFlags(I2);
  1147. unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
  1148. LLVMContext::MD_range,
  1149. LLVMContext::MD_fpmath,
  1150. LLVMContext::MD_invariant_load,
  1151. LLVMContext::MD_nonnull,
  1152. LLVMContext::MD_invariant_group,
  1153. LLVMContext::MD_align,
  1154. LLVMContext::MD_dereferenceable,
  1155. LLVMContext::MD_dereferenceable_or_null,
  1156. LLVMContext::MD_mem_parallel_loop_access};
  1157. combineMetadata(I1, I2, KnownIDs, true);
  1158. // I1 and I2 are being combined into a single instruction. Its debug
  1159. // location is the merged locations of the original instructions.
  1160. I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
  1161. I2->eraseFromParent();
  1162. Changed = true;
  1163. }
  1164. I1 = &*BB1_Itr++;
  1165. I2 = &*BB2_Itr++;
  1166. // Skip debug info if it is not identical.
  1167. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  1168. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  1169. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  1170. while (isa<DbgInfoIntrinsic>(I1))
  1171. I1 = &*BB1_Itr++;
  1172. while (isa<DbgInfoIntrinsic>(I2))
  1173. I2 = &*BB2_Itr++;
  1174. }
  1175. } while (I1->isIdenticalToWhenDefined(I2));
  1176. return true;
  1177. HoistTerminator:
  1178. // It may not be possible to hoist an invoke.
  1179. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  1180. return Changed;
  1181. for (BasicBlock *Succ : successors(BB1)) {
  1182. for (PHINode &PN : Succ->phis()) {
  1183. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1184. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1185. if (BB1V == BB2V)
  1186. continue;
  1187. // Check for passingValueIsAlwaysUndefined here because we would rather
  1188. // eliminate undefined control flow then converting it to a select.
  1189. if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
  1190. passingValueIsAlwaysUndefined(BB2V, &PN))
  1191. return Changed;
  1192. if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
  1193. return Changed;
  1194. if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
  1195. return Changed;
  1196. }
  1197. }
  1198. // Okay, it is safe to hoist the terminator.
  1199. Instruction *NT = I1->clone();
  1200. BIParent->getInstList().insert(BI->getIterator(), NT);
  1201. if (!NT->getType()->isVoidTy()) {
  1202. I1->replaceAllUsesWith(NT);
  1203. I2->replaceAllUsesWith(NT);
  1204. NT->takeName(I1);
  1205. }
  1206. IRBuilder<NoFolder> Builder(NT);
  1207. // Hoisting one of the terminators from our successor is a great thing.
  1208. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  1209. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  1210. // nodes, so we insert select instruction to compute the final result.
  1211. std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
  1212. for (BasicBlock *Succ : successors(BB1)) {
  1213. for (PHINode &PN : Succ->phis()) {
  1214. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1215. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1216. if (BB1V == BB2V)
  1217. continue;
  1218. // These values do not agree. Insert a select instruction before NT
  1219. // that determines the right value.
  1220. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  1221. if (!SI)
  1222. SI = cast<SelectInst>(
  1223. Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  1224. BB1V->getName() + "." + BB2V->getName(), BI));
  1225. // Make the PHI node use the select for all incoming values for BB1/BB2
  1226. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
  1227. if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
  1228. PN.setIncomingValue(i, SI);
  1229. }
  1230. }
  1231. // Update any PHI nodes in our new successors.
  1232. for (BasicBlock *Succ : successors(BB1))
  1233. AddPredecessorToBlock(Succ, BIParent, BB1);
  1234. EraseTerminatorAndDCECond(BI);
  1235. return true;
  1236. }
  1237. // All instructions in Insts belong to different blocks that all unconditionally
  1238. // branch to a common successor. Analyze each instruction and return true if it
  1239. // would be possible to sink them into their successor, creating one common
  1240. // instruction instead. For every value that would be required to be provided by
  1241. // PHI node (because an operand varies in each input block), add to PHIOperands.
  1242. static bool canSinkInstructions(
  1243. ArrayRef<Instruction *> Insts,
  1244. DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
  1245. // Prune out obviously bad instructions to move. Any non-store instruction
  1246. // must have exactly one use, and we check later that use is by a single,
  1247. // common PHI instruction in the successor.
  1248. for (auto *I : Insts) {
  1249. // These instructions may change or break semantics if moved.
  1250. if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
  1251. I->getType()->isTokenTy())
  1252. return false;
  1253. // Conservatively return false if I is an inline-asm instruction. Sinking
  1254. // and merging inline-asm instructions can potentially create arguments
  1255. // that cannot satisfy the inline-asm constraints.
  1256. if (const auto *C = dyn_cast<CallInst>(I))
  1257. if (C->isInlineAsm())
  1258. return false;
  1259. // Everything must have only one use too, apart from stores which
  1260. // have no uses.
  1261. if (!isa<StoreInst>(I) && !I->hasOneUse())
  1262. return false;
  1263. }
  1264. const Instruction *I0 = Insts.front();
  1265. for (auto *I : Insts)
  1266. if (!I->isSameOperationAs(I0))
  1267. return false;
  1268. // All instructions in Insts are known to be the same opcode. If they aren't
  1269. // stores, check the only user of each is a PHI or in the same block as the
  1270. // instruction, because if a user is in the same block as an instruction
  1271. // we're contemplating sinking, it must already be determined to be sinkable.
  1272. if (!isa<StoreInst>(I0)) {
  1273. auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
  1274. auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
  1275. if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
  1276. auto *U = cast<Instruction>(*I->user_begin());
  1277. return (PNUse &&
  1278. PNUse->getParent() == Succ &&
  1279. PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
  1280. U->getParent() == I->getParent();
  1281. }))
  1282. return false;
  1283. }
  1284. // Because SROA can't handle speculating stores of selects, try not
  1285. // to sink loads or stores of allocas when we'd have to create a PHI for
  1286. // the address operand. Also, because it is likely that loads or stores
  1287. // of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
  1288. // This can cause code churn which can have unintended consequences down
  1289. // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
  1290. // FIXME: This is a workaround for a deficiency in SROA - see
  1291. // https://llvm.org/bugs/show_bug.cgi?id=30188
  1292. if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
  1293. return isa<AllocaInst>(I->getOperand(1));
  1294. }))
  1295. return false;
  1296. if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
  1297. return isa<AllocaInst>(I->getOperand(0));
  1298. }))
  1299. return false;
  1300. for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
  1301. if (I0->getOperand(OI)->getType()->isTokenTy())
  1302. // Don't touch any operand of token type.
  1303. return false;
  1304. auto SameAsI0 = [&I0, OI](const Instruction *I) {
  1305. assert(I->getNumOperands() == I0->getNumOperands());
  1306. return I->getOperand(OI) == I0->getOperand(OI);
  1307. };
  1308. if (!all_of(Insts, SameAsI0)) {
  1309. if (!canReplaceOperandWithVariable(I0, OI))
  1310. // We can't create a PHI from this GEP.
  1311. return false;
  1312. // Don't create indirect calls! The called value is the final operand.
  1313. if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
  1314. // FIXME: if the call was *already* indirect, we should do this.
  1315. return false;
  1316. }
  1317. for (auto *I : Insts)
  1318. PHIOperands[I].push_back(I->getOperand(OI));
  1319. }
  1320. }
  1321. return true;
  1322. }
  1323. // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
  1324. // instruction of every block in Blocks to their common successor, commoning
  1325. // into one instruction.
  1326. static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
  1327. auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
  1328. // canSinkLastInstruction returning true guarantees that every block has at
  1329. // least one non-terminator instruction.
  1330. SmallVector<Instruction*,4> Insts;
  1331. for (auto *BB : Blocks) {
  1332. Instruction *I = BB->getTerminator();
  1333. do {
  1334. I = I->getPrevNode();
  1335. } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
  1336. if (!isa<DbgInfoIntrinsic>(I))
  1337. Insts.push_back(I);
  1338. }
  1339. // The only checking we need to do now is that all users of all instructions
  1340. // are the same PHI node. canSinkLastInstruction should have checked this but
  1341. // it is slightly over-aggressive - it gets confused by commutative instructions
  1342. // so double-check it here.
  1343. Instruction *I0 = Insts.front();
  1344. if (!isa<StoreInst>(I0)) {
  1345. auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
  1346. if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
  1347. auto *U = cast<Instruction>(*I->user_begin());
  1348. return U == PNUse;
  1349. }))
  1350. return false;
  1351. }
  1352. // We don't need to do any more checking here; canSinkLastInstruction should
  1353. // have done it all for us.
  1354. SmallVector<Value*, 4> NewOperands;
  1355. for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
  1356. // This check is different to that in canSinkLastInstruction. There, we
  1357. // cared about the global view once simplifycfg (and instcombine) have
  1358. // completed - it takes into account PHIs that become trivially
  1359. // simplifiable. However here we need a more local view; if an operand
  1360. // differs we create a PHI and rely on instcombine to clean up the very
  1361. // small mess we may make.
  1362. bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
  1363. return I->getOperand(O) != I0->getOperand(O);
  1364. });
  1365. if (!NeedPHI) {
  1366. NewOperands.push_back(I0->getOperand(O));
  1367. continue;
  1368. }
  1369. // Create a new PHI in the successor block and populate it.
  1370. auto *Op = I0->getOperand(O);
  1371. assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
  1372. auto *PN = PHINode::Create(Op->getType(), Insts.size(),
  1373. Op->getName() + ".sink", &BBEnd->front());
  1374. for (auto *I : Insts)
  1375. PN->addIncoming(I->getOperand(O), I->getParent());
  1376. NewOperands.push_back(PN);
  1377. }
  1378. // Arbitrarily use I0 as the new "common" instruction; remap its operands
  1379. // and move it to the start of the successor block.
  1380. for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
  1381. I0->getOperandUse(O).set(NewOperands[O]);
  1382. I0->moveBefore(&*BBEnd->getFirstInsertionPt());
  1383. // Update metadata and IR flags, and merge debug locations.
  1384. for (auto *I : Insts)
  1385. if (I != I0) {
  1386. // The debug location for the "common" instruction is the merged locations
  1387. // of all the commoned instructions. We start with the original location
  1388. // of the "common" instruction and iteratively merge each location in the
  1389. // loop below.
  1390. // This is an N-way merge, which will be inefficient if I0 is a CallInst.
  1391. // However, as N-way merge for CallInst is rare, so we use simplified API
  1392. // instead of using complex API for N-way merge.
  1393. I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
  1394. combineMetadataForCSE(I0, I, true);
  1395. I0->andIRFlags(I);
  1396. }
  1397. if (!isa<StoreInst>(I0)) {
  1398. // canSinkLastInstruction checked that all instructions were used by
  1399. // one and only one PHI node. Find that now, RAUW it to our common
  1400. // instruction and nuke it.
  1401. assert(I0->hasOneUse());
  1402. auto *PN = cast<PHINode>(*I0->user_begin());
  1403. PN->replaceAllUsesWith(I0);
  1404. PN->eraseFromParent();
  1405. }
  1406. // Finally nuke all instructions apart from the common instruction.
  1407. for (auto *I : Insts)
  1408. if (I != I0)
  1409. I->eraseFromParent();
  1410. return true;
  1411. }
  1412. namespace {
  1413. // LockstepReverseIterator - Iterates through instructions
  1414. // in a set of blocks in reverse order from the first non-terminator.
  1415. // For example (assume all blocks have size n):
  1416. // LockstepReverseIterator I([B1, B2, B3]);
  1417. // *I-- = [B1[n], B2[n], B3[n]];
  1418. // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
  1419. // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
  1420. // ...
  1421. class LockstepReverseIterator {
  1422. ArrayRef<BasicBlock*> Blocks;
  1423. SmallVector<Instruction*,4> Insts;
  1424. bool Fail;
  1425. public:
  1426. LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
  1427. reset();
  1428. }
  1429. void reset() {
  1430. Fail = false;
  1431. Insts.clear();
  1432. for (auto *BB : Blocks) {
  1433. Instruction *Inst = BB->getTerminator();
  1434. for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
  1435. Inst = Inst->getPrevNode();
  1436. if (!Inst) {
  1437. // Block wasn't big enough.
  1438. Fail = true;
  1439. return;
  1440. }
  1441. Insts.push_back(Inst);
  1442. }
  1443. }
  1444. bool isValid() const {
  1445. return !Fail;
  1446. }
  1447. void operator--() {
  1448. if (Fail)
  1449. return;
  1450. for (auto *&Inst : Insts) {
  1451. for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
  1452. Inst = Inst->getPrevNode();
  1453. // Already at beginning of block.
  1454. if (!Inst) {
  1455. Fail = true;
  1456. return;
  1457. }
  1458. }
  1459. }
  1460. ArrayRef<Instruction*> operator * () const {
  1461. return Insts;
  1462. }
  1463. };
  1464. } // end anonymous namespace
  1465. /// Check whether BB's predecessors end with unconditional branches. If it is
  1466. /// true, sink any common code from the predecessors to BB.
  1467. /// We also allow one predecessor to end with conditional branch (but no more
  1468. /// than one).
  1469. static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) {
  1470. // We support two situations:
  1471. // (1) all incoming arcs are unconditional
  1472. // (2) one incoming arc is conditional
  1473. //
  1474. // (2) is very common in switch defaults and
  1475. // else-if patterns;
  1476. //
  1477. // if (a) f(1);
  1478. // else if (b) f(2);
  1479. //
  1480. // produces:
  1481. //
  1482. // [if]
  1483. // / \
  1484. // [f(1)] [if]
  1485. // | | \
  1486. // | | |
  1487. // | [f(2)]|
  1488. // \ | /
  1489. // [ end ]
  1490. //
  1491. // [end] has two unconditional predecessor arcs and one conditional. The
  1492. // conditional refers to the implicit empty 'else' arc. This conditional
  1493. // arc can also be caused by an empty default block in a switch.
  1494. //
  1495. // In this case, we attempt to sink code from all *unconditional* arcs.
  1496. // If we can sink instructions from these arcs (determined during the scan
  1497. // phase below) we insert a common successor for all unconditional arcs and
  1498. // connect that to [end], to enable sinking:
  1499. //
  1500. // [if]
  1501. // / \
  1502. // [x(1)] [if]
  1503. // | | \
  1504. // | | \
  1505. // | [x(2)] |
  1506. // \ / |
  1507. // [sink.split] |
  1508. // \ /
  1509. // [ end ]
  1510. //
  1511. SmallVector<BasicBlock*,4> UnconditionalPreds;
  1512. Instruction *Cond = nullptr;
  1513. for (auto *B : predecessors(BB)) {
  1514. auto *T = B->getTerminator();
  1515. if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
  1516. UnconditionalPreds.push_back(B);
  1517. else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
  1518. Cond = T;
  1519. else
  1520. return false;
  1521. }
  1522. if (UnconditionalPreds.size() < 2)
  1523. return false;
  1524. bool Changed = false;
  1525. // We take a two-step approach to tail sinking. First we scan from the end of
  1526. // each block upwards in lockstep. If the n'th instruction from the end of each
  1527. // block can be sunk, those instructions are added to ValuesToSink and we
  1528. // carry on. If we can sink an instruction but need to PHI-merge some operands
  1529. // (because they're not identical in each instruction) we add these to
  1530. // PHIOperands.
  1531. unsigned ScanIdx = 0;
  1532. SmallPtrSet<Value*,4> InstructionsToSink;
  1533. DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
  1534. LockstepReverseIterator LRI(UnconditionalPreds);
  1535. while (LRI.isValid() &&
  1536. canSinkInstructions(*LRI, PHIOperands)) {
  1537. LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
  1538. << "\n");
  1539. InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
  1540. ++ScanIdx;
  1541. --LRI;
  1542. }
  1543. auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
  1544. unsigned NumPHIdValues = 0;
  1545. for (auto *I : *LRI)
  1546. for (auto *V : PHIOperands[I])
  1547. if (InstructionsToSink.count(V) == 0)
  1548. ++NumPHIdValues;
  1549. LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
  1550. unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
  1551. if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
  1552. NumPHIInsts++;
  1553. return NumPHIInsts <= 1;
  1554. };
  1555. if (ScanIdx > 0 && Cond) {
  1556. // Check if we would actually sink anything first! This mutates the CFG and
  1557. // adds an extra block. The goal in doing this is to allow instructions that
  1558. // couldn't be sunk before to be sunk - obviously, speculatable instructions
  1559. // (such as trunc, add) can be sunk and predicated already. So we check that
  1560. // we're going to sink at least one non-speculatable instruction.
  1561. LRI.reset();
  1562. unsigned Idx = 0;
  1563. bool Profitable = false;
  1564. while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
  1565. if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
  1566. Profitable = true;
  1567. break;
  1568. }
  1569. --LRI;
  1570. ++Idx;
  1571. }
  1572. if (!Profitable)
  1573. return false;
  1574. LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
  1575. // We have a conditional edge and we're going to sink some instructions.
  1576. // Insert a new block postdominating all blocks we're going to sink from.
  1577. if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split"))
  1578. // Edges couldn't be split.
  1579. return false;
  1580. Changed = true;
  1581. }
  1582. // Now that we've analyzed all potential sinking candidates, perform the
  1583. // actual sink. We iteratively sink the last non-terminator of the source
  1584. // blocks into their common successor unless doing so would require too
  1585. // many PHI instructions to be generated (currently only one PHI is allowed
  1586. // per sunk instruction).
  1587. //
  1588. // We can use InstructionsToSink to discount values needing PHI-merging that will
  1589. // actually be sunk in a later iteration. This allows us to be more
  1590. // aggressive in what we sink. This does allow a false positive where we
  1591. // sink presuming a later value will also be sunk, but stop half way through
  1592. // and never actually sink it which means we produce more PHIs than intended.
  1593. // This is unlikely in practice though.
  1594. for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
  1595. LLVM_DEBUG(dbgs() << "SINK: Sink: "
  1596. << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
  1597. << "\n");
  1598. // Because we've sunk every instruction in turn, the current instruction to
  1599. // sink is always at index 0.
  1600. LRI.reset();
  1601. if (!ProfitableToSinkInstruction(LRI)) {
  1602. // Too many PHIs would be created.
  1603. LLVM_DEBUG(
  1604. dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
  1605. break;
  1606. }
  1607. if (!sinkLastInstruction(UnconditionalPreds))
  1608. return Changed;
  1609. NumSinkCommons++;
  1610. Changed = true;
  1611. }
  1612. return Changed;
  1613. }
  1614. /// Determine if we can hoist sink a sole store instruction out of a
  1615. /// conditional block.
  1616. ///
  1617. /// We are looking for code like the following:
  1618. /// BrBB:
  1619. /// store i32 %add, i32* %arrayidx2
  1620. /// ... // No other stores or function calls (we could be calling a memory
  1621. /// ... // function).
  1622. /// %cmp = icmp ult %x, %y
  1623. /// br i1 %cmp, label %EndBB, label %ThenBB
  1624. /// ThenBB:
  1625. /// store i32 %add5, i32* %arrayidx2
  1626. /// br label EndBB
  1627. /// EndBB:
  1628. /// ...
  1629. /// We are going to transform this into:
  1630. /// BrBB:
  1631. /// store i32 %add, i32* %arrayidx2
  1632. /// ... //
  1633. /// %cmp = icmp ult %x, %y
  1634. /// %add.add5 = select i1 %cmp, i32 %add, %add5
  1635. /// store i32 %add.add5, i32* %arrayidx2
  1636. /// ...
  1637. ///
  1638. /// \return The pointer to the value of the previous store if the store can be
  1639. /// hoisted into the predecessor block. 0 otherwise.
  1640. static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
  1641. BasicBlock *StoreBB, BasicBlock *EndBB) {
  1642. StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
  1643. if (!StoreToHoist)
  1644. return nullptr;
  1645. // Volatile or atomic.
  1646. if (!StoreToHoist->isSimple())
  1647. return nullptr;
  1648. Value *StorePtr = StoreToHoist->getPointerOperand();
  1649. // Look for a store to the same pointer in BrBB.
  1650. unsigned MaxNumInstToLookAt = 9;
  1651. for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) {
  1652. if (!MaxNumInstToLookAt)
  1653. break;
  1654. --MaxNumInstToLookAt;
  1655. // Could be calling an instruction that affects memory like free().
  1656. if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
  1657. return nullptr;
  1658. if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
  1659. // Found the previous store make sure it stores to the same location.
  1660. if (SI->getPointerOperand() == StorePtr)
  1661. // Found the previous store, return its value operand.
  1662. return SI->getValueOperand();
  1663. return nullptr; // Unknown store.
  1664. }
  1665. }
  1666. return nullptr;
  1667. }
  1668. /// Speculate a conditional basic block flattening the CFG.
  1669. ///
  1670. /// Note that this is a very risky transform currently. Speculating
  1671. /// instructions like this is most often not desirable. Instead, there is an MI
  1672. /// pass which can do it with full awareness of the resource constraints.
  1673. /// However, some cases are "obvious" and we should do directly. An example of
  1674. /// this is speculating a single, reasonably cheap instruction.
  1675. ///
  1676. /// There is only one distinct advantage to flattening the CFG at the IR level:
  1677. /// it makes very common but simplistic optimizations such as are common in
  1678. /// instcombine and the DAG combiner more powerful by removing CFG edges and
  1679. /// modeling their effects with easier to reason about SSA value graphs.
  1680. ///
  1681. ///
  1682. /// An illustration of this transform is turning this IR:
  1683. /// \code
  1684. /// BB:
  1685. /// %cmp = icmp ult %x, %y
  1686. /// br i1 %cmp, label %EndBB, label %ThenBB
  1687. /// ThenBB:
  1688. /// %sub = sub %x, %y
  1689. /// br label BB2
  1690. /// EndBB:
  1691. /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
  1692. /// ...
  1693. /// \endcode
  1694. ///
  1695. /// Into this IR:
  1696. /// \code
  1697. /// BB:
  1698. /// %cmp = icmp ult %x, %y
  1699. /// %sub = sub %x, %y
  1700. /// %cond = select i1 %cmp, 0, %sub
  1701. /// ...
  1702. /// \endcode
  1703. ///
  1704. /// \returns true if the conditional block is removed.
  1705. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
  1706. const TargetTransformInfo &TTI) {
  1707. // Be conservative for now. FP select instruction can often be expensive.
  1708. Value *BrCond = BI->getCondition();
  1709. if (isa<FCmpInst>(BrCond))
  1710. return false;
  1711. BasicBlock *BB = BI->getParent();
  1712. BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
  1713. // If ThenBB is actually on the false edge of the conditional branch, remember
  1714. // to swap the select operands later.
  1715. bool Invert = false;
  1716. if (ThenBB != BI->getSuccessor(0)) {
  1717. assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
  1718. Invert = true;
  1719. }
  1720. assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
  1721. // Keep a count of how many times instructions are used within ThenBB when
  1722. // they are candidates for sinking into ThenBB. Specifically:
  1723. // - They are defined in BB, and
  1724. // - They have no side effects, and
  1725. // - All of their uses are in ThenBB.
  1726. SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
  1727. SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
  1728. unsigned SpeculationCost = 0;
  1729. Value *SpeculatedStoreValue = nullptr;
  1730. StoreInst *SpeculatedStore = nullptr;
  1731. for (BasicBlock::iterator BBI = ThenBB->begin(),
  1732. BBE = std::prev(ThenBB->end());
  1733. BBI != BBE; ++BBI) {
  1734. Instruction *I = &*BBI;
  1735. // Skip debug info.
  1736. if (isa<DbgInfoIntrinsic>(I)) {
  1737. SpeculatedDbgIntrinsics.push_back(I);
  1738. continue;
  1739. }
  1740. // Only speculatively execute a single instruction (not counting the
  1741. // terminator) for now.
  1742. ++SpeculationCost;
  1743. if (SpeculationCost > 1)
  1744. return false;
  1745. // Don't hoist the instruction if it's unsafe or expensive.
  1746. if (!isSafeToSpeculativelyExecute(I) &&
  1747. !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
  1748. I, BB, ThenBB, EndBB))))
  1749. return false;
  1750. if (!SpeculatedStoreValue &&
  1751. ComputeSpeculationCost(I, TTI) >
  1752. PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
  1753. return false;
  1754. // Store the store speculation candidate.
  1755. if (SpeculatedStoreValue)
  1756. SpeculatedStore = cast<StoreInst>(I);
  1757. // Do not hoist the instruction if any of its operands are defined but not
  1758. // used in BB. The transformation will prevent the operand from
  1759. // being sunk into the use block.
  1760. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
  1761. Instruction *OpI = dyn_cast<Instruction>(*i);
  1762. if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
  1763. continue; // Not a candidate for sinking.
  1764. ++SinkCandidateUseCounts[OpI];
  1765. }
  1766. }
  1767. // Consider any sink candidates which are only used in ThenBB as costs for
  1768. // speculation. Note, while we iterate over a DenseMap here, we are summing
  1769. // and so iteration order isn't significant.
  1770. for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
  1771. I = SinkCandidateUseCounts.begin(),
  1772. E = SinkCandidateUseCounts.end();
  1773. I != E; ++I)
  1774. if (I->first->hasNUses(I->second)) {
  1775. ++SpeculationCost;
  1776. if (SpeculationCost > 1)
  1777. return false;
  1778. }
  1779. // Check that the PHI nodes can be converted to selects.
  1780. bool HaveRewritablePHIs = false;
  1781. for (PHINode &PN : EndBB->phis()) {
  1782. Value *OrigV = PN.getIncomingValueForBlock(BB);
  1783. Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
  1784. // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
  1785. // Skip PHIs which are trivial.
  1786. if (ThenV == OrigV)
  1787. continue;
  1788. // Don't convert to selects if we could remove undefined behavior instead.
  1789. if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
  1790. passingValueIsAlwaysUndefined(ThenV, &PN))
  1791. return false;
  1792. HaveRewritablePHIs = true;
  1793. ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
  1794. ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
  1795. if (!OrigCE && !ThenCE)
  1796. continue; // Known safe and cheap.
  1797. if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
  1798. (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
  1799. return false;
  1800. unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
  1801. unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
  1802. unsigned MaxCost =
  1803. 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
  1804. if (OrigCost + ThenCost > MaxCost)
  1805. return false;
  1806. // Account for the cost of an unfolded ConstantExpr which could end up
  1807. // getting expanded into Instructions.
  1808. // FIXME: This doesn't account for how many operations are combined in the
  1809. // constant expression.
  1810. ++SpeculationCost;
  1811. if (SpeculationCost > 1)
  1812. return false;
  1813. }
  1814. // If there are no PHIs to process, bail early. This helps ensure idempotence
  1815. // as well.
  1816. if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
  1817. return false;
  1818. // If we get here, we can hoist the instruction and if-convert.
  1819. LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
  1820. // Insert a select of the value of the speculated store.
  1821. if (SpeculatedStoreValue) {
  1822. IRBuilder<NoFolder> Builder(BI);
  1823. Value *TrueV = SpeculatedStore->getValueOperand();
  1824. Value *FalseV = SpeculatedStoreValue;
  1825. if (Invert)
  1826. std::swap(TrueV, FalseV);
  1827. Value *S = Builder.CreateSelect(
  1828. BrCond, TrueV, FalseV, "spec.store.select", BI);
  1829. SpeculatedStore->setOperand(0, S);
  1830. SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
  1831. SpeculatedStore->getDebugLoc());
  1832. }
  1833. // Metadata can be dependent on the condition we are hoisting above.
  1834. // Conservatively strip all metadata on the instruction.
  1835. for (auto &I : *ThenBB)
  1836. I.dropUnknownNonDebugMetadata();
  1837. // Hoist the instructions.
  1838. BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
  1839. ThenBB->begin(), std::prev(ThenBB->end()));
  1840. // Insert selects and rewrite the PHI operands.
  1841. IRBuilder<NoFolder> Builder(BI);
  1842. for (PHINode &PN : EndBB->phis()) {
  1843. unsigned OrigI = PN.getBasicBlockIndex(BB);
  1844. unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
  1845. Value *OrigV = PN.getIncomingValue(OrigI);
  1846. Value *ThenV = PN.getIncomingValue(ThenI);
  1847. // Skip PHIs which are trivial.
  1848. if (OrigV == ThenV)
  1849. continue;
  1850. // Create a select whose true value is the speculatively executed value and
  1851. // false value is the preexisting value. Swap them if the branch
  1852. // destinations were inverted.
  1853. Value *TrueV = ThenV, *FalseV = OrigV;
  1854. if (Invert)
  1855. std::swap(TrueV, FalseV);
  1856. Value *V = Builder.CreateSelect(
  1857. BrCond, TrueV, FalseV, "spec.select", BI);
  1858. PN.setIncomingValue(OrigI, V);
  1859. PN.setIncomingValue(ThenI, V);
  1860. }
  1861. // Remove speculated dbg intrinsics.
  1862. // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
  1863. // dbg value for the different flows and inserting it after the select.
  1864. for (Instruction *I : SpeculatedDbgIntrinsics)
  1865. I->eraseFromParent();
  1866. ++NumSpeculations;
  1867. return true;
  1868. }
  1869. /// Return true if we can thread a branch across this block.
  1870. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  1871. unsigned Size = 0;
  1872. for (Instruction &I : BB->instructionsWithoutDebug()) {
  1873. if (Size > 10)
  1874. return false; // Don't clone large BB's.
  1875. ++Size;
  1876. // We can only support instructions that do not define values that are
  1877. // live outside of the current basic block.
  1878. for (User *U : I.users()) {
  1879. Instruction *UI = cast<Instruction>(U);
  1880. if (UI->getParent() != BB || isa<PHINode>(UI))
  1881. return false;
  1882. }
  1883. // Looks ok, continue checking.
  1884. }
  1885. return true;
  1886. }
  1887. /// If we have a conditional branch on a PHI node value that is defined in the
  1888. /// same block as the branch and if any PHI entries are constants, thread edges
  1889. /// corresponding to that entry to be branches to their ultimate destination.
  1890. static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
  1891. AssumptionCache *AC) {
  1892. BasicBlock *BB = BI->getParent();
  1893. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  1894. // NOTE: we currently cannot transform this case if the PHI node is used
  1895. // outside of the block.
  1896. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  1897. return false;
  1898. // Degenerate case of a single entry PHI.
  1899. if (PN->getNumIncomingValues() == 1) {
  1900. FoldSingleEntryPHINodes(PN->getParent());
  1901. return true;
  1902. }
  1903. // Now we know that this block has multiple preds and two succs.
  1904. if (!BlockIsSimpleEnoughToThreadThrough(BB))
  1905. return false;
  1906. // Can't fold blocks that contain noduplicate or convergent calls.
  1907. if (any_of(*BB, [](const Instruction &I) {
  1908. const CallInst *CI = dyn_cast<CallInst>(&I);
  1909. return CI && (CI->cannotDuplicate() || CI->isConvergent());
  1910. }))
  1911. return false;
  1912. // Okay, this is a simple enough basic block. See if any phi values are
  1913. // constants.
  1914. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1915. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1916. if (!CB || !CB->getType()->isIntegerTy(1))
  1917. continue;
  1918. // Okay, we now know that all edges from PredBB should be revectored to
  1919. // branch to RealDest.
  1920. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1921. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1922. if (RealDest == BB)
  1923. continue; // Skip self loops.
  1924. // Skip if the predecessor's terminator is an indirect branch.
  1925. if (isa<IndirectBrInst>(PredBB->getTerminator()))
  1926. continue;
  1927. // The dest block might have PHI nodes, other predecessors and other
  1928. // difficult cases. Instead of being smart about this, just insert a new
  1929. // block that jumps to the destination block, effectively splitting
  1930. // the edge we are about to create.
  1931. BasicBlock *EdgeBB =
  1932. BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
  1933. RealDest->getParent(), RealDest);
  1934. BranchInst::Create(RealDest, EdgeBB);
  1935. // Update PHI nodes.
  1936. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1937. // BB may have instructions that are being threaded over. Clone these
  1938. // instructions into EdgeBB. We know that there will be no uses of the
  1939. // cloned instructions outside of EdgeBB.
  1940. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1941. DenseMap<Value *, Value *> TranslateMap; // Track translated values.
  1942. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1943. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1944. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1945. continue;
  1946. }
  1947. // Clone the instruction.
  1948. Instruction *N = BBI->clone();
  1949. if (BBI->hasName())
  1950. N->setName(BBI->getName() + ".c");
  1951. // Update operands due to translation.
  1952. for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
  1953. DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
  1954. if (PI != TranslateMap.end())
  1955. *i = PI->second;
  1956. }
  1957. // Check for trivial simplification.
  1958. if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
  1959. if (!BBI->use_empty())
  1960. TranslateMap[&*BBI] = V;
  1961. if (!N->mayHaveSideEffects()) {
  1962. N->deleteValue(); // Instruction folded away, don't need actual inst
  1963. N = nullptr;
  1964. }
  1965. } else {
  1966. if (!BBI->use_empty())
  1967. TranslateMap[&*BBI] = N;
  1968. }
  1969. // Insert the new instruction into its new home.
  1970. if (N)
  1971. EdgeBB->getInstList().insert(InsertPt, N);
  1972. // Register the new instruction with the assumption cache if necessary.
  1973. if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
  1974. if (II->getIntrinsicID() == Intrinsic::assume)
  1975. AC->registerAssumption(II);
  1976. }
  1977. // Loop over all of the edges from PredBB to BB, changing them to branch
  1978. // to EdgeBB instead.
  1979. Instruction *PredBBTI = PredBB->getTerminator();
  1980. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1981. if (PredBBTI->getSuccessor(i) == BB) {
  1982. BB->removePredecessor(PredBB);
  1983. PredBBTI->setSuccessor(i, EdgeBB);
  1984. }
  1985. // Recurse, simplifying any other constants.
  1986. return FoldCondBranchOnPHI(BI, DL, AC) || true;
  1987. }
  1988. return false;
  1989. }
  1990. /// Given a BB that starts with the specified two-entry PHI node,
  1991. /// see if we can eliminate it.
  1992. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
  1993. const DataLayout &DL) {
  1994. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1995. // statement", which has a very simple dominance structure. Basically, we
  1996. // are trying to find the condition that is being branched on, which
  1997. // subsequently causes this merge to happen. We really want control
  1998. // dependence information for this check, but simplifycfg can't keep it up
  1999. // to date, and this catches most of the cases we care about anyway.
  2000. BasicBlock *BB = PN->getParent();
  2001. const Function *Fn = BB->getParent();
  2002. if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
  2003. return false;
  2004. BasicBlock *IfTrue, *IfFalse;
  2005. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  2006. if (!IfCond ||
  2007. // Don't bother if the branch will be constant folded trivially.
  2008. isa<ConstantInt>(IfCond))
  2009. return false;
  2010. // Okay, we found that we can merge this two-entry phi node into a select.
  2011. // Doing so would require us to fold *all* two entry phi nodes in this block.
  2012. // At some point this becomes non-profitable (particularly if the target
  2013. // doesn't support cmov's). Only do this transformation if there are two or
  2014. // fewer PHI nodes in this block.
  2015. unsigned NumPhis = 0;
  2016. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  2017. if (NumPhis > 2)
  2018. return false;
  2019. // Loop over the PHI's seeing if we can promote them all to select
  2020. // instructions. While we are at it, keep track of the instructions
  2021. // that need to be moved to the dominating block.
  2022. SmallPtrSet<Instruction *, 4> AggressiveInsts;
  2023. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  2024. MaxCostVal1 = PHINodeFoldingThreshold;
  2025. MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
  2026. MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
  2027. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  2028. PHINode *PN = cast<PHINode>(II++);
  2029. if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
  2030. PN->replaceAllUsesWith(V);
  2031. PN->eraseFromParent();
  2032. continue;
  2033. }
  2034. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
  2035. MaxCostVal0, TTI) ||
  2036. !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
  2037. MaxCostVal1, TTI))
  2038. return false;
  2039. }
  2040. // If we folded the first phi, PN dangles at this point. Refresh it. If
  2041. // we ran out of PHIs then we simplified them all.
  2042. PN = dyn_cast<PHINode>(BB->begin());
  2043. if (!PN)
  2044. return true;
  2045. // Don't fold i1 branches on PHIs which contain binary operators. These can
  2046. // often be turned into switches and other things.
  2047. if (PN->getType()->isIntegerTy(1) &&
  2048. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  2049. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  2050. isa<BinaryOperator>(IfCond)))
  2051. return false;
  2052. // If all PHI nodes are promotable, check to make sure that all instructions
  2053. // in the predecessor blocks can be promoted as well. If not, we won't be able
  2054. // to get rid of the control flow, so it's not worth promoting to select
  2055. // instructions.
  2056. BasicBlock *DomBlock = nullptr;
  2057. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  2058. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  2059. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  2060. IfBlock1 = nullptr;
  2061. } else {
  2062. DomBlock = *pred_begin(IfBlock1);
  2063. for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I)
  2064. if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
  2065. // This is not an aggressive instruction that we can promote.
  2066. // Because of this, we won't be able to get rid of the control flow, so
  2067. // the xform is not worth it.
  2068. return false;
  2069. }
  2070. }
  2071. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  2072. IfBlock2 = nullptr;
  2073. } else {
  2074. DomBlock = *pred_begin(IfBlock2);
  2075. for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I)
  2076. if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
  2077. // This is not an aggressive instruction that we can promote.
  2078. // Because of this, we won't be able to get rid of the control flow, so
  2079. // the xform is not worth it.
  2080. return false;
  2081. }
  2082. }
  2083. LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
  2084. << " T: " << IfTrue->getName()
  2085. << " F: " << IfFalse->getName() << "\n");
  2086. // If we can still promote the PHI nodes after this gauntlet of tests,
  2087. // do all of the PHI's now.
  2088. Instruction *InsertPt = DomBlock->getTerminator();
  2089. IRBuilder<NoFolder> Builder(InsertPt);
  2090. // Move all 'aggressive' instructions, which are defined in the
  2091. // conditional parts of the if's up to the dominating block.
  2092. if (IfBlock1)
  2093. hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1);
  2094. if (IfBlock2)
  2095. hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2);
  2096. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  2097. // Change the PHI node into a select instruction.
  2098. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  2099. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  2100. Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
  2101. PN->replaceAllUsesWith(Sel);
  2102. Sel->takeName(PN);
  2103. PN->eraseFromParent();
  2104. }
  2105. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  2106. // has been flattened. Change DomBlock to jump directly to our new block to
  2107. // avoid other simplifycfg's kicking in on the diamond.
  2108. Instruction *OldTI = DomBlock->getTerminator();
  2109. Builder.SetInsertPoint(OldTI);
  2110. Builder.CreateBr(BB);
  2111. OldTI->eraseFromParent();
  2112. return true;
  2113. }
  2114. /// If we found a conditional branch that goes to two returning blocks,
  2115. /// try to merge them together into one return,
  2116. /// introducing a select if the return values disagree.
  2117. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  2118. IRBuilder<> &Builder) {
  2119. assert(BI->isConditional() && "Must be a conditional branch");
  2120. BasicBlock *TrueSucc = BI->getSuccessor(0);
  2121. BasicBlock *FalseSucc = BI->getSuccessor(1);
  2122. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  2123. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  2124. // Check to ensure both blocks are empty (just a return) or optionally empty
  2125. // with PHI nodes. If there are other instructions, merging would cause extra
  2126. // computation on one path or the other.
  2127. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  2128. return false;
  2129. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  2130. return false;
  2131. Builder.SetInsertPoint(BI);
  2132. // Okay, we found a branch that is going to two return nodes. If
  2133. // there is no return value for this function, just change the
  2134. // branch into a return.
  2135. if (FalseRet->getNumOperands() == 0) {
  2136. TrueSucc->removePredecessor(BI->getParent());
  2137. FalseSucc->removePredecessor(BI->getParent());
  2138. Builder.CreateRetVoid();
  2139. EraseTerminatorAndDCECond(BI);
  2140. return true;
  2141. }
  2142. // Otherwise, figure out what the true and false return values are
  2143. // so we can insert a new select instruction.
  2144. Value *TrueValue = TrueRet->getReturnValue();
  2145. Value *FalseValue = FalseRet->getReturnValue();
  2146. // Unwrap any PHI nodes in the return blocks.
  2147. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  2148. if (TVPN->getParent() == TrueSucc)
  2149. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  2150. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  2151. if (FVPN->getParent() == FalseSucc)
  2152. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  2153. // In order for this transformation to be safe, we must be able to
  2154. // unconditionally execute both operands to the return. This is
  2155. // normally the case, but we could have a potentially-trapping
  2156. // constant expression that prevents this transformation from being
  2157. // safe.
  2158. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  2159. if (TCV->canTrap())
  2160. return false;
  2161. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  2162. if (FCV->canTrap())
  2163. return false;
  2164. // Okay, we collected all the mapped values and checked them for sanity, and
  2165. // defined to really do this transformation. First, update the CFG.
  2166. TrueSucc->removePredecessor(BI->getParent());
  2167. FalseSucc->removePredecessor(BI->getParent());
  2168. // Insert select instructions where needed.
  2169. Value *BrCond = BI->getCondition();
  2170. if (TrueValue) {
  2171. // Insert a select if the results differ.
  2172. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  2173. } else if (isa<UndefValue>(TrueValue)) {
  2174. TrueValue = FalseValue;
  2175. } else {
  2176. TrueValue =
  2177. Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
  2178. }
  2179. }
  2180. Value *RI =
  2181. !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  2182. (void)RI;
  2183. LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  2184. << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: "
  2185. << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
  2186. EraseTerminatorAndDCECond(BI);
  2187. return true;
  2188. }
  2189. /// Return true if the given instruction is available
  2190. /// in its predecessor block. If yes, the instruction will be removed.
  2191. static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) {
  2192. if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
  2193. return false;
  2194. for (Instruction &I : *PB) {
  2195. Instruction *PBI = &I;
  2196. // Check whether Inst and PBI generate the same value.
  2197. if (Inst->isIdenticalTo(PBI)) {
  2198. Inst->replaceAllUsesWith(PBI);
  2199. Inst->eraseFromParent();
  2200. return true;
  2201. }
  2202. }
  2203. return false;
  2204. }
  2205. /// Return true if either PBI or BI has branch weight available, and store
  2206. /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
  2207. /// not have branch weight, use 1:1 as its weight.
  2208. static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
  2209. uint64_t &PredTrueWeight,
  2210. uint64_t &PredFalseWeight,
  2211. uint64_t &SuccTrueWeight,
  2212. uint64_t &SuccFalseWeight) {
  2213. bool PredHasWeights =
  2214. PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
  2215. bool SuccHasWeights =
  2216. BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
  2217. if (PredHasWeights || SuccHasWeights) {
  2218. if (!PredHasWeights)
  2219. PredTrueWeight = PredFalseWeight = 1;
  2220. if (!SuccHasWeights)
  2221. SuccTrueWeight = SuccFalseWeight = 1;
  2222. return true;
  2223. } else {
  2224. return false;
  2225. }
  2226. }
  2227. /// If this basic block is simple enough, and if a predecessor branches to us
  2228. /// and one of our successors, fold the block into the predecessor and use
  2229. /// logical operations to pick the right destination.
  2230. bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
  2231. BasicBlock *BB = BI->getParent();
  2232. const unsigned PredCount = pred_size(BB);
  2233. Instruction *Cond = nullptr;
  2234. if (BI->isConditional())
  2235. Cond = dyn_cast<Instruction>(BI->getCondition());
  2236. else {
  2237. // For unconditional branch, check for a simple CFG pattern, where
  2238. // BB has a single predecessor and BB's successor is also its predecessor's
  2239. // successor. If such pattern exists, check for CSE between BB and its
  2240. // predecessor.
  2241. if (BasicBlock *PB = BB->getSinglePredecessor())
  2242. if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
  2243. if (PBI->isConditional() &&
  2244. (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
  2245. BI->getSuccessor(0) == PBI->getSuccessor(1))) {
  2246. for (auto I = BB->instructionsWithoutDebug().begin(),
  2247. E = BB->instructionsWithoutDebug().end();
  2248. I != E;) {
  2249. Instruction *Curr = &*I++;
  2250. if (isa<CmpInst>(Curr)) {
  2251. Cond = Curr;
  2252. break;
  2253. }
  2254. // Quit if we can't remove this instruction.
  2255. if (!tryCSEWithPredecessor(Curr, PB))
  2256. return false;
  2257. }
  2258. }
  2259. if (!Cond)
  2260. return false;
  2261. }
  2262. if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  2263. Cond->getParent() != BB || !Cond->hasOneUse())
  2264. return false;
  2265. // Make sure the instruction after the condition is the cond branch.
  2266. BasicBlock::iterator CondIt = ++Cond->getIterator();
  2267. // Ignore dbg intrinsics.
  2268. while (isa<DbgInfoIntrinsic>(CondIt))
  2269. ++CondIt;
  2270. if (&*CondIt != BI)
  2271. return false;
  2272. // Only allow this transformation if computing the condition doesn't involve
  2273. // too many instructions and these involved instructions can be executed
  2274. // unconditionally. We denote all involved instructions except the condition
  2275. // as "bonus instructions", and only allow this transformation when the
  2276. // number of the bonus instructions we'll need to create when cloning into
  2277. // each predecessor does not exceed a certain threshold.
  2278. unsigned NumBonusInsts = 0;
  2279. for (auto I = BB->begin(); Cond != &*I; ++I) {
  2280. // Ignore dbg intrinsics.
  2281. if (isa<DbgInfoIntrinsic>(I))
  2282. continue;
  2283. if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
  2284. return false;
  2285. // I has only one use and can be executed unconditionally.
  2286. Instruction *User = dyn_cast<Instruction>(I->user_back());
  2287. if (User == nullptr || User->getParent() != BB)
  2288. return false;
  2289. // I is used in the same BB. Since BI uses Cond and doesn't have more slots
  2290. // to use any other instruction, User must be an instruction between next(I)
  2291. // and Cond.
  2292. // Account for the cost of duplicating this instruction into each
  2293. // predecessor.
  2294. NumBonusInsts += PredCount;
  2295. // Early exits once we reach the limit.
  2296. if (NumBonusInsts > BonusInstThreshold)
  2297. return false;
  2298. }
  2299. // Cond is known to be a compare or binary operator. Check to make sure that
  2300. // neither operand is a potentially-trapping constant expression.
  2301. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  2302. if (CE->canTrap())
  2303. return false;
  2304. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  2305. if (CE->canTrap())
  2306. return false;
  2307. // Finally, don't infinitely unroll conditional loops.
  2308. BasicBlock *TrueDest = BI->getSuccessor(0);
  2309. BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
  2310. if (TrueDest == BB || FalseDest == BB)
  2311. return false;
  2312. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2313. BasicBlock *PredBlock = *PI;
  2314. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  2315. // Check that we have two conditional branches. If there is a PHI node in
  2316. // the common successor, verify that the same value flows in from both
  2317. // blocks.
  2318. SmallVector<PHINode *, 4> PHIs;
  2319. if (!PBI || PBI->isUnconditional() ||
  2320. (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
  2321. (!BI->isConditional() &&
  2322. !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
  2323. continue;
  2324. // Determine if the two branches share a common destination.
  2325. Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
  2326. bool InvertPredCond = false;
  2327. if (BI->isConditional()) {
  2328. if (PBI->getSuccessor(0) == TrueDest) {
  2329. Opc = Instruction::Or;
  2330. } else if (PBI->getSuccessor(1) == FalseDest) {
  2331. Opc = Instruction::And;
  2332. } else if (PBI->getSuccessor(0) == FalseDest) {
  2333. Opc = Instruction::And;
  2334. InvertPredCond = true;
  2335. } else if (PBI->getSuccessor(1) == TrueDest) {
  2336. Opc = Instruction::Or;
  2337. InvertPredCond = true;
  2338. } else {
  2339. continue;
  2340. }
  2341. } else {
  2342. if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
  2343. continue;
  2344. }
  2345. LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  2346. IRBuilder<> Builder(PBI);
  2347. // If we need to invert the condition in the pred block to match, do so now.
  2348. if (InvertPredCond) {
  2349. Value *NewCond = PBI->getCondition();
  2350. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  2351. CmpInst *CI = cast<CmpInst>(NewCond);
  2352. CI->setPredicate(CI->getInversePredicate());
  2353. } else {
  2354. NewCond =
  2355. Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
  2356. }
  2357. PBI->setCondition(NewCond);
  2358. PBI->swapSuccessors();
  2359. }
  2360. // If we have bonus instructions, clone them into the predecessor block.
  2361. // Note that there may be multiple predecessor blocks, so we cannot move
  2362. // bonus instructions to a predecessor block.
  2363. ValueToValueMapTy VMap; // maps original values to cloned values
  2364. // We already make sure Cond is the last instruction before BI. Therefore,
  2365. // all instructions before Cond other than DbgInfoIntrinsic are bonus
  2366. // instructions.
  2367. for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
  2368. if (isa<DbgInfoIntrinsic>(BonusInst))
  2369. continue;
  2370. Instruction *NewBonusInst = BonusInst->clone();
  2371. RemapInstruction(NewBonusInst, VMap,
  2372. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  2373. VMap[&*BonusInst] = NewBonusInst;
  2374. // If we moved a load, we cannot any longer claim any knowledge about
  2375. // its potential value. The previous information might have been valid
  2376. // only given the branch precondition.
  2377. // For an analogous reason, we must also drop all the metadata whose
  2378. // semantics we don't understand.
  2379. NewBonusInst->dropUnknownNonDebugMetadata();
  2380. PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
  2381. NewBonusInst->takeName(&*BonusInst);
  2382. BonusInst->setName(BonusInst->getName() + ".old");
  2383. }
  2384. // Clone Cond into the predecessor basic block, and or/and the
  2385. // two conditions together.
  2386. Instruction *CondInPred = Cond->clone();
  2387. RemapInstruction(CondInPred, VMap,
  2388. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  2389. PredBlock->getInstList().insert(PBI->getIterator(), CondInPred);
  2390. CondInPred->takeName(Cond);
  2391. Cond->setName(CondInPred->getName() + ".old");
  2392. if (BI->isConditional()) {
  2393. Instruction *NewCond = cast<Instruction>(
  2394. Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond"));
  2395. PBI->setCondition(NewCond);
  2396. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2397. bool HasWeights =
  2398. extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
  2399. SuccTrueWeight, SuccFalseWeight);
  2400. SmallVector<uint64_t, 8> NewWeights;
  2401. if (PBI->getSuccessor(0) == BB) {
  2402. if (HasWeights) {
  2403. // PBI: br i1 %x, BB, FalseDest
  2404. // BI: br i1 %y, TrueDest, FalseDest
  2405. // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
  2406. NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
  2407. // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
  2408. // TrueWeight for PBI * FalseWeight for BI.
  2409. // We assume that total weights of a BranchInst can fit into 32 bits.
  2410. // Therefore, we will not have overflow using 64-bit arithmetic.
  2411. NewWeights.push_back(PredFalseWeight *
  2412. (SuccFalseWeight + SuccTrueWeight) +
  2413. PredTrueWeight * SuccFalseWeight);
  2414. }
  2415. AddPredecessorToBlock(TrueDest, PredBlock, BB);
  2416. PBI->setSuccessor(0, TrueDest);
  2417. }
  2418. if (PBI->getSuccessor(1) == BB) {
  2419. if (HasWeights) {
  2420. // PBI: br i1 %x, TrueDest, BB
  2421. // BI: br i1 %y, TrueDest, FalseDest
  2422. // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
  2423. // FalseWeight for PBI * TrueWeight for BI.
  2424. NewWeights.push_back(PredTrueWeight *
  2425. (SuccFalseWeight + SuccTrueWeight) +
  2426. PredFalseWeight * SuccTrueWeight);
  2427. // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
  2428. NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
  2429. }
  2430. AddPredecessorToBlock(FalseDest, PredBlock, BB);
  2431. PBI->setSuccessor(1, FalseDest);
  2432. }
  2433. if (NewWeights.size() == 2) {
  2434. // Halve the weights if any of them cannot fit in an uint32_t
  2435. FitWeights(NewWeights);
  2436. SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
  2437. NewWeights.end());
  2438. setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
  2439. } else
  2440. PBI->setMetadata(LLVMContext::MD_prof, nullptr);
  2441. } else {
  2442. // Update PHI nodes in the common successors.
  2443. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  2444. ConstantInt *PBI_C = cast<ConstantInt>(
  2445. PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
  2446. assert(PBI_C->getType()->isIntegerTy(1));
  2447. Instruction *MergedCond = nullptr;
  2448. if (PBI->getSuccessor(0) == TrueDest) {
  2449. // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
  2450. // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
  2451. // is false: !PBI_Cond and BI_Value
  2452. Instruction *NotCond = cast<Instruction>(
  2453. Builder.CreateNot(PBI->getCondition(), "not.cond"));
  2454. MergedCond = cast<Instruction>(
  2455. Builder.CreateBinOp(Instruction::And, NotCond, CondInPred,
  2456. "and.cond"));
  2457. if (PBI_C->isOne())
  2458. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2459. Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
  2460. } else {
  2461. // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
  2462. // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
  2463. // is false: PBI_Cond and BI_Value
  2464. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2465. Instruction::And, PBI->getCondition(), CondInPred, "and.cond"));
  2466. if (PBI_C->isOne()) {
  2467. Instruction *NotCond = cast<Instruction>(
  2468. Builder.CreateNot(PBI->getCondition(), "not.cond"));
  2469. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2470. Instruction::Or, NotCond, MergedCond, "or.cond"));
  2471. }
  2472. }
  2473. // Update PHI Node.
  2474. PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
  2475. MergedCond);
  2476. }
  2477. // Change PBI from Conditional to Unconditional.
  2478. BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
  2479. EraseTerminatorAndDCECond(PBI);
  2480. PBI = New_PBI;
  2481. }
  2482. // If BI was a loop latch, it may have had associated loop metadata.
  2483. // We need to copy it to the new latch, that is, PBI.
  2484. if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
  2485. PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
  2486. // TODO: If BB is reachable from all paths through PredBlock, then we
  2487. // could replace PBI's branch probabilities with BI's.
  2488. // Copy any debug value intrinsics into the end of PredBlock.
  2489. for (Instruction &I : *BB)
  2490. if (isa<DbgInfoIntrinsic>(I))
  2491. I.clone()->insertBefore(PBI);
  2492. return true;
  2493. }
  2494. return false;
  2495. }
  2496. // If there is only one store in BB1 and BB2, return it, otherwise return
  2497. // nullptr.
  2498. static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
  2499. StoreInst *S = nullptr;
  2500. for (auto *BB : {BB1, BB2}) {
  2501. if (!BB)
  2502. continue;
  2503. for (auto &I : *BB)
  2504. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  2505. if (S)
  2506. // Multiple stores seen.
  2507. return nullptr;
  2508. else
  2509. S = SI;
  2510. }
  2511. }
  2512. return S;
  2513. }
  2514. static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
  2515. Value *AlternativeV = nullptr) {
  2516. // PHI is going to be a PHI node that allows the value V that is defined in
  2517. // BB to be referenced in BB's only successor.
  2518. //
  2519. // If AlternativeV is nullptr, the only value we care about in PHI is V. It
  2520. // doesn't matter to us what the other operand is (it'll never get used). We
  2521. // could just create a new PHI with an undef incoming value, but that could
  2522. // increase register pressure if EarlyCSE/InstCombine can't fold it with some
  2523. // other PHI. So here we directly look for some PHI in BB's successor with V
  2524. // as an incoming operand. If we find one, we use it, else we create a new
  2525. // one.
  2526. //
  2527. // If AlternativeV is not nullptr, we care about both incoming values in PHI.
  2528. // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
  2529. // where OtherBB is the single other predecessor of BB's only successor.
  2530. PHINode *PHI = nullptr;
  2531. BasicBlock *Succ = BB->getSingleSuccessor();
  2532. for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
  2533. if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
  2534. PHI = cast<PHINode>(I);
  2535. if (!AlternativeV)
  2536. break;
  2537. assert(pred_size(Succ) == 2);
  2538. auto PredI = pred_begin(Succ);
  2539. BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
  2540. if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
  2541. break;
  2542. PHI = nullptr;
  2543. }
  2544. if (PHI)
  2545. return PHI;
  2546. // If V is not an instruction defined in BB, just return it.
  2547. if (!AlternativeV &&
  2548. (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
  2549. return V;
  2550. PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
  2551. PHI->addIncoming(V, BB);
  2552. for (BasicBlock *PredBB : predecessors(Succ))
  2553. if (PredBB != BB)
  2554. PHI->addIncoming(
  2555. AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
  2556. return PHI;
  2557. }
  2558. static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
  2559. BasicBlock *QTB, BasicBlock *QFB,
  2560. BasicBlock *PostBB, Value *Address,
  2561. bool InvertPCond, bool InvertQCond,
  2562. const DataLayout &DL) {
  2563. auto IsaBitcastOfPointerType = [](const Instruction &I) {
  2564. return Operator::getOpcode(&I) == Instruction::BitCast &&
  2565. I.getType()->isPointerTy();
  2566. };
  2567. // If we're not in aggressive mode, we only optimize if we have some
  2568. // confidence that by optimizing we'll allow P and/or Q to be if-converted.
  2569. auto IsWorthwhile = [&](BasicBlock *BB) {
  2570. if (!BB)
  2571. return true;
  2572. // Heuristic: if the block can be if-converted/phi-folded and the
  2573. // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
  2574. // thread this store.
  2575. unsigned N = 0;
  2576. for (auto &I : BB->instructionsWithoutDebug()) {
  2577. // Cheap instructions viable for folding.
  2578. if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
  2579. isa<StoreInst>(I))
  2580. ++N;
  2581. // Free instructions.
  2582. else if (I.isTerminator() || IsaBitcastOfPointerType(I))
  2583. continue;
  2584. else
  2585. return false;
  2586. }
  2587. // The store we want to merge is counted in N, so add 1 to make sure
  2588. // we're counting the instructions that would be left.
  2589. return N <= (PHINodeFoldingThreshold + 1);
  2590. };
  2591. if (!MergeCondStoresAggressively &&
  2592. (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
  2593. !IsWorthwhile(QFB)))
  2594. return false;
  2595. // For every pointer, there must be exactly two stores, one coming from
  2596. // PTB or PFB, and the other from QTB or QFB. We don't support more than one
  2597. // store (to any address) in PTB,PFB or QTB,QFB.
  2598. // FIXME: We could relax this restriction with a bit more work and performance
  2599. // testing.
  2600. StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
  2601. StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
  2602. if (!PStore || !QStore)
  2603. return false;
  2604. // Now check the stores are compatible.
  2605. if (!QStore->isUnordered() || !PStore->isUnordered())
  2606. return false;
  2607. // Check that sinking the store won't cause program behavior changes. Sinking
  2608. // the store out of the Q blocks won't change any behavior as we're sinking
  2609. // from a block to its unconditional successor. But we're moving a store from
  2610. // the P blocks down through the middle block (QBI) and past both QFB and QTB.
  2611. // So we need to check that there are no aliasing loads or stores in
  2612. // QBI, QTB and QFB. We also need to check there are no conflicting memory
  2613. // operations between PStore and the end of its parent block.
  2614. //
  2615. // The ideal way to do this is to query AliasAnalysis, but we don't
  2616. // preserve AA currently so that is dangerous. Be super safe and just
  2617. // check there are no other memory operations at all.
  2618. for (auto &I : *QFB->getSinglePredecessor())
  2619. if (I.mayReadOrWriteMemory())
  2620. return false;
  2621. for (auto &I : *QFB)
  2622. if (&I != QStore && I.mayReadOrWriteMemory())
  2623. return false;
  2624. if (QTB)
  2625. for (auto &I : *QTB)
  2626. if (&I != QStore && I.mayReadOrWriteMemory())
  2627. return false;
  2628. for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
  2629. I != E; ++I)
  2630. if (&*I != PStore && I->mayReadOrWriteMemory())
  2631. return false;
  2632. // If PostBB has more than two predecessors, we need to split it so we can
  2633. // sink the store.
  2634. if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
  2635. // We know that QFB's only successor is PostBB. And QFB has a single
  2636. // predecessor. If QTB exists, then its only successor is also PostBB.
  2637. // If QTB does not exist, then QFB's only predecessor has a conditional
  2638. // branch to QFB and PostBB.
  2639. BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
  2640. BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred},
  2641. "condstore.split");
  2642. if (!NewBB)
  2643. return false;
  2644. PostBB = NewBB;
  2645. }
  2646. // OK, we're going to sink the stores to PostBB. The store has to be
  2647. // conditional though, so first create the predicate.
  2648. Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
  2649. ->getCondition();
  2650. Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
  2651. ->getCondition();
  2652. Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
  2653. PStore->getParent());
  2654. Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
  2655. QStore->getParent(), PPHI);
  2656. IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
  2657. Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
  2658. Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
  2659. if (InvertPCond)
  2660. PPred = QB.CreateNot(PPred);
  2661. if (InvertQCond)
  2662. QPred = QB.CreateNot(QPred);
  2663. Value *CombinedPred = QB.CreateOr(PPred, QPred);
  2664. auto *T =
  2665. SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
  2666. QB.SetInsertPoint(T);
  2667. StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
  2668. AAMDNodes AAMD;
  2669. PStore->getAAMetadata(AAMD, /*Merge=*/false);
  2670. PStore->getAAMetadata(AAMD, /*Merge=*/true);
  2671. SI->setAAMetadata(AAMD);
  2672. unsigned PAlignment = PStore->getAlignment();
  2673. unsigned QAlignment = QStore->getAlignment();
  2674. unsigned TypeAlignment =
  2675. DL.getABITypeAlignment(SI->getValueOperand()->getType());
  2676. unsigned MinAlignment;
  2677. unsigned MaxAlignment;
  2678. std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
  2679. // Choose the minimum alignment. If we could prove both stores execute, we
  2680. // could use biggest one. In this case, though, we only know that one of the
  2681. // stores executes. And we don't know it's safe to take the alignment from a
  2682. // store that doesn't execute.
  2683. if (MinAlignment != 0) {
  2684. // Choose the minimum of all non-zero alignments.
  2685. SI->setAlignment(MinAlignment);
  2686. } else if (MaxAlignment != 0) {
  2687. // Choose the minimal alignment between the non-zero alignment and the ABI
  2688. // default alignment for the type of the stored value.
  2689. SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
  2690. } else {
  2691. // If both alignments are zero, use ABI default alignment for the type of
  2692. // the stored value.
  2693. SI->setAlignment(TypeAlignment);
  2694. }
  2695. QStore->eraseFromParent();
  2696. PStore->eraseFromParent();
  2697. return true;
  2698. }
  2699. static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
  2700. const DataLayout &DL) {
  2701. // The intention here is to find diamonds or triangles (see below) where each
  2702. // conditional block contains a store to the same address. Both of these
  2703. // stores are conditional, so they can't be unconditionally sunk. But it may
  2704. // be profitable to speculatively sink the stores into one merged store at the
  2705. // end, and predicate the merged store on the union of the two conditions of
  2706. // PBI and QBI.
  2707. //
  2708. // This can reduce the number of stores executed if both of the conditions are
  2709. // true, and can allow the blocks to become small enough to be if-converted.
  2710. // This optimization will also chain, so that ladders of test-and-set
  2711. // sequences can be if-converted away.
  2712. //
  2713. // We only deal with simple diamonds or triangles:
  2714. //
  2715. // PBI or PBI or a combination of the two
  2716. // / \ | \
  2717. // PTB PFB | PFB
  2718. // \ / | /
  2719. // QBI QBI
  2720. // / \ | \
  2721. // QTB QFB | QFB
  2722. // \ / | /
  2723. // PostBB PostBB
  2724. //
  2725. // We model triangles as a type of diamond with a nullptr "true" block.
  2726. // Triangles are canonicalized so that the fallthrough edge is represented by
  2727. // a true condition, as in the diagram above.
  2728. BasicBlock *PTB = PBI->getSuccessor(0);
  2729. BasicBlock *PFB = PBI->getSuccessor(1);
  2730. BasicBlock *QTB = QBI->getSuccessor(0);
  2731. BasicBlock *QFB = QBI->getSuccessor(1);
  2732. BasicBlock *PostBB = QFB->getSingleSuccessor();
  2733. // Make sure we have a good guess for PostBB. If QTB's only successor is
  2734. // QFB, then QFB is a better PostBB.
  2735. if (QTB->getSingleSuccessor() == QFB)
  2736. PostBB = QFB;
  2737. // If we couldn't find a good PostBB, stop.
  2738. if (!PostBB)
  2739. return false;
  2740. bool InvertPCond = false, InvertQCond = false;
  2741. // Canonicalize fallthroughs to the true branches.
  2742. if (PFB == QBI->getParent()) {
  2743. std::swap(PFB, PTB);
  2744. InvertPCond = true;
  2745. }
  2746. if (QFB == PostBB) {
  2747. std::swap(QFB, QTB);
  2748. InvertQCond = true;
  2749. }
  2750. // From this point on we can assume PTB or QTB may be fallthroughs but PFB
  2751. // and QFB may not. Model fallthroughs as a nullptr block.
  2752. if (PTB == QBI->getParent())
  2753. PTB = nullptr;
  2754. if (QTB == PostBB)
  2755. QTB = nullptr;
  2756. // Legality bailouts. We must have at least the non-fallthrough blocks and
  2757. // the post-dominating block, and the non-fallthroughs must only have one
  2758. // predecessor.
  2759. auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
  2760. return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
  2761. };
  2762. if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
  2763. !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
  2764. return false;
  2765. if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
  2766. (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
  2767. return false;
  2768. if (!QBI->getParent()->hasNUses(2))
  2769. return false;
  2770. // OK, this is a sequence of two diamonds or triangles.
  2771. // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
  2772. SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
  2773. for (auto *BB : {PTB, PFB}) {
  2774. if (!BB)
  2775. continue;
  2776. for (auto &I : *BB)
  2777. if (StoreInst *SI = dyn_cast<StoreInst>(&I))
  2778. PStoreAddresses.insert(SI->getPointerOperand());
  2779. }
  2780. for (auto *BB : {QTB, QFB}) {
  2781. if (!BB)
  2782. continue;
  2783. for (auto &I : *BB)
  2784. if (StoreInst *SI = dyn_cast<StoreInst>(&I))
  2785. QStoreAddresses.insert(SI->getPointerOperand());
  2786. }
  2787. set_intersect(PStoreAddresses, QStoreAddresses);
  2788. // set_intersect mutates PStoreAddresses in place. Rename it here to make it
  2789. // clear what it contains.
  2790. auto &CommonAddresses = PStoreAddresses;
  2791. bool Changed = false;
  2792. for (auto *Address : CommonAddresses)
  2793. Changed |= mergeConditionalStoreToAddress(
  2794. PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
  2795. return Changed;
  2796. }
  2797. /// If we have a conditional branch as a predecessor of another block,
  2798. /// this function tries to simplify it. We know
  2799. /// that PBI and BI are both conditional branches, and BI is in one of the
  2800. /// successor blocks of PBI - PBI branches to BI.
  2801. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
  2802. const DataLayout &DL) {
  2803. assert(PBI->isConditional() && BI->isConditional());
  2804. BasicBlock *BB = BI->getParent();
  2805. // If this block ends with a branch instruction, and if there is a
  2806. // predecessor that ends on a branch of the same condition, make
  2807. // this conditional branch redundant.
  2808. if (PBI->getCondition() == BI->getCondition() &&
  2809. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2810. // Okay, the outcome of this conditional branch is statically
  2811. // knowable. If this block had a single pred, handle specially.
  2812. if (BB->getSinglePredecessor()) {
  2813. // Turn this into a branch on constant.
  2814. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2815. BI->setCondition(
  2816. ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
  2817. return true; // Nuke the branch on constant.
  2818. }
  2819. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  2820. // in the constant and simplify the block result. Subsequent passes of
  2821. // simplifycfg will thread the block.
  2822. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  2823. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  2824. PHINode *NewPN = PHINode::Create(
  2825. Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
  2826. BI->getCondition()->getName() + ".pr", &BB->front());
  2827. // Okay, we're going to insert the PHI node. Since PBI is not the only
  2828. // predecessor, compute the PHI'd conditional value for all of the preds.
  2829. // Any predecessor where the condition is not computable we keep symbolic.
  2830. for (pred_iterator PI = PB; PI != PE; ++PI) {
  2831. BasicBlock *P = *PI;
  2832. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
  2833. PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
  2834. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2835. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2836. NewPN->addIncoming(
  2837. ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
  2838. P);
  2839. } else {
  2840. NewPN->addIncoming(BI->getCondition(), P);
  2841. }
  2842. }
  2843. BI->setCondition(NewPN);
  2844. return true;
  2845. }
  2846. }
  2847. if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  2848. if (CE->canTrap())
  2849. return false;
  2850. // If both branches are conditional and both contain stores to the same
  2851. // address, remove the stores from the conditionals and create a conditional
  2852. // merged store at the end.
  2853. if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
  2854. return true;
  2855. // If this is a conditional branch in an empty block, and if any
  2856. // predecessors are a conditional branch to one of our destinations,
  2857. // fold the conditions into logical ops and one cond br.
  2858. // Ignore dbg intrinsics.
  2859. if (&*BB->instructionsWithoutDebug().begin() != BI)
  2860. return false;
  2861. int PBIOp, BIOp;
  2862. if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
  2863. PBIOp = 0;
  2864. BIOp = 0;
  2865. } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
  2866. PBIOp = 0;
  2867. BIOp = 1;
  2868. } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
  2869. PBIOp = 1;
  2870. BIOp = 0;
  2871. } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
  2872. PBIOp = 1;
  2873. BIOp = 1;
  2874. } else {
  2875. return false;
  2876. }
  2877. // Check to make sure that the other destination of this branch
  2878. // isn't BB itself. If so, this is an infinite loop that will
  2879. // keep getting unwound.
  2880. if (PBI->getSuccessor(PBIOp) == BB)
  2881. return false;
  2882. // Do not perform this transformation if it would require
  2883. // insertion of a large number of select instructions. For targets
  2884. // without predication/cmovs, this is a big pessimization.
  2885. // Also do not perform this transformation if any phi node in the common
  2886. // destination block can trap when reached by BB or PBB (PR17073). In that
  2887. // case, it would be unsafe to hoist the operation into a select instruction.
  2888. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  2889. unsigned NumPhis = 0;
  2890. for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
  2891. ++II, ++NumPhis) {
  2892. if (NumPhis > 2) // Disable this xform.
  2893. return false;
  2894. PHINode *PN = cast<PHINode>(II);
  2895. Value *BIV = PN->getIncomingValueForBlock(BB);
  2896. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
  2897. if (CE->canTrap())
  2898. return false;
  2899. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2900. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2901. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
  2902. if (CE->canTrap())
  2903. return false;
  2904. }
  2905. // Finally, if everything is ok, fold the branches to logical ops.
  2906. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  2907. LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  2908. << "AND: " << *BI->getParent());
  2909. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  2910. // branch in it, where one edge (OtherDest) goes back to itself but the other
  2911. // exits. We don't *know* that the program avoids the infinite loop
  2912. // (even though that seems likely). If we do this xform naively, we'll end up
  2913. // recursively unpeeling the loop. Since we know that (after the xform is
  2914. // done) that the block *is* infinite if reached, we just make it an obviously
  2915. // infinite loop with no cond branch.
  2916. if (OtherDest == BB) {
  2917. // Insert it at the end of the function, because it's either code,
  2918. // or it won't matter if it's hot. :)
  2919. BasicBlock *InfLoopBlock =
  2920. BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
  2921. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  2922. OtherDest = InfLoopBlock;
  2923. }
  2924. LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
  2925. // BI may have other predecessors. Because of this, we leave
  2926. // it alone, but modify PBI.
  2927. // Make sure we get to CommonDest on True&True directions.
  2928. Value *PBICond = PBI->getCondition();
  2929. IRBuilder<NoFolder> Builder(PBI);
  2930. if (PBIOp)
  2931. PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
  2932. Value *BICond = BI->getCondition();
  2933. if (BIOp)
  2934. BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
  2935. // Merge the conditions.
  2936. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  2937. // Modify PBI to branch on the new condition to the new dests.
  2938. PBI->setCondition(Cond);
  2939. PBI->setSuccessor(0, CommonDest);
  2940. PBI->setSuccessor(1, OtherDest);
  2941. // Update branch weight for PBI.
  2942. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2943. uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
  2944. bool HasWeights =
  2945. extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
  2946. SuccTrueWeight, SuccFalseWeight);
  2947. if (HasWeights) {
  2948. PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2949. PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
  2950. SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2951. SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2952. // The weight to CommonDest should be PredCommon * SuccTotal +
  2953. // PredOther * SuccCommon.
  2954. // The weight to OtherDest should be PredOther * SuccOther.
  2955. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
  2956. PredOther * SuccCommon,
  2957. PredOther * SuccOther};
  2958. // Halve the weights if any of them cannot fit in an uint32_t
  2959. FitWeights(NewWeights);
  2960. setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
  2961. }
  2962. // OtherDest may have phi nodes. If so, add an entry from PBI's
  2963. // block that are identical to the entries for BI's block.
  2964. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  2965. // We know that the CommonDest already had an edge from PBI to
  2966. // it. If it has PHIs though, the PHIs may have different
  2967. // entries for BB and PBI's BB. If so, insert a select to make
  2968. // them agree.
  2969. for (PHINode &PN : CommonDest->phis()) {
  2970. Value *BIV = PN.getIncomingValueForBlock(BB);
  2971. unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
  2972. Value *PBIV = PN.getIncomingValue(PBBIdx);
  2973. if (BIV != PBIV) {
  2974. // Insert a select in PBI to pick the right value.
  2975. SelectInst *NV = cast<SelectInst>(
  2976. Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
  2977. PN.setIncomingValue(PBBIdx, NV);
  2978. // Although the select has the same condition as PBI, the original branch
  2979. // weights for PBI do not apply to the new select because the select's
  2980. // 'logical' edges are incoming edges of the phi that is eliminated, not
  2981. // the outgoing edges of PBI.
  2982. if (HasWeights) {
  2983. uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2984. uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
  2985. uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2986. uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2987. // The weight to PredCommonDest should be PredCommon * SuccTotal.
  2988. // The weight to PredOtherDest should be PredOther * SuccCommon.
  2989. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
  2990. PredOther * SuccCommon};
  2991. FitWeights(NewWeights);
  2992. setBranchWeights(NV, NewWeights[0], NewWeights[1]);
  2993. }
  2994. }
  2995. }
  2996. LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  2997. LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
  2998. // This basic block is probably dead. We know it has at least
  2999. // one fewer predecessor.
  3000. return true;
  3001. }
  3002. // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
  3003. // true or to FalseBB if Cond is false.
  3004. // Takes care of updating the successors and removing the old terminator.
  3005. // Also makes sure not to introduce new successors by assuming that edges to
  3006. // non-successor TrueBBs and FalseBBs aren't reachable.
  3007. static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
  3008. BasicBlock *TrueBB, BasicBlock *FalseBB,
  3009. uint32_t TrueWeight,
  3010. uint32_t FalseWeight) {
  3011. // Remove any superfluous successor edges from the CFG.
  3012. // First, figure out which successors to preserve.
  3013. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  3014. // successor.
  3015. BasicBlock *KeepEdge1 = TrueBB;
  3016. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
  3017. // Then remove the rest.
  3018. for (BasicBlock *Succ : successors(OldTerm)) {
  3019. // Make sure only to keep exactly one copy of each edge.
  3020. if (Succ == KeepEdge1)
  3021. KeepEdge1 = nullptr;
  3022. else if (Succ == KeepEdge2)
  3023. KeepEdge2 = nullptr;
  3024. else
  3025. Succ->removePredecessor(OldTerm->getParent(),
  3026. /*DontDeleteUselessPHIs=*/true);
  3027. }
  3028. IRBuilder<> Builder(OldTerm);
  3029. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  3030. // Insert an appropriate new terminator.
  3031. if (!KeepEdge1 && !KeepEdge2) {
  3032. if (TrueBB == FalseBB)
  3033. // We were only looking for one successor, and it was present.
  3034. // Create an unconditional branch to it.
  3035. Builder.CreateBr(TrueBB);
  3036. else {
  3037. // We found both of the successors we were looking for.
  3038. // Create a conditional branch sharing the condition of the select.
  3039. BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  3040. if (TrueWeight != FalseWeight)
  3041. setBranchWeights(NewBI, TrueWeight, FalseWeight);
  3042. }
  3043. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  3044. // Neither of the selected blocks were successors, so this
  3045. // terminator must be unreachable.
  3046. new UnreachableInst(OldTerm->getContext(), OldTerm);
  3047. } else {
  3048. // One of the selected values was a successor, but the other wasn't.
  3049. // Insert an unconditional branch to the one that was found;
  3050. // the edge to the one that wasn't must be unreachable.
  3051. if (!KeepEdge1)
  3052. // Only TrueBB was found.
  3053. Builder.CreateBr(TrueBB);
  3054. else
  3055. // Only FalseBB was found.
  3056. Builder.CreateBr(FalseBB);
  3057. }
  3058. EraseTerminatorAndDCECond(OldTerm);
  3059. return true;
  3060. }
  3061. // Replaces
  3062. // (switch (select cond, X, Y)) on constant X, Y
  3063. // with a branch - conditional if X and Y lead to distinct BBs,
  3064. // unconditional otherwise.
  3065. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  3066. // Check for constant integer values in the select.
  3067. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  3068. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  3069. if (!TrueVal || !FalseVal)
  3070. return false;
  3071. // Find the relevant condition and destinations.
  3072. Value *Condition = Select->getCondition();
  3073. BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
  3074. BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
  3075. // Get weight for TrueBB and FalseBB.
  3076. uint32_t TrueWeight = 0, FalseWeight = 0;
  3077. SmallVector<uint64_t, 8> Weights;
  3078. bool HasWeights = HasBranchWeights(SI);
  3079. if (HasWeights) {
  3080. GetBranchWeights(SI, Weights);
  3081. if (Weights.size() == 1 + SI->getNumCases()) {
  3082. TrueWeight =
  3083. (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
  3084. FalseWeight =
  3085. (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
  3086. }
  3087. }
  3088. // Perform the actual simplification.
  3089. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
  3090. FalseWeight);
  3091. }
  3092. // Replaces
  3093. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  3094. // blockaddress(@fn, BlockB)))
  3095. // with
  3096. // (br cond, BlockA, BlockB).
  3097. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  3098. // Check that both operands of the select are block addresses.
  3099. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  3100. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  3101. if (!TBA || !FBA)
  3102. return false;
  3103. // Extract the actual blocks.
  3104. BasicBlock *TrueBB = TBA->getBasicBlock();
  3105. BasicBlock *FalseBB = FBA->getBasicBlock();
  3106. // Perform the actual simplification.
  3107. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
  3108. 0);
  3109. }
  3110. /// This is called when we find an icmp instruction
  3111. /// (a seteq/setne with a constant) as the only instruction in a
  3112. /// block that ends with an uncond branch. We are looking for a very specific
  3113. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  3114. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  3115. /// default value goes to an uncond block with a seteq in it, we get something
  3116. /// like:
  3117. ///
  3118. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  3119. /// DEFAULT:
  3120. /// %tmp = icmp eq i8 %A, 92
  3121. /// br label %end
  3122. /// end:
  3123. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  3124. ///
  3125. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  3126. /// the PHI, merging the third icmp into the switch.
  3127. bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
  3128. ICmpInst *ICI, IRBuilder<> &Builder) {
  3129. BasicBlock *BB = ICI->getParent();
  3130. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  3131. // complex.
  3132. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
  3133. return false;
  3134. Value *V = ICI->getOperand(0);
  3135. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  3136. // The pattern we're looking for is where our only predecessor is a switch on
  3137. // 'V' and this block is the default case for the switch. In this case we can
  3138. // fold the compared value into the switch to simplify things.
  3139. BasicBlock *Pred = BB->getSinglePredecessor();
  3140. if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
  3141. return false;
  3142. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  3143. if (SI->getCondition() != V)
  3144. return false;
  3145. // If BB is reachable on a non-default case, then we simply know the value of
  3146. // V in this block. Substitute it and constant fold the icmp instruction
  3147. // away.
  3148. if (SI->getDefaultDest() != BB) {
  3149. ConstantInt *VVal = SI->findCaseDest(BB);
  3150. assert(VVal && "Should have a unique destination value");
  3151. ICI->setOperand(0, VVal);
  3152. if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
  3153. ICI->replaceAllUsesWith(V);
  3154. ICI->eraseFromParent();
  3155. }
  3156. // BB is now empty, so it is likely to simplify away.
  3157. return requestResimplify();
  3158. }
  3159. // Ok, the block is reachable from the default dest. If the constant we're
  3160. // comparing exists in one of the other edges, then we can constant fold ICI
  3161. // and zap it.
  3162. if (SI->findCaseValue(Cst) != SI->case_default()) {
  3163. Value *V;
  3164. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  3165. V = ConstantInt::getFalse(BB->getContext());
  3166. else
  3167. V = ConstantInt::getTrue(BB->getContext());
  3168. ICI->replaceAllUsesWith(V);
  3169. ICI->eraseFromParent();
  3170. // BB is now empty, so it is likely to simplify away.
  3171. return requestResimplify();
  3172. }
  3173. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  3174. // the block.
  3175. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  3176. PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
  3177. if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
  3178. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  3179. return false;
  3180. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  3181. // true in the PHI.
  3182. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  3183. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  3184. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  3185. std::swap(DefaultCst, NewCst);
  3186. // Replace ICI (which is used by the PHI for the default value) with true or
  3187. // false depending on if it is EQ or NE.
  3188. ICI->replaceAllUsesWith(DefaultCst);
  3189. ICI->eraseFromParent();
  3190. // Okay, the switch goes to this block on a default value. Add an edge from
  3191. // the switch to the merge point on the compared value.
  3192. BasicBlock *NewBB =
  3193. BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
  3194. SmallVector<uint64_t, 8> Weights;
  3195. bool HasWeights = HasBranchWeights(SI);
  3196. if (HasWeights) {
  3197. GetBranchWeights(SI, Weights);
  3198. if (Weights.size() == 1 + SI->getNumCases()) {
  3199. // Split weight for default case to case for "Cst".
  3200. Weights[0] = (Weights[0] + 1) >> 1;
  3201. Weights.push_back(Weights[0]);
  3202. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  3203. setBranchWeights(SI, MDWeights);
  3204. }
  3205. }
  3206. SI->addCase(Cst, NewBB);
  3207. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  3208. Builder.SetInsertPoint(NewBB);
  3209. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  3210. Builder.CreateBr(SuccBlock);
  3211. PHIUse->addIncoming(NewCst, NewBB);
  3212. return true;
  3213. }
  3214. /// The specified branch is a conditional branch.
  3215. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  3216. /// fold it into a switch instruction if so.
  3217. static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
  3218. const DataLayout &DL) {
  3219. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  3220. if (!Cond)
  3221. return false;
  3222. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  3223. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  3224. // 'setne's and'ed together, collect them.
  3225. // Try to gather values from a chain of and/or to be turned into a switch
  3226. ConstantComparesGatherer ConstantCompare(Cond, DL);
  3227. // Unpack the result
  3228. SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
  3229. Value *CompVal = ConstantCompare.CompValue;
  3230. unsigned UsedICmps = ConstantCompare.UsedICmps;
  3231. Value *ExtraCase = ConstantCompare.Extra;
  3232. // If we didn't have a multiply compared value, fail.
  3233. if (!CompVal)
  3234. return false;
  3235. // Avoid turning single icmps into a switch.
  3236. if (UsedICmps <= 1)
  3237. return false;
  3238. bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
  3239. // There might be duplicate constants in the list, which the switch
  3240. // instruction can't handle, remove them now.
  3241. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  3242. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  3243. // If Extra was used, we require at least two switch values to do the
  3244. // transformation. A switch with one value is just a conditional branch.
  3245. if (ExtraCase && Values.size() < 2)
  3246. return false;
  3247. // TODO: Preserve branch weight metadata, similarly to how
  3248. // FoldValueComparisonIntoPredecessors preserves it.
  3249. // Figure out which block is which destination.
  3250. BasicBlock *DefaultBB = BI->getSuccessor(1);
  3251. BasicBlock *EdgeBB = BI->getSuccessor(0);
  3252. if (!TrueWhenEqual)
  3253. std::swap(DefaultBB, EdgeBB);
  3254. BasicBlock *BB = BI->getParent();
  3255. LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  3256. << " cases into SWITCH. BB is:\n"
  3257. << *BB);
  3258. // If there are any extra values that couldn't be folded into the switch
  3259. // then we evaluate them with an explicit branch first. Split the block
  3260. // right before the condbr to handle it.
  3261. if (ExtraCase) {
  3262. BasicBlock *NewBB =
  3263. BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
  3264. // Remove the uncond branch added to the old block.
  3265. Instruction *OldTI = BB->getTerminator();
  3266. Builder.SetInsertPoint(OldTI);
  3267. if (TrueWhenEqual)
  3268. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  3269. else
  3270. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  3271. OldTI->eraseFromParent();
  3272. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  3273. // for the edge we just added.
  3274. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  3275. LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  3276. << "\nEXTRABB = " << *BB);
  3277. BB = NewBB;
  3278. }
  3279. Builder.SetInsertPoint(BI);
  3280. // Convert pointer to int before we switch.
  3281. if (CompVal->getType()->isPointerTy()) {
  3282. CompVal = Builder.CreatePtrToInt(
  3283. CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
  3284. }
  3285. // Create the new switch instruction now.
  3286. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  3287. // Add all of the 'cases' to the switch instruction.
  3288. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  3289. New->addCase(Values[i], EdgeBB);
  3290. // We added edges from PI to the EdgeBB. As such, if there were any
  3291. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  3292. // the number of edges added.
  3293. for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
  3294. PHINode *PN = cast<PHINode>(BBI);
  3295. Value *InVal = PN->getIncomingValueForBlock(BB);
  3296. for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
  3297. PN->addIncoming(InVal, BB);
  3298. }
  3299. // Erase the old branch instruction.
  3300. EraseTerminatorAndDCECond(BI);
  3301. LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  3302. return true;
  3303. }
  3304. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  3305. if (isa<PHINode>(RI->getValue()))
  3306. return SimplifyCommonResume(RI);
  3307. else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
  3308. RI->getValue() == RI->getParent()->getFirstNonPHI())
  3309. // The resume must unwind the exception that caused control to branch here.
  3310. return SimplifySingleResume(RI);
  3311. return false;
  3312. }
  3313. // Simplify resume that is shared by several landing pads (phi of landing pad).
  3314. bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
  3315. BasicBlock *BB = RI->getParent();
  3316. // Check that there are no other instructions except for debug intrinsics
  3317. // between the phi of landing pads (RI->getValue()) and resume instruction.
  3318. BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
  3319. E = RI->getIterator();
  3320. while (++I != E)
  3321. if (!isa<DbgInfoIntrinsic>(I))
  3322. return false;
  3323. SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
  3324. auto *PhiLPInst = cast<PHINode>(RI->getValue());
  3325. // Check incoming blocks to see if any of them are trivial.
  3326. for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
  3327. Idx++) {
  3328. auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
  3329. auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
  3330. // If the block has other successors, we can not delete it because
  3331. // it has other dependents.
  3332. if (IncomingBB->getUniqueSuccessor() != BB)
  3333. continue;
  3334. auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
  3335. // Not the landing pad that caused the control to branch here.
  3336. if (IncomingValue != LandingPad)
  3337. continue;
  3338. bool isTrivial = true;
  3339. I = IncomingBB->getFirstNonPHI()->getIterator();
  3340. E = IncomingBB->getTerminator()->getIterator();
  3341. while (++I != E)
  3342. if (!isa<DbgInfoIntrinsic>(I)) {
  3343. isTrivial = false;
  3344. break;
  3345. }
  3346. if (isTrivial)
  3347. TrivialUnwindBlocks.insert(IncomingBB);
  3348. }
  3349. // If no trivial unwind blocks, don't do any simplifications.
  3350. if (TrivialUnwindBlocks.empty())
  3351. return false;
  3352. // Turn all invokes that unwind here into calls.
  3353. for (auto *TrivialBB : TrivialUnwindBlocks) {
  3354. // Blocks that will be simplified should be removed from the phi node.
  3355. // Note there could be multiple edges to the resume block, and we need
  3356. // to remove them all.
  3357. while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
  3358. BB->removePredecessor(TrivialBB, true);
  3359. for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
  3360. PI != PE;) {
  3361. BasicBlock *Pred = *PI++;
  3362. removeUnwindEdge(Pred);
  3363. }
  3364. // In each SimplifyCFG run, only the current processed block can be erased.
  3365. // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
  3366. // of erasing TrivialBB, we only remove the branch to the common resume
  3367. // block so that we can later erase the resume block since it has no
  3368. // predecessors.
  3369. TrivialBB->getTerminator()->eraseFromParent();
  3370. new UnreachableInst(RI->getContext(), TrivialBB);
  3371. }
  3372. // Delete the resume block if all its predecessors have been removed.
  3373. if (pred_empty(BB))
  3374. BB->eraseFromParent();
  3375. return !TrivialUnwindBlocks.empty();
  3376. }
  3377. // Simplify resume that is only used by a single (non-phi) landing pad.
  3378. bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
  3379. BasicBlock *BB = RI->getParent();
  3380. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  3381. assert(RI->getValue() == LPInst &&
  3382. "Resume must unwind the exception that caused control to here");
  3383. // Check that there are no other instructions except for debug intrinsics.
  3384. BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
  3385. while (++I != E)
  3386. if (!isa<DbgInfoIntrinsic>(I))
  3387. return false;
  3388. // Turn all invokes that unwind here into calls and delete the basic block.
  3389. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  3390. BasicBlock *Pred = *PI++;
  3391. removeUnwindEdge(Pred);
  3392. }
  3393. // The landingpad is now unreachable. Zap it.
  3394. if (LoopHeaders)
  3395. LoopHeaders->erase(BB);
  3396. BB->eraseFromParent();
  3397. return true;
  3398. }
  3399. static bool removeEmptyCleanup(CleanupReturnInst *RI) {
  3400. // If this is a trivial cleanup pad that executes no instructions, it can be
  3401. // eliminated. If the cleanup pad continues to the caller, any predecessor
  3402. // that is an EH pad will be updated to continue to the caller and any
  3403. // predecessor that terminates with an invoke instruction will have its invoke
  3404. // instruction converted to a call instruction. If the cleanup pad being
  3405. // simplified does not continue to the caller, each predecessor will be
  3406. // updated to continue to the unwind destination of the cleanup pad being
  3407. // simplified.
  3408. BasicBlock *BB = RI->getParent();
  3409. CleanupPadInst *CPInst = RI->getCleanupPad();
  3410. if (CPInst->getParent() != BB)
  3411. // This isn't an empty cleanup.
  3412. return false;
  3413. // We cannot kill the pad if it has multiple uses. This typically arises
  3414. // from unreachable basic blocks.
  3415. if (!CPInst->hasOneUse())
  3416. return false;
  3417. // Check that there are no other instructions except for benign intrinsics.
  3418. BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
  3419. while (++I != E) {
  3420. auto *II = dyn_cast<IntrinsicInst>(I);
  3421. if (!II)
  3422. return false;
  3423. Intrinsic::ID IntrinsicID = II->getIntrinsicID();
  3424. switch (IntrinsicID) {
  3425. case Intrinsic::dbg_declare:
  3426. case Intrinsic::dbg_value:
  3427. case Intrinsic::dbg_label:
  3428. case Intrinsic::lifetime_end:
  3429. break;
  3430. default:
  3431. return false;
  3432. }
  3433. }
  3434. // If the cleanup return we are simplifying unwinds to the caller, this will
  3435. // set UnwindDest to nullptr.
  3436. BasicBlock *UnwindDest = RI->getUnwindDest();
  3437. Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
  3438. // We're about to remove BB from the control flow. Before we do, sink any
  3439. // PHINodes into the unwind destination. Doing this before changing the
  3440. // control flow avoids some potentially slow checks, since we can currently
  3441. // be certain that UnwindDest and BB have no common predecessors (since they
  3442. // are both EH pads).
  3443. if (UnwindDest) {
  3444. // First, go through the PHI nodes in UnwindDest and update any nodes that
  3445. // reference the block we are removing
  3446. for (BasicBlock::iterator I = UnwindDest->begin(),
  3447. IE = DestEHPad->getIterator();
  3448. I != IE; ++I) {
  3449. PHINode *DestPN = cast<PHINode>(I);
  3450. int Idx = DestPN->getBasicBlockIndex(BB);
  3451. // Since BB unwinds to UnwindDest, it has to be in the PHI node.
  3452. assert(Idx != -1);
  3453. // This PHI node has an incoming value that corresponds to a control
  3454. // path through the cleanup pad we are removing. If the incoming
  3455. // value is in the cleanup pad, it must be a PHINode (because we
  3456. // verified above that the block is otherwise empty). Otherwise, the
  3457. // value is either a constant or a value that dominates the cleanup
  3458. // pad being removed.
  3459. //
  3460. // Because BB and UnwindDest are both EH pads, all of their
  3461. // predecessors must unwind to these blocks, and since no instruction
  3462. // can have multiple unwind destinations, there will be no overlap in
  3463. // incoming blocks between SrcPN and DestPN.
  3464. Value *SrcVal = DestPN->getIncomingValue(Idx);
  3465. PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
  3466. // Remove the entry for the block we are deleting.
  3467. DestPN->removeIncomingValue(Idx, false);
  3468. if (SrcPN && SrcPN->getParent() == BB) {
  3469. // If the incoming value was a PHI node in the cleanup pad we are
  3470. // removing, we need to merge that PHI node's incoming values into
  3471. // DestPN.
  3472. for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
  3473. SrcIdx != SrcE; ++SrcIdx) {
  3474. DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
  3475. SrcPN->getIncomingBlock(SrcIdx));
  3476. }
  3477. } else {
  3478. // Otherwise, the incoming value came from above BB and
  3479. // so we can just reuse it. We must associate all of BB's
  3480. // predecessors with this value.
  3481. for (auto *pred : predecessors(BB)) {
  3482. DestPN->addIncoming(SrcVal, pred);
  3483. }
  3484. }
  3485. }
  3486. // Sink any remaining PHI nodes directly into UnwindDest.
  3487. Instruction *InsertPt = DestEHPad;
  3488. for (BasicBlock::iterator I = BB->begin(),
  3489. IE = BB->getFirstNonPHI()->getIterator();
  3490. I != IE;) {
  3491. // The iterator must be incremented here because the instructions are
  3492. // being moved to another block.
  3493. PHINode *PN = cast<PHINode>(I++);
  3494. if (PN->use_empty())
  3495. // If the PHI node has no uses, just leave it. It will be erased
  3496. // when we erase BB below.
  3497. continue;
  3498. // Otherwise, sink this PHI node into UnwindDest.
  3499. // Any predecessors to UnwindDest which are not already represented
  3500. // must be back edges which inherit the value from the path through
  3501. // BB. In this case, the PHI value must reference itself.
  3502. for (auto *pred : predecessors(UnwindDest))
  3503. if (pred != BB)
  3504. PN->addIncoming(PN, pred);
  3505. PN->moveBefore(InsertPt);
  3506. }
  3507. }
  3508. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  3509. // The iterator must be updated here because we are removing this pred.
  3510. BasicBlock *PredBB = *PI++;
  3511. if (UnwindDest == nullptr) {
  3512. removeUnwindEdge(PredBB);
  3513. } else {
  3514. Instruction *TI = PredBB->getTerminator();
  3515. TI->replaceUsesOfWith(BB, UnwindDest);
  3516. }
  3517. }
  3518. // The cleanup pad is now unreachable. Zap it.
  3519. BB->eraseFromParent();
  3520. return true;
  3521. }
  3522. // Try to merge two cleanuppads together.
  3523. static bool mergeCleanupPad(CleanupReturnInst *RI) {
  3524. // Skip any cleanuprets which unwind to caller, there is nothing to merge
  3525. // with.
  3526. BasicBlock *UnwindDest = RI->getUnwindDest();
  3527. if (!UnwindDest)
  3528. return false;
  3529. // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
  3530. // be safe to merge without code duplication.
  3531. if (UnwindDest->getSinglePredecessor() != RI->getParent())
  3532. return false;
  3533. // Verify that our cleanuppad's unwind destination is another cleanuppad.
  3534. auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
  3535. if (!SuccessorCleanupPad)
  3536. return false;
  3537. CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
  3538. // Replace any uses of the successor cleanupad with the predecessor pad
  3539. // The only cleanuppad uses should be this cleanupret, it's cleanupret and
  3540. // funclet bundle operands.
  3541. SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
  3542. // Remove the old cleanuppad.
  3543. SuccessorCleanupPad->eraseFromParent();
  3544. // Now, we simply replace the cleanupret with a branch to the unwind
  3545. // destination.
  3546. BranchInst::Create(UnwindDest, RI->getParent());
  3547. RI->eraseFromParent();
  3548. return true;
  3549. }
  3550. bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
  3551. // It is possible to transiantly have an undef cleanuppad operand because we
  3552. // have deleted some, but not all, dead blocks.
  3553. // Eventually, this block will be deleted.
  3554. if (isa<UndefValue>(RI->getOperand(0)))
  3555. return false;
  3556. if (mergeCleanupPad(RI))
  3557. return true;
  3558. if (removeEmptyCleanup(RI))
  3559. return true;
  3560. return false;
  3561. }
  3562. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  3563. BasicBlock *BB = RI->getParent();
  3564. if (!BB->getFirstNonPHIOrDbg()->isTerminator())
  3565. return false;
  3566. // Find predecessors that end with branches.
  3567. SmallVector<BasicBlock *, 8> UncondBranchPreds;
  3568. SmallVector<BranchInst *, 8> CondBranchPreds;
  3569. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  3570. BasicBlock *P = *PI;
  3571. Instruction *PTI = P->getTerminator();
  3572. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  3573. if (BI->isUnconditional())
  3574. UncondBranchPreds.push_back(P);
  3575. else
  3576. CondBranchPreds.push_back(BI);
  3577. }
  3578. }
  3579. // If we found some, do the transformation!
  3580. if (!UncondBranchPreds.empty() && DupRet) {
  3581. while (!UncondBranchPreds.empty()) {
  3582. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  3583. LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
  3584. << "INTO UNCOND BRANCH PRED: " << *Pred);
  3585. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  3586. }
  3587. // If we eliminated all predecessors of the block, delete the block now.
  3588. if (pred_empty(BB)) {
  3589. // We know there are no successors, so just nuke the block.
  3590. if (LoopHeaders)
  3591. LoopHeaders->erase(BB);
  3592. BB->eraseFromParent();
  3593. }
  3594. return true;
  3595. }
  3596. // Check out all of the conditional branches going to this return
  3597. // instruction. If any of them just select between returns, change the
  3598. // branch itself into a select/return pair.
  3599. while (!CondBranchPreds.empty()) {
  3600. BranchInst *BI = CondBranchPreds.pop_back_val();
  3601. // Check to see if the non-BB successor is also a return block.
  3602. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  3603. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  3604. SimplifyCondBranchToTwoReturns(BI, Builder))
  3605. return true;
  3606. }
  3607. return false;
  3608. }
  3609. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  3610. BasicBlock *BB = UI->getParent();
  3611. bool Changed = false;
  3612. // If there are any instructions immediately before the unreachable that can
  3613. // be removed, do so.
  3614. while (UI->getIterator() != BB->begin()) {
  3615. BasicBlock::iterator BBI = UI->getIterator();
  3616. --BBI;
  3617. // Do not delete instructions that can have side effects which might cause
  3618. // the unreachable to not be reachable; specifically, calls and volatile
  3619. // operations may have this effect.
  3620. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
  3621. break;
  3622. if (BBI->mayHaveSideEffects()) {
  3623. if (auto *SI = dyn_cast<StoreInst>(BBI)) {
  3624. if (SI->isVolatile())
  3625. break;
  3626. } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
  3627. if (LI->isVolatile())
  3628. break;
  3629. } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  3630. if (RMWI->isVolatile())
  3631. break;
  3632. } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  3633. if (CXI->isVolatile())
  3634. break;
  3635. } else if (isa<CatchPadInst>(BBI)) {
  3636. // A catchpad may invoke exception object constructors and such, which
  3637. // in some languages can be arbitrary code, so be conservative by
  3638. // default.
  3639. // For CoreCLR, it just involves a type test, so can be removed.
  3640. if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
  3641. EHPersonality::CoreCLR)
  3642. break;
  3643. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  3644. !isa<LandingPadInst>(BBI)) {
  3645. break;
  3646. }
  3647. // Note that deleting LandingPad's here is in fact okay, although it
  3648. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  3649. // all the predecessors of this block will be the unwind edges of Invokes,
  3650. // and we can therefore guarantee this block will be erased.
  3651. }
  3652. // Delete this instruction (any uses are guaranteed to be dead)
  3653. if (!BBI->use_empty())
  3654. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  3655. BBI->eraseFromParent();
  3656. Changed = true;
  3657. }
  3658. // If the unreachable instruction is the first in the block, take a gander
  3659. // at all of the predecessors of this instruction, and simplify them.
  3660. if (&BB->front() != UI)
  3661. return Changed;
  3662. SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
  3663. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  3664. Instruction *TI = Preds[i]->getTerminator();
  3665. IRBuilder<> Builder(TI);
  3666. if (auto *BI = dyn_cast<BranchInst>(TI)) {
  3667. if (BI->isUnconditional()) {
  3668. if (BI->getSuccessor(0) == BB) {
  3669. new UnreachableInst(TI->getContext(), TI);
  3670. TI->eraseFromParent();
  3671. Changed = true;
  3672. }
  3673. } else {
  3674. if (BI->getSuccessor(0) == BB) {
  3675. Builder.CreateBr(BI->getSuccessor(1));
  3676. EraseTerminatorAndDCECond(BI);
  3677. } else if (BI->getSuccessor(1) == BB) {
  3678. Builder.CreateBr(BI->getSuccessor(0));
  3679. EraseTerminatorAndDCECond(BI);
  3680. Changed = true;
  3681. }
  3682. }
  3683. } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
  3684. for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
  3685. if (i->getCaseSuccessor() != BB) {
  3686. ++i;
  3687. continue;
  3688. }
  3689. BB->removePredecessor(SI->getParent());
  3690. i = SI->removeCase(i);
  3691. e = SI->case_end();
  3692. Changed = true;
  3693. }
  3694. } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
  3695. if (II->getUnwindDest() == BB) {
  3696. removeUnwindEdge(TI->getParent());
  3697. Changed = true;
  3698. }
  3699. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
  3700. if (CSI->getUnwindDest() == BB) {
  3701. removeUnwindEdge(TI->getParent());
  3702. Changed = true;
  3703. continue;
  3704. }
  3705. for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
  3706. E = CSI->handler_end();
  3707. I != E; ++I) {
  3708. if (*I == BB) {
  3709. CSI->removeHandler(I);
  3710. --I;
  3711. --E;
  3712. Changed = true;
  3713. }
  3714. }
  3715. if (CSI->getNumHandlers() == 0) {
  3716. BasicBlock *CatchSwitchBB = CSI->getParent();
  3717. if (CSI->hasUnwindDest()) {
  3718. // Redirect preds to the unwind dest
  3719. CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
  3720. } else {
  3721. // Rewrite all preds to unwind to caller (or from invoke to call).
  3722. SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
  3723. for (BasicBlock *EHPred : EHPreds)
  3724. removeUnwindEdge(EHPred);
  3725. }
  3726. // The catchswitch is no longer reachable.
  3727. new UnreachableInst(CSI->getContext(), CSI);
  3728. CSI->eraseFromParent();
  3729. Changed = true;
  3730. }
  3731. } else if (isa<CleanupReturnInst>(TI)) {
  3732. new UnreachableInst(TI->getContext(), TI);
  3733. TI->eraseFromParent();
  3734. Changed = true;
  3735. }
  3736. }
  3737. // If this block is now dead, remove it.
  3738. if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
  3739. // We know there are no successors, so just nuke the block.
  3740. if (LoopHeaders)
  3741. LoopHeaders->erase(BB);
  3742. BB->eraseFromParent();
  3743. return true;
  3744. }
  3745. return Changed;
  3746. }
  3747. static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
  3748. assert(Cases.size() >= 1);
  3749. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  3750. for (size_t I = 1, E = Cases.size(); I != E; ++I) {
  3751. if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
  3752. return false;
  3753. }
  3754. return true;
  3755. }
  3756. /// Turn a switch with two reachable destinations into an integer range
  3757. /// comparison and branch.
  3758. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  3759. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  3760. bool HasDefault =
  3761. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3762. // Partition the cases into two sets with different destinations.
  3763. BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
  3764. BasicBlock *DestB = nullptr;
  3765. SmallVector<ConstantInt *, 16> CasesA;
  3766. SmallVector<ConstantInt *, 16> CasesB;
  3767. for (auto Case : SI->cases()) {
  3768. BasicBlock *Dest = Case.getCaseSuccessor();
  3769. if (!DestA)
  3770. DestA = Dest;
  3771. if (Dest == DestA) {
  3772. CasesA.push_back(Case.getCaseValue());
  3773. continue;
  3774. }
  3775. if (!DestB)
  3776. DestB = Dest;
  3777. if (Dest == DestB) {
  3778. CasesB.push_back(Case.getCaseValue());
  3779. continue;
  3780. }
  3781. return false; // More than two destinations.
  3782. }
  3783. assert(DestA && DestB &&
  3784. "Single-destination switch should have been folded.");
  3785. assert(DestA != DestB);
  3786. assert(DestB != SI->getDefaultDest());
  3787. assert(!CasesB.empty() && "There must be non-default cases.");
  3788. assert(!CasesA.empty() || HasDefault);
  3789. // Figure out if one of the sets of cases form a contiguous range.
  3790. SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
  3791. BasicBlock *ContiguousDest = nullptr;
  3792. BasicBlock *OtherDest = nullptr;
  3793. if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
  3794. ContiguousCases = &CasesA;
  3795. ContiguousDest = DestA;
  3796. OtherDest = DestB;
  3797. } else if (CasesAreContiguous(CasesB)) {
  3798. ContiguousCases = &CasesB;
  3799. ContiguousDest = DestB;
  3800. OtherDest = DestA;
  3801. } else
  3802. return false;
  3803. // Start building the compare and branch.
  3804. Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
  3805. Constant *NumCases =
  3806. ConstantInt::get(Offset->getType(), ContiguousCases->size());
  3807. Value *Sub = SI->getCondition();
  3808. if (!Offset->isNullValue())
  3809. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
  3810. Value *Cmp;
  3811. // If NumCases overflowed, then all possible values jump to the successor.
  3812. if (NumCases->isNullValue() && !ContiguousCases->empty())
  3813. Cmp = ConstantInt::getTrue(SI->getContext());
  3814. else
  3815. Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  3816. BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
  3817. // Update weight for the newly-created conditional branch.
  3818. if (HasBranchWeights(SI)) {
  3819. SmallVector<uint64_t, 8> Weights;
  3820. GetBranchWeights(SI, Weights);
  3821. if (Weights.size() == 1 + SI->getNumCases()) {
  3822. uint64_t TrueWeight = 0;
  3823. uint64_t FalseWeight = 0;
  3824. for (size_t I = 0, E = Weights.size(); I != E; ++I) {
  3825. if (SI->getSuccessor(I) == ContiguousDest)
  3826. TrueWeight += Weights[I];
  3827. else
  3828. FalseWeight += Weights[I];
  3829. }
  3830. while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
  3831. TrueWeight /= 2;
  3832. FalseWeight /= 2;
  3833. }
  3834. setBranchWeights(NewBI, TrueWeight, FalseWeight);
  3835. }
  3836. }
  3837. // Prune obsolete incoming values off the successors' PHI nodes.
  3838. for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
  3839. unsigned PreviousEdges = ContiguousCases->size();
  3840. if (ContiguousDest == SI->getDefaultDest())
  3841. ++PreviousEdges;
  3842. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  3843. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  3844. }
  3845. for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
  3846. unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
  3847. if (OtherDest == SI->getDefaultDest())
  3848. ++PreviousEdges;
  3849. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  3850. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  3851. }
  3852. // Drop the switch.
  3853. SI->eraseFromParent();
  3854. return true;
  3855. }
  3856. /// Compute masked bits for the condition of a switch
  3857. /// and use it to remove dead cases.
  3858. static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
  3859. const DataLayout &DL) {
  3860. Value *Cond = SI->getCondition();
  3861. unsigned Bits = Cond->getType()->getIntegerBitWidth();
  3862. KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
  3863. // We can also eliminate cases by determining that their values are outside of
  3864. // the limited range of the condition based on how many significant (non-sign)
  3865. // bits are in the condition value.
  3866. unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
  3867. unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
  3868. // Gather dead cases.
  3869. SmallVector<ConstantInt *, 8> DeadCases;
  3870. for (auto &Case : SI->cases()) {
  3871. const APInt &CaseVal = Case.getCaseValue()->getValue();
  3872. if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
  3873. (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
  3874. DeadCases.push_back(Case.getCaseValue());
  3875. LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
  3876. << " is dead.\n");
  3877. }
  3878. }
  3879. // If we can prove that the cases must cover all possible values, the
  3880. // default destination becomes dead and we can remove it. If we know some
  3881. // of the bits in the value, we can use that to more precisely compute the
  3882. // number of possible unique case values.
  3883. bool HasDefault =
  3884. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3885. const unsigned NumUnknownBits =
  3886. Bits - (Known.Zero | Known.One).countPopulation();
  3887. assert(NumUnknownBits <= Bits);
  3888. if (HasDefault && DeadCases.empty() &&
  3889. NumUnknownBits < 64 /* avoid overflow */ &&
  3890. SI->getNumCases() == (1ULL << NumUnknownBits)) {
  3891. LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
  3892. BasicBlock *NewDefault =
  3893. SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
  3894. SI->setDefaultDest(&*NewDefault);
  3895. SplitBlock(&*NewDefault, &NewDefault->front());
  3896. auto *OldTI = NewDefault->getTerminator();
  3897. new UnreachableInst(SI->getContext(), OldTI);
  3898. EraseTerminatorAndDCECond(OldTI);
  3899. return true;
  3900. }
  3901. SmallVector<uint64_t, 8> Weights;
  3902. bool HasWeight = HasBranchWeights(SI);
  3903. if (HasWeight) {
  3904. GetBranchWeights(SI, Weights);
  3905. HasWeight = (Weights.size() == 1 + SI->getNumCases());
  3906. }
  3907. // Remove dead cases from the switch.
  3908. for (ConstantInt *DeadCase : DeadCases) {
  3909. SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
  3910. assert(CaseI != SI->case_default() &&
  3911. "Case was not found. Probably mistake in DeadCases forming.");
  3912. if (HasWeight) {
  3913. std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.back());
  3914. Weights.pop_back();
  3915. }
  3916. // Prune unused values from PHI nodes.
  3917. CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
  3918. SI->removeCase(CaseI);
  3919. }
  3920. if (HasWeight && Weights.size() >= 2) {
  3921. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  3922. setBranchWeights(SI, MDWeights);
  3923. }
  3924. return !DeadCases.empty();
  3925. }
  3926. /// If BB would be eligible for simplification by
  3927. /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  3928. /// by an unconditional branch), look at the phi node for BB in the successor
  3929. /// block and see if the incoming value is equal to CaseValue. If so, return
  3930. /// the phi node, and set PhiIndex to BB's index in the phi node.
  3931. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  3932. BasicBlock *BB, int *PhiIndex) {
  3933. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  3934. return nullptr; // BB must be empty to be a candidate for simplification.
  3935. if (!BB->getSinglePredecessor())
  3936. return nullptr; // BB must be dominated by the switch.
  3937. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  3938. if (!Branch || !Branch->isUnconditional())
  3939. return nullptr; // Terminator must be unconditional branch.
  3940. BasicBlock *Succ = Branch->getSuccessor(0);
  3941. for (PHINode &PHI : Succ->phis()) {
  3942. int Idx = PHI.getBasicBlockIndex(BB);
  3943. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  3944. Value *InValue = PHI.getIncomingValue(Idx);
  3945. if (InValue != CaseValue)
  3946. continue;
  3947. *PhiIndex = Idx;
  3948. return &PHI;
  3949. }
  3950. return nullptr;
  3951. }
  3952. /// Try to forward the condition of a switch instruction to a phi node
  3953. /// dominated by the switch, if that would mean that some of the destination
  3954. /// blocks of the switch can be folded away. Return true if a change is made.
  3955. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  3956. using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
  3957. ForwardingNodesMap ForwardingNodes;
  3958. BasicBlock *SwitchBlock = SI->getParent();
  3959. bool Changed = false;
  3960. for (auto &Case : SI->cases()) {
  3961. ConstantInt *CaseValue = Case.getCaseValue();
  3962. BasicBlock *CaseDest = Case.getCaseSuccessor();
  3963. // Replace phi operands in successor blocks that are using the constant case
  3964. // value rather than the switch condition variable:
  3965. // switchbb:
  3966. // switch i32 %x, label %default [
  3967. // i32 17, label %succ
  3968. // ...
  3969. // succ:
  3970. // %r = phi i32 ... [ 17, %switchbb ] ...
  3971. // -->
  3972. // %r = phi i32 ... [ %x, %switchbb ] ...
  3973. for (PHINode &Phi : CaseDest->phis()) {
  3974. // This only works if there is exactly 1 incoming edge from the switch to
  3975. // a phi. If there is >1, that means multiple cases of the switch map to 1
  3976. // value in the phi, and that phi value is not the switch condition. Thus,
  3977. // this transform would not make sense (the phi would be invalid because
  3978. // a phi can't have different incoming values from the same block).
  3979. int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
  3980. if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
  3981. count(Phi.blocks(), SwitchBlock) == 1) {
  3982. Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
  3983. Changed = true;
  3984. }
  3985. }
  3986. // Collect phi nodes that are indirectly using this switch's case constants.
  3987. int PhiIdx;
  3988. if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
  3989. ForwardingNodes[Phi].push_back(PhiIdx);
  3990. }
  3991. for (auto &ForwardingNode : ForwardingNodes) {
  3992. PHINode *Phi = ForwardingNode.first;
  3993. SmallVectorImpl<int> &Indexes = ForwardingNode.second;
  3994. if (Indexes.size() < 2)
  3995. continue;
  3996. for (int Index : Indexes)
  3997. Phi->setIncomingValue(Index, SI->getCondition());
  3998. Changed = true;
  3999. }
  4000. return Changed;
  4001. }
  4002. /// Return true if the backend will be able to handle
  4003. /// initializing an array of constants like C.
  4004. static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
  4005. if (C->isThreadDependent())
  4006. return false;
  4007. if (C->isDLLImportDependent())
  4008. return false;
  4009. if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
  4010. !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
  4011. !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
  4012. return false;
  4013. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  4014. if (!CE->isGEPWithNoNotionalOverIndexing())
  4015. return false;
  4016. if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
  4017. return false;
  4018. }
  4019. if (!TTI.shouldBuildLookupTablesForConstant(C))
  4020. return false;
  4021. return true;
  4022. }
  4023. /// If V is a Constant, return it. Otherwise, try to look up
  4024. /// its constant value in ConstantPool, returning 0 if it's not there.
  4025. static Constant *
  4026. LookupConstant(Value *V,
  4027. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  4028. if (Constant *C = dyn_cast<Constant>(V))
  4029. return C;
  4030. return ConstantPool.lookup(V);
  4031. }
  4032. /// Try to fold instruction I into a constant. This works for
  4033. /// simple instructions such as binary operations where both operands are
  4034. /// constant or can be replaced by constants from the ConstantPool. Returns the
  4035. /// resulting constant on success, 0 otherwise.
  4036. static Constant *
  4037. ConstantFold(Instruction *I, const DataLayout &DL,
  4038. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  4039. if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  4040. Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
  4041. if (!A)
  4042. return nullptr;
  4043. if (A->isAllOnesValue())
  4044. return LookupConstant(Select->getTrueValue(), ConstantPool);
  4045. if (A->isNullValue())
  4046. return LookupConstant(Select->getFalseValue(), ConstantPool);
  4047. return nullptr;
  4048. }
  4049. SmallVector<Constant *, 4> COps;
  4050. for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
  4051. if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
  4052. COps.push_back(A);
  4053. else
  4054. return nullptr;
  4055. }
  4056. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  4057. return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
  4058. COps[1], DL);
  4059. }
  4060. return ConstantFoldInstOperands(I, COps, DL);
  4061. }
  4062. /// Try to determine the resulting constant values in phi nodes
  4063. /// at the common destination basic block, *CommonDest, for one of the case
  4064. /// destionations CaseDest corresponding to value CaseVal (0 for the default
  4065. /// case), of a switch instruction SI.
  4066. static bool
  4067. GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
  4068. BasicBlock **CommonDest,
  4069. SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
  4070. const DataLayout &DL, const TargetTransformInfo &TTI) {
  4071. // The block from which we enter the common destination.
  4072. BasicBlock *Pred = SI->getParent();
  4073. // If CaseDest is empty except for some side-effect free instructions through
  4074. // which we can constant-propagate the CaseVal, continue to its successor.
  4075. SmallDenseMap<Value *, Constant *> ConstantPool;
  4076. ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
  4077. for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
  4078. if (I.isTerminator()) {
  4079. // If the terminator is a simple branch, continue to the next block.
  4080. if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
  4081. return false;
  4082. Pred = CaseDest;
  4083. CaseDest = I.getSuccessor(0);
  4084. } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
  4085. // Instruction is side-effect free and constant.
  4086. // If the instruction has uses outside this block or a phi node slot for
  4087. // the block, it is not safe to bypass the instruction since it would then
  4088. // no longer dominate all its uses.
  4089. for (auto &Use : I.uses()) {
  4090. User *User = Use.getUser();
  4091. if (Instruction *I = dyn_cast<Instruction>(User))
  4092. if (I->getParent() == CaseDest)
  4093. continue;
  4094. if (PHINode *Phi = dyn_cast<PHINode>(User))
  4095. if (Phi->getIncomingBlock(Use) == CaseDest)
  4096. continue;
  4097. return false;
  4098. }
  4099. ConstantPool.insert(std::make_pair(&I, C));
  4100. } else {
  4101. break;
  4102. }
  4103. }
  4104. // If we did not have a CommonDest before, use the current one.
  4105. if (!*CommonDest)
  4106. *CommonDest = CaseDest;
  4107. // If the destination isn't the common one, abort.
  4108. if (CaseDest != *CommonDest)
  4109. return false;
  4110. // Get the values for this case from phi nodes in the destination block.
  4111. for (PHINode &PHI : (*CommonDest)->phis()) {
  4112. int Idx = PHI.getBasicBlockIndex(Pred);
  4113. if (Idx == -1)
  4114. continue;
  4115. Constant *ConstVal =
  4116. LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
  4117. if (!ConstVal)
  4118. return false;
  4119. // Be conservative about which kinds of constants we support.
  4120. if (!ValidLookupTableConstant(ConstVal, TTI))
  4121. return false;
  4122. Res.push_back(std::make_pair(&PHI, ConstVal));
  4123. }
  4124. return Res.size() > 0;
  4125. }
  4126. // Helper function used to add CaseVal to the list of cases that generate
  4127. // Result. Returns the updated number of cases that generate this result.
  4128. static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
  4129. SwitchCaseResultVectorTy &UniqueResults,
  4130. Constant *Result) {
  4131. for (auto &I : UniqueResults) {
  4132. if (I.first == Result) {
  4133. I.second.push_back(CaseVal);
  4134. return I.second.size();
  4135. }
  4136. }
  4137. UniqueResults.push_back(
  4138. std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
  4139. return 1;
  4140. }
  4141. // Helper function that initializes a map containing
  4142. // results for the PHI node of the common destination block for a switch
  4143. // instruction. Returns false if multiple PHI nodes have been found or if
  4144. // there is not a common destination block for the switch.
  4145. static bool
  4146. InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
  4147. SwitchCaseResultVectorTy &UniqueResults,
  4148. Constant *&DefaultResult, const DataLayout &DL,
  4149. const TargetTransformInfo &TTI,
  4150. uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
  4151. for (auto &I : SI->cases()) {
  4152. ConstantInt *CaseVal = I.getCaseValue();
  4153. // Resulting value at phi nodes for this case value.
  4154. SwitchCaseResultsTy Results;
  4155. if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
  4156. DL, TTI))
  4157. return false;
  4158. // Only one value per case is permitted.
  4159. if (Results.size() > 1)
  4160. return false;
  4161. // Add the case->result mapping to UniqueResults.
  4162. const uintptr_t NumCasesForResult =
  4163. MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
  4164. // Early out if there are too many cases for this result.
  4165. if (NumCasesForResult > MaxCasesPerResult)
  4166. return false;
  4167. // Early out if there are too many unique results.
  4168. if (UniqueResults.size() > MaxUniqueResults)
  4169. return false;
  4170. // Check the PHI consistency.
  4171. if (!PHI)
  4172. PHI = Results[0].first;
  4173. else if (PHI != Results[0].first)
  4174. return false;
  4175. }
  4176. // Find the default result value.
  4177. SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
  4178. BasicBlock *DefaultDest = SI->getDefaultDest();
  4179. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
  4180. DL, TTI);
  4181. // If the default value is not found abort unless the default destination
  4182. // is unreachable.
  4183. DefaultResult =
  4184. DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
  4185. if ((!DefaultResult &&
  4186. !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
  4187. return false;
  4188. return true;
  4189. }
  4190. // Helper function that checks if it is possible to transform a switch with only
  4191. // two cases (or two cases + default) that produces a result into a select.
  4192. // Example:
  4193. // switch (a) {
  4194. // case 10: %0 = icmp eq i32 %a, 10
  4195. // return 10; %1 = select i1 %0, i32 10, i32 4
  4196. // case 20: ----> %2 = icmp eq i32 %a, 20
  4197. // return 2; %3 = select i1 %2, i32 2, i32 %1
  4198. // default:
  4199. // return 4;
  4200. // }
  4201. static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
  4202. Constant *DefaultResult, Value *Condition,
  4203. IRBuilder<> &Builder) {
  4204. assert(ResultVector.size() == 2 &&
  4205. "We should have exactly two unique results at this point");
  4206. // If we are selecting between only two cases transform into a simple
  4207. // select or a two-way select if default is possible.
  4208. if (ResultVector[0].second.size() == 1 &&
  4209. ResultVector[1].second.size() == 1) {
  4210. ConstantInt *const FirstCase = ResultVector[0].second[0];
  4211. ConstantInt *const SecondCase = ResultVector[1].second[0];
  4212. bool DefaultCanTrigger = DefaultResult;
  4213. Value *SelectValue = ResultVector[1].first;
  4214. if (DefaultCanTrigger) {
  4215. Value *const ValueCompare =
  4216. Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
  4217. SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
  4218. DefaultResult, "switch.select");
  4219. }
  4220. Value *const ValueCompare =
  4221. Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
  4222. return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
  4223. SelectValue, "switch.select");
  4224. }
  4225. return nullptr;
  4226. }
  4227. // Helper function to cleanup a switch instruction that has been converted into
  4228. // a select, fixing up PHI nodes and basic blocks.
  4229. static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
  4230. Value *SelectValue,
  4231. IRBuilder<> &Builder) {
  4232. BasicBlock *SelectBB = SI->getParent();
  4233. while (PHI->getBasicBlockIndex(SelectBB) >= 0)
  4234. PHI->removeIncomingValue(SelectBB);
  4235. PHI->addIncoming(SelectValue, SelectBB);
  4236. Builder.CreateBr(PHI->getParent());
  4237. // Remove the switch.
  4238. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  4239. BasicBlock *Succ = SI->getSuccessor(i);
  4240. if (Succ == PHI->getParent())
  4241. continue;
  4242. Succ->removePredecessor(SelectBB);
  4243. }
  4244. SI->eraseFromParent();
  4245. }
  4246. /// If the switch is only used to initialize one or more
  4247. /// phi nodes in a common successor block with only two different
  4248. /// constant values, replace the switch with select.
  4249. static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
  4250. const DataLayout &DL,
  4251. const TargetTransformInfo &TTI) {
  4252. Value *const Cond = SI->getCondition();
  4253. PHINode *PHI = nullptr;
  4254. BasicBlock *CommonDest = nullptr;
  4255. Constant *DefaultResult;
  4256. SwitchCaseResultVectorTy UniqueResults;
  4257. // Collect all the cases that will deliver the same value from the switch.
  4258. if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
  4259. DL, TTI, 2, 1))
  4260. return false;
  4261. // Selects choose between maximum two values.
  4262. if (UniqueResults.size() != 2)
  4263. return false;
  4264. assert(PHI != nullptr && "PHI for value select not found");
  4265. Builder.SetInsertPoint(SI);
  4266. Value *SelectValue =
  4267. ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
  4268. if (SelectValue) {
  4269. RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
  4270. return true;
  4271. }
  4272. // The switch couldn't be converted into a select.
  4273. return false;
  4274. }
  4275. namespace {
  4276. /// This class represents a lookup table that can be used to replace a switch.
  4277. class SwitchLookupTable {
  4278. public:
  4279. /// Create a lookup table to use as a switch replacement with the contents
  4280. /// of Values, using DefaultValue to fill any holes in the table.
  4281. SwitchLookupTable(
  4282. Module &M, uint64_t TableSize, ConstantInt *Offset,
  4283. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  4284. Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
  4285. /// Build instructions with Builder to retrieve the value at
  4286. /// the position given by Index in the lookup table.
  4287. Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
  4288. /// Return true if a table with TableSize elements of
  4289. /// type ElementType would fit in a target-legal register.
  4290. static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
  4291. Type *ElementType);
  4292. private:
  4293. // Depending on the contents of the table, it can be represented in
  4294. // different ways.
  4295. enum {
  4296. // For tables where each element contains the same value, we just have to
  4297. // store that single value and return it for each lookup.
  4298. SingleValueKind,
  4299. // For tables where there is a linear relationship between table index
  4300. // and values. We calculate the result with a simple multiplication
  4301. // and addition instead of a table lookup.
  4302. LinearMapKind,
  4303. // For small tables with integer elements, we can pack them into a bitmap
  4304. // that fits into a target-legal register. Values are retrieved by
  4305. // shift and mask operations.
  4306. BitMapKind,
  4307. // The table is stored as an array of values. Values are retrieved by load
  4308. // instructions from the table.
  4309. ArrayKind
  4310. } Kind;
  4311. // For SingleValueKind, this is the single value.
  4312. Constant *SingleValue = nullptr;
  4313. // For BitMapKind, this is the bitmap.
  4314. ConstantInt *BitMap = nullptr;
  4315. IntegerType *BitMapElementTy = nullptr;
  4316. // For LinearMapKind, these are the constants used to derive the value.
  4317. ConstantInt *LinearOffset = nullptr;
  4318. ConstantInt *LinearMultiplier = nullptr;
  4319. // For ArrayKind, this is the array.
  4320. GlobalVariable *Array = nullptr;
  4321. };
  4322. } // end anonymous namespace
  4323. SwitchLookupTable::SwitchLookupTable(
  4324. Module &M, uint64_t TableSize, ConstantInt *Offset,
  4325. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  4326. Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
  4327. assert(Values.size() && "Can't build lookup table without values!");
  4328. assert(TableSize >= Values.size() && "Can't fit values in table!");
  4329. // If all values in the table are equal, this is that value.
  4330. SingleValue = Values.begin()->second;
  4331. Type *ValueType = Values.begin()->second->getType();
  4332. // Build up the table contents.
  4333. SmallVector<Constant *, 64> TableContents(TableSize);
  4334. for (size_t I = 0, E = Values.size(); I != E; ++I) {
  4335. ConstantInt *CaseVal = Values[I].first;
  4336. Constant *CaseRes = Values[I].second;
  4337. assert(CaseRes->getType() == ValueType);
  4338. uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
  4339. TableContents[Idx] = CaseRes;
  4340. if (CaseRes != SingleValue)
  4341. SingleValue = nullptr;
  4342. }
  4343. // Fill in any holes in the table with the default result.
  4344. if (Values.size() < TableSize) {
  4345. assert(DefaultValue &&
  4346. "Need a default value to fill the lookup table holes.");
  4347. assert(DefaultValue->getType() == ValueType);
  4348. for (uint64_t I = 0; I < TableSize; ++I) {
  4349. if (!TableContents[I])
  4350. TableContents[I] = DefaultValue;
  4351. }
  4352. if (DefaultValue != SingleValue)
  4353. SingleValue = nullptr;
  4354. }
  4355. // If each element in the table contains the same value, we only need to store
  4356. // that single value.
  4357. if (SingleValue) {
  4358. Kind = SingleValueKind;
  4359. return;
  4360. }
  4361. // Check if we can derive the value with a linear transformation from the
  4362. // table index.
  4363. if (isa<IntegerType>(ValueType)) {
  4364. bool LinearMappingPossible = true;
  4365. APInt PrevVal;
  4366. APInt DistToPrev;
  4367. assert(TableSize >= 2 && "Should be a SingleValue table.");
  4368. // Check if there is the same distance between two consecutive values.
  4369. for (uint64_t I = 0; I < TableSize; ++I) {
  4370. ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
  4371. if (!ConstVal) {
  4372. // This is an undef. We could deal with it, but undefs in lookup tables
  4373. // are very seldom. It's probably not worth the additional complexity.
  4374. LinearMappingPossible = false;
  4375. break;
  4376. }
  4377. const APInt &Val = ConstVal->getValue();
  4378. if (I != 0) {
  4379. APInt Dist = Val - PrevVal;
  4380. if (I == 1) {
  4381. DistToPrev = Dist;
  4382. } else if (Dist != DistToPrev) {
  4383. LinearMappingPossible = false;
  4384. break;
  4385. }
  4386. }
  4387. PrevVal = Val;
  4388. }
  4389. if (LinearMappingPossible) {
  4390. LinearOffset = cast<ConstantInt>(TableContents[0]);
  4391. LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
  4392. Kind = LinearMapKind;
  4393. ++NumLinearMaps;
  4394. return;
  4395. }
  4396. }
  4397. // If the type is integer and the table fits in a register, build a bitmap.
  4398. if (WouldFitInRegister(DL, TableSize, ValueType)) {
  4399. IntegerType *IT = cast<IntegerType>(ValueType);
  4400. APInt TableInt(TableSize * IT->getBitWidth(), 0);
  4401. for (uint64_t I = TableSize; I > 0; --I) {
  4402. TableInt <<= IT->getBitWidth();
  4403. // Insert values into the bitmap. Undef values are set to zero.
  4404. if (!isa<UndefValue>(TableContents[I - 1])) {
  4405. ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
  4406. TableInt |= Val->getValue().zext(TableInt.getBitWidth());
  4407. }
  4408. }
  4409. BitMap = ConstantInt::get(M.getContext(), TableInt);
  4410. BitMapElementTy = IT;
  4411. Kind = BitMapKind;
  4412. ++NumBitMaps;
  4413. return;
  4414. }
  4415. // Store the table in an array.
  4416. ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
  4417. Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
  4418. Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
  4419. GlobalVariable::PrivateLinkage, Initializer,
  4420. "switch.table." + FuncName);
  4421. Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  4422. // Set the alignment to that of an array items. We will be only loading one
  4423. // value out of it.
  4424. Array->setAlignment(DL.getPrefTypeAlignment(ValueType));
  4425. Kind = ArrayKind;
  4426. }
  4427. Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
  4428. switch (Kind) {
  4429. case SingleValueKind:
  4430. return SingleValue;
  4431. case LinearMapKind: {
  4432. // Derive the result value from the input value.
  4433. Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
  4434. false, "switch.idx.cast");
  4435. if (!LinearMultiplier->isOne())
  4436. Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
  4437. if (!LinearOffset->isZero())
  4438. Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
  4439. return Result;
  4440. }
  4441. case BitMapKind: {
  4442. // Type of the bitmap (e.g. i59).
  4443. IntegerType *MapTy = BitMap->getType();
  4444. // Cast Index to the same type as the bitmap.
  4445. // Note: The Index is <= the number of elements in the table, so
  4446. // truncating it to the width of the bitmask is safe.
  4447. Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
  4448. // Multiply the shift amount by the element width.
  4449. ShiftAmt = Builder.CreateMul(
  4450. ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
  4451. "switch.shiftamt");
  4452. // Shift down.
  4453. Value *DownShifted =
  4454. Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
  4455. // Mask off.
  4456. return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
  4457. }
  4458. case ArrayKind: {
  4459. // Make sure the table index will not overflow when treated as signed.
  4460. IntegerType *IT = cast<IntegerType>(Index->getType());
  4461. uint64_t TableSize =
  4462. Array->getInitializer()->getType()->getArrayNumElements();
  4463. if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
  4464. Index = Builder.CreateZExt(
  4465. Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
  4466. "switch.tableidx.zext");
  4467. Value *GEPIndices[] = {Builder.getInt32(0), Index};
  4468. Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
  4469. GEPIndices, "switch.gep");
  4470. return Builder.CreateLoad(GEP, "switch.load");
  4471. }
  4472. }
  4473. llvm_unreachable("Unknown lookup table kind!");
  4474. }
  4475. bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
  4476. uint64_t TableSize,
  4477. Type *ElementType) {
  4478. auto *IT = dyn_cast<IntegerType>(ElementType);
  4479. if (!IT)
  4480. return false;
  4481. // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
  4482. // are <= 15, we could try to narrow the type.
  4483. // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
  4484. if (TableSize >= UINT_MAX / IT->getBitWidth())
  4485. return false;
  4486. return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
  4487. }
  4488. /// Determine whether a lookup table should be built for this switch, based on
  4489. /// the number of cases, size of the table, and the types of the results.
  4490. static bool
  4491. ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
  4492. const TargetTransformInfo &TTI, const DataLayout &DL,
  4493. const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
  4494. if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
  4495. return false; // TableSize overflowed, or mul below might overflow.
  4496. bool AllTablesFitInRegister = true;
  4497. bool HasIllegalType = false;
  4498. for (const auto &I : ResultTypes) {
  4499. Type *Ty = I.second;
  4500. // Saturate this flag to true.
  4501. HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
  4502. // Saturate this flag to false.
  4503. AllTablesFitInRegister =
  4504. AllTablesFitInRegister &&
  4505. SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
  4506. // If both flags saturate, we're done. NOTE: This *only* works with
  4507. // saturating flags, and all flags have to saturate first due to the
  4508. // non-deterministic behavior of iterating over a dense map.
  4509. if (HasIllegalType && !AllTablesFitInRegister)
  4510. break;
  4511. }
  4512. // If each table would fit in a register, we should build it anyway.
  4513. if (AllTablesFitInRegister)
  4514. return true;
  4515. // Don't build a table that doesn't fit in-register if it has illegal types.
  4516. if (HasIllegalType)
  4517. return false;
  4518. // The table density should be at least 40%. This is the same criterion as for
  4519. // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
  4520. // FIXME: Find the best cut-off.
  4521. return SI->getNumCases() * 10 >= TableSize * 4;
  4522. }
  4523. /// Try to reuse the switch table index compare. Following pattern:
  4524. /// \code
  4525. /// if (idx < tablesize)
  4526. /// r = table[idx]; // table does not contain default_value
  4527. /// else
  4528. /// r = default_value;
  4529. /// if (r != default_value)
  4530. /// ...
  4531. /// \endcode
  4532. /// Is optimized to:
  4533. /// \code
  4534. /// cond = idx < tablesize;
  4535. /// if (cond)
  4536. /// r = table[idx];
  4537. /// else
  4538. /// r = default_value;
  4539. /// if (cond)
  4540. /// ...
  4541. /// \endcode
  4542. /// Jump threading will then eliminate the second if(cond).
  4543. static void reuseTableCompare(
  4544. User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
  4545. Constant *DefaultValue,
  4546. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
  4547. ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
  4548. if (!CmpInst)
  4549. return;
  4550. // We require that the compare is in the same block as the phi so that jump
  4551. // threading can do its work afterwards.
  4552. if (CmpInst->getParent() != PhiBlock)
  4553. return;
  4554. Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
  4555. if (!CmpOp1)
  4556. return;
  4557. Value *RangeCmp = RangeCheckBranch->getCondition();
  4558. Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
  4559. Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
  4560. // Check if the compare with the default value is constant true or false.
  4561. Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  4562. DefaultValue, CmpOp1, true);
  4563. if (DefaultConst != TrueConst && DefaultConst != FalseConst)
  4564. return;
  4565. // Check if the compare with the case values is distinct from the default
  4566. // compare result.
  4567. for (auto ValuePair : Values) {
  4568. Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  4569. ValuePair.second, CmpOp1, true);
  4570. if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
  4571. return;
  4572. assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
  4573. "Expect true or false as compare result.");
  4574. }
  4575. // Check if the branch instruction dominates the phi node. It's a simple
  4576. // dominance check, but sufficient for our needs.
  4577. // Although this check is invariant in the calling loops, it's better to do it
  4578. // at this late stage. Practically we do it at most once for a switch.
  4579. BasicBlock *BranchBlock = RangeCheckBranch->getParent();
  4580. for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
  4581. BasicBlock *Pred = *PI;
  4582. if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
  4583. return;
  4584. }
  4585. if (DefaultConst == FalseConst) {
  4586. // The compare yields the same result. We can replace it.
  4587. CmpInst->replaceAllUsesWith(RangeCmp);
  4588. ++NumTableCmpReuses;
  4589. } else {
  4590. // The compare yields the same result, just inverted. We can replace it.
  4591. Value *InvertedTableCmp = BinaryOperator::CreateXor(
  4592. RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
  4593. RangeCheckBranch);
  4594. CmpInst->replaceAllUsesWith(InvertedTableCmp);
  4595. ++NumTableCmpReuses;
  4596. }
  4597. }
  4598. /// If the switch is only used to initialize one or more phi nodes in a common
  4599. /// successor block with different constant values, replace the switch with
  4600. /// lookup tables.
  4601. static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
  4602. const DataLayout &DL,
  4603. const TargetTransformInfo &TTI) {
  4604. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  4605. Function *Fn = SI->getParent()->getParent();
  4606. // Only build lookup table when we have a target that supports it or the
  4607. // attribute is not set.
  4608. if (!TTI.shouldBuildLookupTables() ||
  4609. (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
  4610. return false;
  4611. // FIXME: If the switch is too sparse for a lookup table, perhaps we could
  4612. // split off a dense part and build a lookup table for that.
  4613. // FIXME: This creates arrays of GEPs to constant strings, which means each
  4614. // GEP needs a runtime relocation in PIC code. We should just build one big
  4615. // string and lookup indices into that.
  4616. // Ignore switches with less than three cases. Lookup tables will not make
  4617. // them faster, so we don't analyze them.
  4618. if (SI->getNumCases() < 3)
  4619. return false;
  4620. // Figure out the corresponding result for each case value and phi node in the
  4621. // common destination, as well as the min and max case values.
  4622. assert(!empty(SI->cases()));
  4623. SwitchInst::CaseIt CI = SI->case_begin();
  4624. ConstantInt *MinCaseVal = CI->getCaseValue();
  4625. ConstantInt *MaxCaseVal = CI->getCaseValue();
  4626. BasicBlock *CommonDest = nullptr;
  4627. using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
  4628. SmallDenseMap<PHINode *, ResultListTy> ResultLists;
  4629. SmallDenseMap<PHINode *, Constant *> DefaultResults;
  4630. SmallDenseMap<PHINode *, Type *> ResultTypes;
  4631. SmallVector<PHINode *, 4> PHIs;
  4632. for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
  4633. ConstantInt *CaseVal = CI->getCaseValue();
  4634. if (CaseVal->getValue().slt(MinCaseVal->getValue()))
  4635. MinCaseVal = CaseVal;
  4636. if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
  4637. MaxCaseVal = CaseVal;
  4638. // Resulting value at phi nodes for this case value.
  4639. using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
  4640. ResultsTy Results;
  4641. if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
  4642. Results, DL, TTI))
  4643. return false;
  4644. // Append the result from this case to the list for each phi.
  4645. for (const auto &I : Results) {
  4646. PHINode *PHI = I.first;
  4647. Constant *Value = I.second;
  4648. if (!ResultLists.count(PHI))
  4649. PHIs.push_back(PHI);
  4650. ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
  4651. }
  4652. }
  4653. // Keep track of the result types.
  4654. for (PHINode *PHI : PHIs) {
  4655. ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
  4656. }
  4657. uint64_t NumResults = ResultLists[PHIs[0]].size();
  4658. APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
  4659. uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
  4660. bool TableHasHoles = (NumResults < TableSize);
  4661. // If the table has holes, we need a constant result for the default case
  4662. // or a bitmask that fits in a register.
  4663. SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
  4664. bool HasDefaultResults =
  4665. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
  4666. DefaultResultsList, DL, TTI);
  4667. bool NeedMask = (TableHasHoles && !HasDefaultResults);
  4668. if (NeedMask) {
  4669. // As an extra penalty for the validity test we require more cases.
  4670. if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
  4671. return false;
  4672. if (!DL.fitsInLegalInteger(TableSize))
  4673. return false;
  4674. }
  4675. for (const auto &I : DefaultResultsList) {
  4676. PHINode *PHI = I.first;
  4677. Constant *Result = I.second;
  4678. DefaultResults[PHI] = Result;
  4679. }
  4680. if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
  4681. return false;
  4682. // Create the BB that does the lookups.
  4683. Module &Mod = *CommonDest->getParent()->getParent();
  4684. BasicBlock *LookupBB = BasicBlock::Create(
  4685. Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
  4686. // Compute the table index value.
  4687. Builder.SetInsertPoint(SI);
  4688. Value *TableIndex;
  4689. if (MinCaseVal->isNullValue())
  4690. TableIndex = SI->getCondition();
  4691. else
  4692. TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
  4693. "switch.tableidx");
  4694. // Compute the maximum table size representable by the integer type we are
  4695. // switching upon.
  4696. unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
  4697. uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
  4698. assert(MaxTableSize >= TableSize &&
  4699. "It is impossible for a switch to have more entries than the max "
  4700. "representable value of its input integer type's size.");
  4701. // If the default destination is unreachable, or if the lookup table covers
  4702. // all values of the conditional variable, branch directly to the lookup table
  4703. // BB. Otherwise, check that the condition is within the case range.
  4704. const bool DefaultIsReachable =
  4705. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  4706. const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
  4707. BranchInst *RangeCheckBranch = nullptr;
  4708. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  4709. Builder.CreateBr(LookupBB);
  4710. // Note: We call removeProdecessor later since we need to be able to get the
  4711. // PHI value for the default case in case we're using a bit mask.
  4712. } else {
  4713. Value *Cmp = Builder.CreateICmpULT(
  4714. TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
  4715. RangeCheckBranch =
  4716. Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
  4717. }
  4718. // Populate the BB that does the lookups.
  4719. Builder.SetInsertPoint(LookupBB);
  4720. if (NeedMask) {
  4721. // Before doing the lookup, we do the hole check. The LookupBB is therefore
  4722. // re-purposed to do the hole check, and we create a new LookupBB.
  4723. BasicBlock *MaskBB = LookupBB;
  4724. MaskBB->setName("switch.hole_check");
  4725. LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
  4726. CommonDest->getParent(), CommonDest);
  4727. // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
  4728. // unnecessary illegal types.
  4729. uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
  4730. APInt MaskInt(TableSizePowOf2, 0);
  4731. APInt One(TableSizePowOf2, 1);
  4732. // Build bitmask; fill in a 1 bit for every case.
  4733. const ResultListTy &ResultList = ResultLists[PHIs[0]];
  4734. for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
  4735. uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
  4736. .getLimitedValue();
  4737. MaskInt |= One << Idx;
  4738. }
  4739. ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
  4740. // Get the TableIndex'th bit of the bitmask.
  4741. // If this bit is 0 (meaning hole) jump to the default destination,
  4742. // else continue with table lookup.
  4743. IntegerType *MapTy = TableMask->getType();
  4744. Value *MaskIndex =
  4745. Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
  4746. Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
  4747. Value *LoBit = Builder.CreateTrunc(
  4748. Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
  4749. Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
  4750. Builder.SetInsertPoint(LookupBB);
  4751. AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
  4752. }
  4753. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  4754. // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
  4755. // do not delete PHINodes here.
  4756. SI->getDefaultDest()->removePredecessor(SI->getParent(),
  4757. /*DontDeleteUselessPHIs=*/true);
  4758. }
  4759. bool ReturnedEarly = false;
  4760. for (PHINode *PHI : PHIs) {
  4761. const ResultListTy &ResultList = ResultLists[PHI];
  4762. // If using a bitmask, use any value to fill the lookup table holes.
  4763. Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
  4764. StringRef FuncName = Fn->getName();
  4765. SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
  4766. FuncName);
  4767. Value *Result = Table.BuildLookup(TableIndex, Builder);
  4768. // If the result is used to return immediately from the function, we want to
  4769. // do that right here.
  4770. if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
  4771. PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
  4772. Builder.CreateRet(Result);
  4773. ReturnedEarly = true;
  4774. break;
  4775. }
  4776. // Do a small peephole optimization: re-use the switch table compare if
  4777. // possible.
  4778. if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
  4779. BasicBlock *PhiBlock = PHI->getParent();
  4780. // Search for compare instructions which use the phi.
  4781. for (auto *User : PHI->users()) {
  4782. reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
  4783. }
  4784. }
  4785. PHI->addIncoming(Result, LookupBB);
  4786. }
  4787. if (!ReturnedEarly)
  4788. Builder.CreateBr(CommonDest);
  4789. // Remove the switch.
  4790. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  4791. BasicBlock *Succ = SI->getSuccessor(i);
  4792. if (Succ == SI->getDefaultDest())
  4793. continue;
  4794. Succ->removePredecessor(SI->getParent());
  4795. }
  4796. SI->eraseFromParent();
  4797. ++NumLookupTables;
  4798. if (NeedMask)
  4799. ++NumLookupTablesHoles;
  4800. return true;
  4801. }
  4802. static bool isSwitchDense(ArrayRef<int64_t> Values) {
  4803. // See also SelectionDAGBuilder::isDense(), which this function was based on.
  4804. uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
  4805. uint64_t Range = Diff + 1;
  4806. uint64_t NumCases = Values.size();
  4807. // 40% is the default density for building a jump table in optsize/minsize mode.
  4808. uint64_t MinDensity = 40;
  4809. return NumCases * 100 >= Range * MinDensity;
  4810. }
  4811. /// Try to transform a switch that has "holes" in it to a contiguous sequence
  4812. /// of cases.
  4813. ///
  4814. /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
  4815. /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
  4816. ///
  4817. /// This converts a sparse switch into a dense switch which allows better
  4818. /// lowering and could also allow transforming into a lookup table.
  4819. static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
  4820. const DataLayout &DL,
  4821. const TargetTransformInfo &TTI) {
  4822. auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
  4823. if (CondTy->getIntegerBitWidth() > 64 ||
  4824. !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
  4825. return false;
  4826. // Only bother with this optimization if there are more than 3 switch cases;
  4827. // SDAG will only bother creating jump tables for 4 or more cases.
  4828. if (SI->getNumCases() < 4)
  4829. return false;
  4830. // This transform is agnostic to the signedness of the input or case values. We
  4831. // can treat the case values as signed or unsigned. We can optimize more common
  4832. // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
  4833. // as signed.
  4834. SmallVector<int64_t,4> Values;
  4835. for (auto &C : SI->cases())
  4836. Values.push_back(C.getCaseValue()->getValue().getSExtValue());
  4837. llvm::sort(Values);
  4838. // If the switch is already dense, there's nothing useful to do here.
  4839. if (isSwitchDense(Values))
  4840. return false;
  4841. // First, transform the values such that they start at zero and ascend.
  4842. int64_t Base = Values[0];
  4843. for (auto &V : Values)
  4844. V -= (uint64_t)(Base);
  4845. // Now we have signed numbers that have been shifted so that, given enough
  4846. // precision, there are no negative values. Since the rest of the transform
  4847. // is bitwise only, we switch now to an unsigned representation.
  4848. uint64_t GCD = 0;
  4849. for (auto &V : Values)
  4850. GCD = GreatestCommonDivisor64(GCD, (uint64_t)V);
  4851. // This transform can be done speculatively because it is so cheap - it results
  4852. // in a single rotate operation being inserted. This can only happen if the
  4853. // factor extracted is a power of 2.
  4854. // FIXME: If the GCD is an odd number we can multiply by the multiplicative
  4855. // inverse of GCD and then perform this transform.
  4856. // FIXME: It's possible that optimizing a switch on powers of two might also
  4857. // be beneficial - flag values are often powers of two and we could use a CLZ
  4858. // as the key function.
  4859. if (GCD <= 1 || !isPowerOf2_64(GCD))
  4860. // No common divisor found or too expensive to compute key function.
  4861. return false;
  4862. unsigned Shift = Log2_64(GCD);
  4863. for (auto &V : Values)
  4864. V = (int64_t)((uint64_t)V >> Shift);
  4865. if (!isSwitchDense(Values))
  4866. // Transform didn't create a dense switch.
  4867. return false;
  4868. // The obvious transform is to shift the switch condition right and emit a
  4869. // check that the condition actually cleanly divided by GCD, i.e.
  4870. // C & (1 << Shift - 1) == 0
  4871. // inserting a new CFG edge to handle the case where it didn't divide cleanly.
  4872. //
  4873. // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
  4874. // shift and puts the shifted-off bits in the uppermost bits. If any of these
  4875. // are nonzero then the switch condition will be very large and will hit the
  4876. // default case.
  4877. auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
  4878. Builder.SetInsertPoint(SI);
  4879. auto *ShiftC = ConstantInt::get(Ty, Shift);
  4880. auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
  4881. auto *LShr = Builder.CreateLShr(Sub, ShiftC);
  4882. auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
  4883. auto *Rot = Builder.CreateOr(LShr, Shl);
  4884. SI->replaceUsesOfWith(SI->getCondition(), Rot);
  4885. for (auto Case : SI->cases()) {
  4886. auto *Orig = Case.getCaseValue();
  4887. auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
  4888. Case.setValue(
  4889. cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
  4890. }
  4891. return true;
  4892. }
  4893. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  4894. BasicBlock *BB = SI->getParent();
  4895. if (isValueEqualityComparison(SI)) {
  4896. // If we only have one predecessor, and if it is a branch on this value,
  4897. // see if that predecessor totally determines the outcome of this switch.
  4898. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  4899. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  4900. return requestResimplify();
  4901. Value *Cond = SI->getCondition();
  4902. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  4903. if (SimplifySwitchOnSelect(SI, Select))
  4904. return requestResimplify();
  4905. // If the block only contains the switch, see if we can fold the block
  4906. // away into any preds.
  4907. if (SI == &*BB->instructionsWithoutDebug().begin())
  4908. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  4909. return requestResimplify();
  4910. }
  4911. // Try to transform the switch into an icmp and a branch.
  4912. if (TurnSwitchRangeIntoICmp(SI, Builder))
  4913. return requestResimplify();
  4914. // Remove unreachable cases.
  4915. if (eliminateDeadSwitchCases(SI, Options.AC, DL))
  4916. return requestResimplify();
  4917. if (switchToSelect(SI, Builder, DL, TTI))
  4918. return requestResimplify();
  4919. if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
  4920. return requestResimplify();
  4921. // The conversion from switch to lookup tables results in difficult-to-analyze
  4922. // code and makes pruning branches much harder. This is a problem if the
  4923. // switch expression itself can still be restricted as a result of inlining or
  4924. // CVP. Therefore, only apply this transformation during late stages of the
  4925. // optimisation pipeline.
  4926. if (Options.ConvertSwitchToLookupTable &&
  4927. SwitchToLookupTable(SI, Builder, DL, TTI))
  4928. return requestResimplify();
  4929. if (ReduceSwitchRange(SI, Builder, DL, TTI))
  4930. return requestResimplify();
  4931. return false;
  4932. }
  4933. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  4934. BasicBlock *BB = IBI->getParent();
  4935. bool Changed = false;
  4936. // Eliminate redundant destinations.
  4937. SmallPtrSet<Value *, 8> Succs;
  4938. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  4939. BasicBlock *Dest = IBI->getDestination(i);
  4940. if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
  4941. Dest->removePredecessor(BB);
  4942. IBI->removeDestination(i);
  4943. --i;
  4944. --e;
  4945. Changed = true;
  4946. }
  4947. }
  4948. if (IBI->getNumDestinations() == 0) {
  4949. // If the indirectbr has no successors, change it to unreachable.
  4950. new UnreachableInst(IBI->getContext(), IBI);
  4951. EraseTerminatorAndDCECond(IBI);
  4952. return true;
  4953. }
  4954. if (IBI->getNumDestinations() == 1) {
  4955. // If the indirectbr has one successor, change it to a direct branch.
  4956. BranchInst::Create(IBI->getDestination(0), IBI);
  4957. EraseTerminatorAndDCECond(IBI);
  4958. return true;
  4959. }
  4960. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  4961. if (SimplifyIndirectBrOnSelect(IBI, SI))
  4962. return requestResimplify();
  4963. }
  4964. return Changed;
  4965. }
  4966. /// Given an block with only a single landing pad and a unconditional branch
  4967. /// try to find another basic block which this one can be merged with. This
  4968. /// handles cases where we have multiple invokes with unique landing pads, but
  4969. /// a shared handler.
  4970. ///
  4971. /// We specifically choose to not worry about merging non-empty blocks
  4972. /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
  4973. /// practice, the optimizer produces empty landing pad blocks quite frequently
  4974. /// when dealing with exception dense code. (see: instcombine, gvn, if-else
  4975. /// sinking in this file)
  4976. ///
  4977. /// This is primarily a code size optimization. We need to avoid performing
  4978. /// any transform which might inhibit optimization (such as our ability to
  4979. /// specialize a particular handler via tail commoning). We do this by not
  4980. /// merging any blocks which require us to introduce a phi. Since the same
  4981. /// values are flowing through both blocks, we don't lose any ability to
  4982. /// specialize. If anything, we make such specialization more likely.
  4983. ///
  4984. /// TODO - This transformation could remove entries from a phi in the target
  4985. /// block when the inputs in the phi are the same for the two blocks being
  4986. /// merged. In some cases, this could result in removal of the PHI entirely.
  4987. static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
  4988. BasicBlock *BB) {
  4989. auto Succ = BB->getUniqueSuccessor();
  4990. assert(Succ);
  4991. // If there's a phi in the successor block, we'd likely have to introduce
  4992. // a phi into the merged landing pad block.
  4993. if (isa<PHINode>(*Succ->begin()))
  4994. return false;
  4995. for (BasicBlock *OtherPred : predecessors(Succ)) {
  4996. if (BB == OtherPred)
  4997. continue;
  4998. BasicBlock::iterator I = OtherPred->begin();
  4999. LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
  5000. if (!LPad2 || !LPad2->isIdenticalTo(LPad))
  5001. continue;
  5002. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5003. ;
  5004. BranchInst *BI2 = dyn_cast<BranchInst>(I);
  5005. if (!BI2 || !BI2->isIdenticalTo(BI))
  5006. continue;
  5007. // We've found an identical block. Update our predecessors to take that
  5008. // path instead and make ourselves dead.
  5009. SmallPtrSet<BasicBlock *, 16> Preds;
  5010. Preds.insert(pred_begin(BB), pred_end(BB));
  5011. for (BasicBlock *Pred : Preds) {
  5012. InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
  5013. assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
  5014. "unexpected successor");
  5015. II->setUnwindDest(OtherPred);
  5016. }
  5017. // The debug info in OtherPred doesn't cover the merged control flow that
  5018. // used to go through BB. We need to delete it or update it.
  5019. for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
  5020. Instruction &Inst = *I;
  5021. I++;
  5022. if (isa<DbgInfoIntrinsic>(Inst))
  5023. Inst.eraseFromParent();
  5024. }
  5025. SmallPtrSet<BasicBlock *, 16> Succs;
  5026. Succs.insert(succ_begin(BB), succ_end(BB));
  5027. for (BasicBlock *Succ : Succs) {
  5028. Succ->removePredecessor(BB);
  5029. }
  5030. IRBuilder<> Builder(BI);
  5031. Builder.CreateUnreachable();
  5032. BI->eraseFromParent();
  5033. return true;
  5034. }
  5035. return false;
  5036. }
  5037. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
  5038. IRBuilder<> &Builder) {
  5039. BasicBlock *BB = BI->getParent();
  5040. BasicBlock *Succ = BI->getSuccessor(0);
  5041. // If the Terminator is the only non-phi instruction, simplify the block.
  5042. // If LoopHeader is provided, check if the block or its successor is a loop
  5043. // header. (This is for early invocations before loop simplify and
  5044. // vectorization to keep canonical loop forms for nested loops. These blocks
  5045. // can be eliminated when the pass is invoked later in the back-end.)
  5046. // Note that if BB has only one predecessor then we do not introduce new
  5047. // backedge, so we can eliminate BB.
  5048. bool NeedCanonicalLoop =
  5049. Options.NeedCanonicalLoop &&
  5050. (LoopHeaders && pred_size(BB) > 1 &&
  5051. (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
  5052. BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
  5053. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  5054. !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
  5055. return true;
  5056. // If the only instruction in the block is a seteq/setne comparison against a
  5057. // constant, try to simplify the block.
  5058. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  5059. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  5060. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5061. ;
  5062. if (I->isTerminator() &&
  5063. tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
  5064. return true;
  5065. }
  5066. // See if we can merge an empty landing pad block with another which is
  5067. // equivalent.
  5068. if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
  5069. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5070. ;
  5071. if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
  5072. return true;
  5073. }
  5074. // If this basic block is ONLY a compare and a branch, and if a predecessor
  5075. // branches to us and our successor, fold the comparison into the
  5076. // predecessor and use logical operations to update the incoming value
  5077. // for PHI nodes in common successor.
  5078. if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
  5079. return requestResimplify();
  5080. return false;
  5081. }
  5082. static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
  5083. BasicBlock *PredPred = nullptr;
  5084. for (auto *P : predecessors(BB)) {
  5085. BasicBlock *PPred = P->getSinglePredecessor();
  5086. if (!PPred || (PredPred && PredPred != PPred))
  5087. return nullptr;
  5088. PredPred = PPred;
  5089. }
  5090. return PredPred;
  5091. }
  5092. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  5093. BasicBlock *BB = BI->getParent();
  5094. const Function *Fn = BB->getParent();
  5095. if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
  5096. return false;
  5097. // Conditional branch
  5098. if (isValueEqualityComparison(BI)) {
  5099. // If we only have one predecessor, and if it is a branch on this value,
  5100. // see if that predecessor totally determines the outcome of this
  5101. // switch.
  5102. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  5103. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  5104. return requestResimplify();
  5105. // This block must be empty, except for the setcond inst, if it exists.
  5106. // Ignore dbg intrinsics.
  5107. auto I = BB->instructionsWithoutDebug().begin();
  5108. if (&*I == BI) {
  5109. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  5110. return requestResimplify();
  5111. } else if (&*I == cast<Instruction>(BI->getCondition())) {
  5112. ++I;
  5113. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  5114. return requestResimplify();
  5115. }
  5116. }
  5117. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  5118. if (SimplifyBranchOnICmpChain(BI, Builder, DL))
  5119. return true;
  5120. // If this basic block has a single dominating predecessor block and the
  5121. // dominating block's condition implies BI's condition, we know the direction
  5122. // of the BI branch.
  5123. if (BasicBlock *Dom = BB->getSinglePredecessor()) {
  5124. auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
  5125. if (PBI && PBI->isConditional() &&
  5126. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  5127. assert(PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB);
  5128. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  5129. Optional<bool> Implication = isImpliedCondition(
  5130. PBI->getCondition(), BI->getCondition(), DL, CondIsTrue);
  5131. if (Implication) {
  5132. // Turn this into a branch on constant.
  5133. auto *OldCond = BI->getCondition();
  5134. ConstantInt *CI = *Implication
  5135. ? ConstantInt::getTrue(BB->getContext())
  5136. : ConstantInt::getFalse(BB->getContext());
  5137. BI->setCondition(CI);
  5138. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  5139. return requestResimplify();
  5140. }
  5141. }
  5142. }
  5143. // If this basic block is ONLY a compare and a branch, and if a predecessor
  5144. // branches to us and one of our successors, fold the comparison into the
  5145. // predecessor and use logical operations to pick the right destination.
  5146. if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
  5147. return requestResimplify();
  5148. // We have a conditional branch to two blocks that are only reachable
  5149. // from BI. We know that the condbr dominates the two blocks, so see if
  5150. // there is any identical code in the "then" and "else" blocks. If so, we
  5151. // can hoist it up to the branching block.
  5152. if (BI->getSuccessor(0)->getSinglePredecessor()) {
  5153. if (BI->getSuccessor(1)->getSinglePredecessor()) {
  5154. if (HoistThenElseCodeToIf(BI, TTI))
  5155. return requestResimplify();
  5156. } else {
  5157. // If Successor #1 has multiple preds, we may be able to conditionally
  5158. // execute Successor #0 if it branches to Successor #1.
  5159. Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
  5160. if (Succ0TI->getNumSuccessors() == 1 &&
  5161. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  5162. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
  5163. return requestResimplify();
  5164. }
  5165. } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
  5166. // If Successor #0 has multiple preds, we may be able to conditionally
  5167. // execute Successor #1 if it branches to Successor #0.
  5168. Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
  5169. if (Succ1TI->getNumSuccessors() == 1 &&
  5170. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  5171. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
  5172. return requestResimplify();
  5173. }
  5174. // If this is a branch on a phi node in the current block, thread control
  5175. // through this block if any PHI node entries are constants.
  5176. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  5177. if (PN->getParent() == BI->getParent())
  5178. if (FoldCondBranchOnPHI(BI, DL, Options.AC))
  5179. return requestResimplify();
  5180. // Scan predecessor blocks for conditional branches.
  5181. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  5182. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  5183. if (PBI != BI && PBI->isConditional())
  5184. if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
  5185. return requestResimplify();
  5186. // Look for diamond patterns.
  5187. if (MergeCondStores)
  5188. if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
  5189. if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
  5190. if (PBI != BI && PBI->isConditional())
  5191. if (mergeConditionalStores(PBI, BI, DL))
  5192. return requestResimplify();
  5193. return false;
  5194. }
  5195. /// Check if passing a value to an instruction will cause undefined behavior.
  5196. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  5197. Constant *C = dyn_cast<Constant>(V);
  5198. if (!C)
  5199. return false;
  5200. if (I->use_empty())
  5201. return false;
  5202. if (C->isNullValue() || isa<UndefValue>(C)) {
  5203. // Only look at the first use, avoid hurting compile time with long uselists
  5204. User *Use = *I->user_begin();
  5205. // Now make sure that there are no instructions in between that can alter
  5206. // control flow (eg. calls)
  5207. for (BasicBlock::iterator
  5208. i = ++BasicBlock::iterator(I),
  5209. UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
  5210. i != UI; ++i)
  5211. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  5212. return false;
  5213. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  5214. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  5215. if (GEP->getPointerOperand() == I)
  5216. return passingValueIsAlwaysUndefined(V, GEP);
  5217. // Look through bitcasts.
  5218. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  5219. return passingValueIsAlwaysUndefined(V, BC);
  5220. // Load from null is undefined.
  5221. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  5222. if (!LI->isVolatile())
  5223. return !NullPointerIsDefined(LI->getFunction(),
  5224. LI->getPointerAddressSpace());
  5225. // Store to null is undefined.
  5226. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  5227. if (!SI->isVolatile())
  5228. return (!NullPointerIsDefined(SI->getFunction(),
  5229. SI->getPointerAddressSpace())) &&
  5230. SI->getPointerOperand() == I;
  5231. // A call to null is undefined.
  5232. if (auto CS = CallSite(Use))
  5233. return !NullPointerIsDefined(CS->getFunction()) &&
  5234. CS.getCalledValue() == I;
  5235. }
  5236. return false;
  5237. }
  5238. /// If BB has an incoming value that will always trigger undefined behavior
  5239. /// (eg. null pointer dereference), remove the branch leading here.
  5240. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  5241. for (PHINode &PHI : BB->phis())
  5242. for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
  5243. if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
  5244. Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
  5245. IRBuilder<> Builder(T);
  5246. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  5247. BB->removePredecessor(PHI.getIncomingBlock(i));
  5248. // Turn uncoditional branches into unreachables and remove the dead
  5249. // destination from conditional branches.
  5250. if (BI->isUnconditional())
  5251. Builder.CreateUnreachable();
  5252. else
  5253. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
  5254. : BI->getSuccessor(0));
  5255. BI->eraseFromParent();
  5256. return true;
  5257. }
  5258. // TODO: SwitchInst.
  5259. }
  5260. return false;
  5261. }
  5262. bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
  5263. bool Changed = false;
  5264. assert(BB && BB->getParent() && "Block not embedded in function!");
  5265. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  5266. // Remove basic blocks that have no predecessors (except the entry block)...
  5267. // or that just have themself as a predecessor. These are unreachable.
  5268. if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
  5269. BB->getSinglePredecessor() == BB) {
  5270. LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
  5271. DeleteDeadBlock(BB);
  5272. return true;
  5273. }
  5274. // Check to see if we can constant propagate this terminator instruction
  5275. // away...
  5276. Changed |= ConstantFoldTerminator(BB, true);
  5277. // Check for and eliminate duplicate PHI nodes in this block.
  5278. Changed |= EliminateDuplicatePHINodes(BB);
  5279. // Check for and remove branches that will always cause undefined behavior.
  5280. Changed |= removeUndefIntroducingPredecessor(BB);
  5281. // Merge basic blocks into their predecessor if there is only one distinct
  5282. // pred, and if there is only one distinct successor of the predecessor, and
  5283. // if there are no PHI nodes.
  5284. if (MergeBlockIntoPredecessor(BB))
  5285. return true;
  5286. if (SinkCommon && Options.SinkCommonInsts)
  5287. Changed |= SinkCommonCodeFromPredecessors(BB);
  5288. IRBuilder<> Builder(BB);
  5289. // If there is a trivial two-entry PHI node in this basic block, and we can
  5290. // eliminate it, do so now.
  5291. if (auto *PN = dyn_cast<PHINode>(BB->begin()))
  5292. if (PN->getNumIncomingValues() == 2)
  5293. Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
  5294. Builder.SetInsertPoint(BB->getTerminator());
  5295. if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  5296. if (BI->isUnconditional()) {
  5297. if (SimplifyUncondBranch(BI, Builder))
  5298. return true;
  5299. } else {
  5300. if (SimplifyCondBranch(BI, Builder))
  5301. return true;
  5302. }
  5303. } else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  5304. if (SimplifyReturn(RI, Builder))
  5305. return true;
  5306. } else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  5307. if (SimplifyResume(RI, Builder))
  5308. return true;
  5309. } else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
  5310. if (SimplifyCleanupReturn(RI))
  5311. return true;
  5312. } else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  5313. if (SimplifySwitch(SI, Builder))
  5314. return true;
  5315. } else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) {
  5316. if (SimplifyUnreachable(UI))
  5317. return true;
  5318. } else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  5319. if (SimplifyIndirectBr(IBI))
  5320. return true;
  5321. }
  5322. return Changed;
  5323. }
  5324. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  5325. bool Changed = false;
  5326. // Repeated simplify BB as long as resimplification is requested.
  5327. do {
  5328. Resimplify = false;
  5329. // Perform one round of simplifcation. Resimplify flag will be set if
  5330. // another iteration is requested.
  5331. Changed |= simplifyOnce(BB);
  5332. } while (Resimplify);
  5333. return Changed;
  5334. }
  5335. bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  5336. const SimplifyCFGOptions &Options,
  5337. SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
  5338. return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
  5339. Options)
  5340. .run(BB);
  5341. }