SimplifyCFG.cpp 231 KB

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