SimplifyCFG.cpp 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647
  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/Transforms/Utils/Local.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/ConstantFolding.h"
  21. #include "llvm/Analysis/InstructionSimplify.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/IR/CFG.h"
  25. #include "llvm/IR/ConstantRange.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/GlobalVariable.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/IR/Metadata.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/IR/NoFolder.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/IR/PatternMatch.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  45. #include "llvm/Transforms/Utils/Local.h"
  46. #include "llvm/Transforms/Utils/ValueMapper.h"
  47. #include <algorithm>
  48. #include <map>
  49. #include <set>
  50. using namespace llvm;
  51. using namespace PatternMatch;
  52. #define DEBUG_TYPE "simplifycfg"
  53. static cl::opt<unsigned>
  54. PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
  55. cl::desc("Control the amount of phi node folding to perform (default = 1)"));
  56. static cl::opt<bool>
  57. DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  58. cl::desc("Duplicate return instructions into unconditional branches"));
  59. static cl::opt<bool>
  60. SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
  61. cl::desc("Sink common instructions down to the end block"));
  62. static cl::opt<bool> HoistCondStores(
  63. "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
  64. cl::desc("Hoist conditional stores if an unconditional store precedes"));
  65. STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
  66. STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
  67. STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
  68. STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
  69. STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
  70. STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
  71. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  72. namespace {
  73. // The first field contains the value that the switch produces when a certain
  74. // case group is selected, and the second field is a vector containing the cases
  75. // composing the case group.
  76. typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
  77. SwitchCaseResultVectorTy;
  78. // The first field contains the phi node that generates a result of the switch
  79. // and the second field contains the value generated for a certain case in the switch
  80. // for that PHI.
  81. typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
  82. /// ValueEqualityComparisonCase - Represents a case of a switch.
  83. struct ValueEqualityComparisonCase {
  84. ConstantInt *Value;
  85. BasicBlock *Dest;
  86. ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
  87. : Value(Value), Dest(Dest) {}
  88. bool operator<(ValueEqualityComparisonCase RHS) const {
  89. // Comparing pointers is ok as we only rely on the order for uniquing.
  90. return Value < RHS.Value;
  91. }
  92. bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
  93. };
  94. class SimplifyCFGOpt {
  95. const TargetTransformInfo &TTI;
  96. unsigned BonusInstThreshold;
  97. const DataLayout *const DL;
  98. AssumptionTracker *AT;
  99. Value *isValueEqualityComparison(TerminatorInst *TI);
  100. BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
  101. std::vector<ValueEqualityComparisonCase> &Cases);
  102. bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  103. BasicBlock *Pred,
  104. IRBuilder<> &Builder);
  105. bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  106. IRBuilder<> &Builder);
  107. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  108. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  109. bool SimplifyUnreachable(UnreachableInst *UI);
  110. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  111. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  112. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
  113. bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
  114. public:
  115. SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
  116. const DataLayout *DL, AssumptionTracker *AT)
  117. : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
  118. bool run(BasicBlock *BB);
  119. };
  120. }
  121. /// SafeToMergeTerminators - Return true if it is safe to merge these two
  122. /// terminator instructions together.
  123. ///
  124. static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
  125. if (SI1 == SI2) return false; // Can't merge with self!
  126. // It is not safe to merge these two switch instructions if they have a common
  127. // successor, and if that successor has a PHI node, and if *that* PHI node has
  128. // conflicting incoming values from the two switch blocks.
  129. BasicBlock *SI1BB = SI1->getParent();
  130. BasicBlock *SI2BB = SI2->getParent();
  131. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  132. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  133. if (SI1Succs.count(*I))
  134. for (BasicBlock::iterator BBI = (*I)->begin();
  135. isa<PHINode>(BBI); ++BBI) {
  136. PHINode *PN = cast<PHINode>(BBI);
  137. if (PN->getIncomingValueForBlock(SI1BB) !=
  138. PN->getIncomingValueForBlock(SI2BB))
  139. return false;
  140. }
  141. return true;
  142. }
  143. /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
  144. /// to merge these two terminator instructions together, where SI1 is an
  145. /// unconditional branch. PhiNodes will store all PHI nodes in common
  146. /// successors.
  147. ///
  148. static bool isProfitableToFoldUnconditional(BranchInst *SI1,
  149. BranchInst *SI2,
  150. Instruction *Cond,
  151. SmallVectorImpl<PHINode*> &PhiNodes) {
  152. if (SI1 == SI2) return false; // Can't merge with self!
  153. assert(SI1->isUnconditional() && SI2->isConditional());
  154. // We fold the unconditional branch if we can easily update all PHI nodes in
  155. // common successors:
  156. // 1> We have a constant incoming value for the conditional branch;
  157. // 2> We have "Cond" as the incoming value for the unconditional branch;
  158. // 3> SI2->getCondition() and Cond have same operands.
  159. CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
  160. if (!Ci2) return false;
  161. if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
  162. Cond->getOperand(1) == Ci2->getOperand(1)) &&
  163. !(Cond->getOperand(0) == Ci2->getOperand(1) &&
  164. Cond->getOperand(1) == Ci2->getOperand(0)))
  165. return false;
  166. BasicBlock *SI1BB = SI1->getParent();
  167. BasicBlock *SI2BB = SI2->getParent();
  168. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  169. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  170. if (SI1Succs.count(*I))
  171. for (BasicBlock::iterator BBI = (*I)->begin();
  172. isa<PHINode>(BBI); ++BBI) {
  173. PHINode *PN = cast<PHINode>(BBI);
  174. if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
  175. !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
  176. return false;
  177. PhiNodes.push_back(PN);
  178. }
  179. return true;
  180. }
  181. /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
  182. /// now be entries in it from the 'NewPred' block. The values that will be
  183. /// flowing into the PHI nodes will be the same as those coming in from
  184. /// ExistPred, an existing predecessor of Succ.
  185. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  186. BasicBlock *ExistPred) {
  187. if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
  188. PHINode *PN;
  189. for (BasicBlock::iterator I = Succ->begin();
  190. (PN = dyn_cast<PHINode>(I)); ++I)
  191. PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
  192. }
  193. /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
  194. /// given instruction, which is assumed to be safe to speculate. 1 means
  195. /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
  196. static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
  197. assert(isSafeToSpeculativelyExecute(I, DL) &&
  198. "Instruction is not safe to speculatively execute!");
  199. switch (Operator::getOpcode(I)) {
  200. default:
  201. // In doubt, be conservative.
  202. return UINT_MAX;
  203. case Instruction::GetElementPtr:
  204. // GEPs are cheap if all indices are constant.
  205. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  206. return UINT_MAX;
  207. return 1;
  208. case Instruction::ExtractValue:
  209. case Instruction::Load:
  210. case Instruction::Add:
  211. case Instruction::Sub:
  212. case Instruction::And:
  213. case Instruction::Or:
  214. case Instruction::Xor:
  215. case Instruction::Shl:
  216. case Instruction::LShr:
  217. case Instruction::AShr:
  218. case Instruction::ICmp:
  219. case Instruction::Trunc:
  220. case Instruction::ZExt:
  221. case Instruction::SExt:
  222. case Instruction::BitCast:
  223. case Instruction::ExtractElement:
  224. case Instruction::InsertElement:
  225. return 1; // These are all cheap.
  226. case Instruction::Call:
  227. case Instruction::Select:
  228. return 2;
  229. }
  230. }
  231. /// DominatesMergePoint - If we have a merge point of an "if condition" as
  232. /// accepted above, return true if the specified value dominates the block. We
  233. /// don't handle the true generality of domination here, just a special case
  234. /// which works well enough for us.
  235. ///
  236. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  237. /// see if V (which must be an instruction) and its recursive operands
  238. /// that do not dominate BB have a combined cost lower than CostRemaining and
  239. /// are non-trapping. If both are true, the instruction is inserted into the
  240. /// set and true is returned.
  241. ///
  242. /// The cost for most non-trapping instructions is defined as 1 except for
  243. /// Select whose cost is 2.
  244. ///
  245. /// After this function returns, CostRemaining is decreased by the cost of
  246. /// V plus its non-dominating operands. If that cost is greater than
  247. /// CostRemaining, false is returned and CostRemaining is undefined.
  248. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  249. SmallPtrSetImpl<Instruction*> *AggressiveInsts,
  250. unsigned &CostRemaining,
  251. const DataLayout *DL) {
  252. Instruction *I = dyn_cast<Instruction>(V);
  253. if (!I) {
  254. // Non-instructions all dominate instructions, but not all constantexprs
  255. // can be executed unconditionally.
  256. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  257. if (C->canTrap())
  258. return false;
  259. return true;
  260. }
  261. BasicBlock *PBB = I->getParent();
  262. // We don't want to allow weird loops that might have the "if condition" in
  263. // the bottom of this block.
  264. if (PBB == BB) return false;
  265. // If this instruction is defined in a block that contains an unconditional
  266. // branch to BB, then it must be in the 'conditional' part of the "if
  267. // statement". If not, it definitely dominates the region.
  268. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  269. if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
  270. return true;
  271. // If we aren't allowing aggressive promotion anymore, then don't consider
  272. // instructions in the 'if region'.
  273. if (!AggressiveInsts) return false;
  274. // If we have seen this instruction before, don't count it again.
  275. if (AggressiveInsts->count(I)) return true;
  276. // Okay, it looks like the instruction IS in the "condition". Check to
  277. // see if it's a cheap instruction to unconditionally compute, and if it
  278. // only uses stuff defined outside of the condition. If so, hoist it out.
  279. if (!isSafeToSpeculativelyExecute(I, DL))
  280. return false;
  281. unsigned Cost = ComputeSpeculationCost(I, DL);
  282. if (Cost > CostRemaining)
  283. return false;
  284. CostRemaining -= Cost;
  285. // Okay, we can only really hoist these out if their operands do
  286. // not take us over the cost threshold.
  287. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  288. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
  289. return false;
  290. // Okay, it's safe to do this! Remember this instruction.
  291. AggressiveInsts->insert(I);
  292. return true;
  293. }
  294. /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
  295. /// and PointerNullValue. Return NULL if value is not a constant int.
  296. static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
  297. // Normal constant int.
  298. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  299. if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
  300. return CI;
  301. // This is some kind of pointer constant. Turn it into a pointer-sized
  302. // ConstantInt if possible.
  303. IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
  304. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  305. if (isa<ConstantPointerNull>(V))
  306. return ConstantInt::get(PtrTy, 0);
  307. // IntToPtr const int.
  308. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  309. if (CE->getOpcode() == Instruction::IntToPtr)
  310. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  311. // The constant is very likely to have the right type already.
  312. if (CI->getType() == PtrTy)
  313. return CI;
  314. else
  315. return cast<ConstantInt>
  316. (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  317. }
  318. return nullptr;
  319. }
  320. namespace {
  321. /// Given a chain of or (||) or and (&&) comparison of a value against a
  322. /// constant, this will try to recover the information required for a switch
  323. /// structure.
  324. /// It will depth-first traverse the chain of comparison, seeking for patterns
  325. /// like %a == 12 or %a < 4 and combine them to produce a set of integer
  326. /// representing the different cases for the switch.
  327. /// Note that if the chain is composed of '||' it will build the set of elements
  328. /// that matches the comparisons (i.e. any of this value validate the chain)
  329. /// while for a chain of '&&' it will build the set elements that make the test
  330. /// fail.
  331. struct ConstantComparesGatherer {
  332. Value *CompValue; /// Value found for the switch comparison
  333. Value *Extra; /// Extra clause to be checked before the switch
  334. SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
  335. unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
  336. /// Construct and compute the result for the comparison instruction Cond
  337. ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
  338. : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
  339. gather(Cond, DL);
  340. }
  341. /// Prevent copy
  342. ConstantComparesGatherer(const ConstantComparesGatherer &)
  343. LLVM_DELETED_FUNCTION;
  344. ConstantComparesGatherer &
  345. operator=(const ConstantComparesGatherer &) LLVM_DELETED_FUNCTION;
  346. private:
  347. /// Try to set the current value used for the comparison, it succeeds only if
  348. /// it wasn't set before or if the new value is the same as the old one
  349. bool setValueOnce(Value *NewVal) {
  350. if(CompValue && CompValue != NewVal) return false;
  351. CompValue = NewVal;
  352. return (CompValue != nullptr);
  353. }
  354. /// Try to match Instruction "I" as a comparison against a constant and
  355. /// populates the array Vals with the set of values that match (or do not
  356. /// match depending on isEQ).
  357. /// Return false on failure. On success, the Value the comparison matched
  358. /// against is placed in CompValue.
  359. /// If CompValue is already set, the function is expected to fail if a match
  360. /// is found but the value compared to is different.
  361. bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
  362. // If this is an icmp against a constant, handle this as one of the cases.
  363. ICmpInst *ICI;
  364. ConstantInt *C;
  365. if (!((ICI = dyn_cast<ICmpInst>(I)) &&
  366. (C = GetConstantInt(I->getOperand(1), DL)))) {
  367. return false;
  368. }
  369. Value *RHSVal;
  370. ConstantInt *RHSC;
  371. // Pattern match a special case
  372. // (x & ~2^x) == y --> x == y || x == y|2^x
  373. // This undoes a transformation done by instcombine to fuse 2 compares.
  374. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
  375. if (match(ICI->getOperand(0),
  376. m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
  377. APInt Not = ~RHSC->getValue();
  378. if (Not.isPowerOf2()) {
  379. // If we already have a value for the switch, it has to match!
  380. if(!setValueOnce(RHSVal))
  381. return false;
  382. Vals.push_back(C);
  383. Vals.push_back(ConstantInt::get(C->getContext(),
  384. C->getValue() | Not));
  385. UsedICmps++;
  386. return true;
  387. }
  388. }
  389. // If we already have a value for the switch, it has to match!
  390. if(!setValueOnce(ICI->getOperand(0)))
  391. return false;
  392. UsedICmps++;
  393. Vals.push_back(C);
  394. return ICI->getOperand(0);
  395. }
  396. // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
  397. ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
  398. C->getValue());
  399. // Shift the range if the compare is fed by an add. This is the range
  400. // compare idiom as emitted by instcombine.
  401. Value *CandidateVal = I->getOperand(0);
  402. if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
  403. Span = Span.subtract(RHSC->getValue());
  404. CandidateVal = RHSVal;
  405. }
  406. // If this is an and/!= check, then we are looking to build the set of
  407. // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
  408. // x != 0 && x != 1.
  409. if (!isEQ)
  410. Span = Span.inverse();
  411. // If there are a ton of values, we don't want to make a ginormous switch.
  412. if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
  413. return false;
  414. }
  415. // If we already have a value for the switch, it has to match!
  416. if(!setValueOnce(CandidateVal))
  417. return false;
  418. // Add all values from the range to the set
  419. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  420. Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
  421. UsedICmps++;
  422. return true;
  423. }
  424. /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
  425. /// eq/ne/lt/gt instructions that compare a value against a constant, extract
  426. /// the value being compared, and stick the list constants into the Vals
  427. /// vector.
  428. /// One "Extra" case is allowed to differ from the other.
  429. void gather(Value *V, const DataLayout *DL) {
  430. Instruction *I = dyn_cast<Instruction>(V);
  431. bool isEQ = (I->getOpcode() == Instruction::Or);
  432. // Keep a stack (SmallVector for efficiency) for depth-first traversal
  433. SmallVector<Value *, 8> DFT;
  434. // Initialize
  435. DFT.push_back(V);
  436. while(!DFT.empty()) {
  437. V = DFT.pop_back_val();
  438. if (Instruction *I = dyn_cast<Instruction>(V)) {
  439. // If it is a || (or && depending on isEQ), process the operands.
  440. if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
  441. DFT.push_back(I->getOperand(1));
  442. DFT.push_back(I->getOperand(0));
  443. continue;
  444. }
  445. // Try to match the current instruction
  446. if (matchInstruction(I, DL, isEQ))
  447. // Match succeed, continue the loop
  448. continue;
  449. }
  450. // One element of the sequence of || (or &&) could not be match as a
  451. // comparison against the same value as the others.
  452. // We allow only one "Extra" case to be checked before the switch
  453. if (!Extra) {
  454. Extra = V;
  455. continue;
  456. }
  457. // Failed to parse a proper sequence, abort now
  458. CompValue = nullptr;
  459. break;
  460. }
  461. }
  462. };
  463. }
  464. static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
  465. Instruction *Cond = nullptr;
  466. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  467. Cond = dyn_cast<Instruction>(SI->getCondition());
  468. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  469. if (BI->isConditional())
  470. Cond = dyn_cast<Instruction>(BI->getCondition());
  471. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  472. Cond = dyn_cast<Instruction>(IBI->getAddress());
  473. }
  474. TI->eraseFromParent();
  475. if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
  476. }
  477. /// isValueEqualityComparison - Return true if the specified terminator checks
  478. /// to see if a value is equal to constant integer value.
  479. Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
  480. Value *CV = nullptr;
  481. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  482. // Do not permit merging of large switch instructions into their
  483. // predecessors unless there is only one predecessor.
  484. if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
  485. pred_end(SI->getParent())) <= 128)
  486. CV = SI->getCondition();
  487. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  488. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  489. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
  490. if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
  491. CV = ICI->getOperand(0);
  492. // Unwrap any lossless ptrtoint cast.
  493. if (DL && CV) {
  494. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
  495. Value *Ptr = PTII->getPointerOperand();
  496. if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
  497. CV = Ptr;
  498. }
  499. }
  500. return CV;
  501. }
  502. /// GetValueEqualityComparisonCases - Given a value comparison instruction,
  503. /// decode all of the 'cases' that it represents and return the 'default' block.
  504. BasicBlock *SimplifyCFGOpt::
  505. GetValueEqualityComparisonCases(TerminatorInst *TI,
  506. std::vector<ValueEqualityComparisonCase>
  507. &Cases) {
  508. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  509. Cases.reserve(SI->getNumCases());
  510. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
  511. Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
  512. i.getCaseSuccessor()));
  513. return SI->getDefaultDest();
  514. }
  515. BranchInst *BI = cast<BranchInst>(TI);
  516. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  517. BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
  518. Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
  519. DL),
  520. Succ));
  521. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  522. }
  523. /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
  524. /// in the list that match the specified block.
  525. static void EliminateBlockCases(BasicBlock *BB,
  526. std::vector<ValueEqualityComparisonCase> &Cases) {
  527. Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
  528. }
  529. /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
  530. /// well.
  531. static bool
  532. ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
  533. std::vector<ValueEqualityComparisonCase > &C2) {
  534. std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
  535. // Make V1 be smaller than V2.
  536. if (V1->size() > V2->size())
  537. std::swap(V1, V2);
  538. if (V1->size() == 0) return false;
  539. if (V1->size() == 1) {
  540. // Just scan V2.
  541. ConstantInt *TheVal = (*V1)[0].Value;
  542. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  543. if (TheVal == (*V2)[i].Value)
  544. return true;
  545. }
  546. // Otherwise, just sort both lists and compare element by element.
  547. array_pod_sort(V1->begin(), V1->end());
  548. array_pod_sort(V2->begin(), V2->end());
  549. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  550. while (i1 != e1 && i2 != e2) {
  551. if ((*V1)[i1].Value == (*V2)[i2].Value)
  552. return true;
  553. if ((*V1)[i1].Value < (*V2)[i2].Value)
  554. ++i1;
  555. else
  556. ++i2;
  557. }
  558. return false;
  559. }
  560. /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
  561. /// terminator instruction and its block is known to only have a single
  562. /// predecessor block, check to see if that predecessor is also a value
  563. /// comparison with the same value, and if that comparison determines the
  564. /// outcome of this comparison. If so, simplify TI. This does a very limited
  565. /// form of jump threading.
  566. bool SimplifyCFGOpt::
  567. SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  568. BasicBlock *Pred,
  569. IRBuilder<> &Builder) {
  570. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  571. if (!PredVal) return false; // Not a value comparison in predecessor.
  572. Value *ThisVal = isValueEqualityComparison(TI);
  573. assert(ThisVal && "This isn't a value comparison!!");
  574. if (ThisVal != PredVal) return false; // Different predicates.
  575. // TODO: Preserve branch weight metadata, similarly to how
  576. // FoldValueComparisonIntoPredecessors preserves it.
  577. // Find out information about when control will move from Pred to TI's block.
  578. std::vector<ValueEqualityComparisonCase> PredCases;
  579. BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
  580. PredCases);
  581. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  582. // Find information about how control leaves this block.
  583. std::vector<ValueEqualityComparisonCase> ThisCases;
  584. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  585. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  586. // If TI's block is the default block from Pred's comparison, potentially
  587. // simplify TI based on this knowledge.
  588. if (PredDef == TI->getParent()) {
  589. // If we are here, we know that the value is none of those cases listed in
  590. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  591. // can simplify TI.
  592. if (!ValuesOverlap(PredCases, ThisCases))
  593. return false;
  594. if (isa<BranchInst>(TI)) {
  595. // Okay, one of the successors of this condbr is dead. Convert it to a
  596. // uncond br.
  597. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  598. // Insert the new branch.
  599. Instruction *NI = Builder.CreateBr(ThisDef);
  600. (void) NI;
  601. // Remove PHI node entries for the dead edge.
  602. ThisCases[0].Dest->removePredecessor(TI->getParent());
  603. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  604. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  605. EraseTerminatorInstAndDCECond(TI);
  606. return true;
  607. }
  608. SwitchInst *SI = cast<SwitchInst>(TI);
  609. // Okay, TI has cases that are statically dead, prune them away.
  610. SmallPtrSet<Constant*, 16> DeadCases;
  611. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  612. DeadCases.insert(PredCases[i].Value);
  613. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  614. << "Through successor TI: " << *TI);
  615. // Collect branch weights into a vector.
  616. SmallVector<uint32_t, 8> Weights;
  617. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  618. bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
  619. if (HasWeight)
  620. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  621. ++MD_i) {
  622. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  623. Weights.push_back(CI->getValue().getZExtValue());
  624. }
  625. for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
  626. --i;
  627. if (DeadCases.count(i.getCaseValue())) {
  628. if (HasWeight) {
  629. std::swap(Weights[i.getCaseIndex()+1], Weights.back());
  630. Weights.pop_back();
  631. }
  632. i.getCaseSuccessor()->removePredecessor(TI->getParent());
  633. SI->removeCase(i);
  634. }
  635. }
  636. if (HasWeight && Weights.size() >= 2)
  637. SI->setMetadata(LLVMContext::MD_prof,
  638. MDBuilder(SI->getParent()->getContext()).
  639. createBranchWeights(Weights));
  640. DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  641. return true;
  642. }
  643. // Otherwise, TI's block must correspond to some matched value. Find out
  644. // which value (or set of values) this is.
  645. ConstantInt *TIV = nullptr;
  646. BasicBlock *TIBB = TI->getParent();
  647. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  648. if (PredCases[i].Dest == TIBB) {
  649. if (TIV)
  650. return false; // Cannot handle multiple values coming to this block.
  651. TIV = PredCases[i].Value;
  652. }
  653. assert(TIV && "No edge from pred to succ?");
  654. // Okay, we found the one constant that our value can be if we get into TI's
  655. // BB. Find out which successor will unconditionally be branched to.
  656. BasicBlock *TheRealDest = nullptr;
  657. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  658. if (ThisCases[i].Value == TIV) {
  659. TheRealDest = ThisCases[i].Dest;
  660. break;
  661. }
  662. // If not handled by any explicit cases, it is handled by the default case.
  663. if (!TheRealDest) TheRealDest = ThisDef;
  664. // Remove PHI node entries for dead edges.
  665. BasicBlock *CheckEdge = TheRealDest;
  666. for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
  667. if (*SI != CheckEdge)
  668. (*SI)->removePredecessor(TIBB);
  669. else
  670. CheckEdge = nullptr;
  671. // Insert the new branch.
  672. Instruction *NI = Builder.CreateBr(TheRealDest);
  673. (void) NI;
  674. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  675. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  676. EraseTerminatorInstAndDCECond(TI);
  677. return true;
  678. }
  679. namespace {
  680. /// ConstantIntOrdering - This class implements a stable ordering of constant
  681. /// integers that does not depend on their address. This is important for
  682. /// applications that sort ConstantInt's to ensure uniqueness.
  683. struct ConstantIntOrdering {
  684. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  685. return LHS->getValue().ult(RHS->getValue());
  686. }
  687. };
  688. }
  689. static int ConstantIntSortPredicate(ConstantInt *const *P1,
  690. ConstantInt *const *P2) {
  691. const ConstantInt *LHS = *P1;
  692. const ConstantInt *RHS = *P2;
  693. if (LHS->getValue().ult(RHS->getValue()))
  694. return 1;
  695. if (LHS->getValue() == RHS->getValue())
  696. return 0;
  697. return -1;
  698. }
  699. static inline bool HasBranchWeights(const Instruction* I) {
  700. MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
  701. if (ProfMD && ProfMD->getOperand(0))
  702. if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
  703. return MDS->getString().equals("branch_weights");
  704. return false;
  705. }
  706. /// Get Weights of a given TerminatorInst, the default weight is at the front
  707. /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
  708. /// metadata.
  709. static void GetBranchWeights(TerminatorInst *TI,
  710. SmallVectorImpl<uint64_t> &Weights) {
  711. MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
  712. assert(MD);
  713. for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
  714. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
  715. Weights.push_back(CI->getValue().getZExtValue());
  716. }
  717. // If TI is a conditional eq, the default case is the false case,
  718. // and the corresponding branch-weight data is at index 2. We swap the
  719. // default weight to be the first entry.
  720. if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
  721. assert(Weights.size() == 2);
  722. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  723. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  724. std::swap(Weights.front(), Weights.back());
  725. }
  726. }
  727. /// Keep halving the weights until all can fit in uint32_t.
  728. static void FitWeights(MutableArrayRef<uint64_t> Weights) {
  729. uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
  730. if (Max > UINT_MAX) {
  731. unsigned Offset = 32 - countLeadingZeros(Max);
  732. for (uint64_t &I : Weights)
  733. I >>= Offset;
  734. }
  735. }
  736. /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
  737. /// equality comparison instruction (either a switch or a branch on "X == c").
  738. /// See if any of the predecessors of the terminator block are value comparisons
  739. /// on the same value. If so, and if safe to do so, fold them together.
  740. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  741. IRBuilder<> &Builder) {
  742. BasicBlock *BB = TI->getParent();
  743. Value *CV = isValueEqualityComparison(TI); // CondVal
  744. assert(CV && "Not a comparison?");
  745. bool Changed = false;
  746. SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
  747. while (!Preds.empty()) {
  748. BasicBlock *Pred = Preds.pop_back_val();
  749. // See if the predecessor is a comparison with the same value.
  750. TerminatorInst *PTI = Pred->getTerminator();
  751. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  752. if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
  753. // Figure out which 'cases' to copy from SI to PSI.
  754. std::vector<ValueEqualityComparisonCase> BBCases;
  755. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  756. std::vector<ValueEqualityComparisonCase> PredCases;
  757. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  758. // Based on whether the default edge from PTI goes to BB or not, fill in
  759. // PredCases and PredDefault with the new switch cases we would like to
  760. // build.
  761. SmallVector<BasicBlock*, 8> NewSuccessors;
  762. // Update the branch weight metadata along the way
  763. SmallVector<uint64_t, 8> Weights;
  764. bool PredHasWeights = HasBranchWeights(PTI);
  765. bool SuccHasWeights = HasBranchWeights(TI);
  766. if (PredHasWeights) {
  767. GetBranchWeights(PTI, Weights);
  768. // branch-weight metadata is inconsistent here.
  769. if (Weights.size() != 1 + PredCases.size())
  770. PredHasWeights = SuccHasWeights = false;
  771. } else if (SuccHasWeights)
  772. // If there are no predecessor weights but there are successor weights,
  773. // populate Weights with 1, which will later be scaled to the sum of
  774. // successor's weights
  775. Weights.assign(1 + PredCases.size(), 1);
  776. SmallVector<uint64_t, 8> SuccWeights;
  777. if (SuccHasWeights) {
  778. GetBranchWeights(TI, SuccWeights);
  779. // branch-weight metadata is inconsistent here.
  780. if (SuccWeights.size() != 1 + BBCases.size())
  781. PredHasWeights = SuccHasWeights = false;
  782. } else if (PredHasWeights)
  783. SuccWeights.assign(1 + BBCases.size(), 1);
  784. if (PredDefault == BB) {
  785. // If this is the default destination from PTI, only the edges in TI
  786. // that don't occur in PTI, or that branch to BB will be activated.
  787. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  788. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  789. if (PredCases[i].Dest != BB)
  790. PTIHandled.insert(PredCases[i].Value);
  791. else {
  792. // The default destination is BB, we don't need explicit targets.
  793. std::swap(PredCases[i], PredCases.back());
  794. if (PredHasWeights || SuccHasWeights) {
  795. // Increase weight for the default case.
  796. Weights[0] += Weights[i+1];
  797. std::swap(Weights[i+1], Weights.back());
  798. Weights.pop_back();
  799. }
  800. PredCases.pop_back();
  801. --i; --e;
  802. }
  803. // Reconstruct the new switch statement we will be building.
  804. if (PredDefault != BBDefault) {
  805. PredDefault->removePredecessor(Pred);
  806. PredDefault = BBDefault;
  807. NewSuccessors.push_back(BBDefault);
  808. }
  809. unsigned CasesFromPred = Weights.size();
  810. uint64_t ValidTotalSuccWeight = 0;
  811. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  812. if (!PTIHandled.count(BBCases[i].Value) &&
  813. BBCases[i].Dest != BBDefault) {
  814. PredCases.push_back(BBCases[i]);
  815. NewSuccessors.push_back(BBCases[i].Dest);
  816. if (SuccHasWeights || PredHasWeights) {
  817. // The default weight is at index 0, so weight for the ith case
  818. // should be at index i+1. Scale the cases from successor by
  819. // PredDefaultWeight (Weights[0]).
  820. Weights.push_back(Weights[0] * SuccWeights[i+1]);
  821. ValidTotalSuccWeight += SuccWeights[i+1];
  822. }
  823. }
  824. if (SuccHasWeights || PredHasWeights) {
  825. ValidTotalSuccWeight += SuccWeights[0];
  826. // Scale the cases from predecessor by ValidTotalSuccWeight.
  827. for (unsigned i = 1; i < CasesFromPred; ++i)
  828. Weights[i] *= ValidTotalSuccWeight;
  829. // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
  830. Weights[0] *= SuccWeights[0];
  831. }
  832. } else {
  833. // If this is not the default destination from PSI, only the edges
  834. // in SI that occur in PSI with a destination of BB will be
  835. // activated.
  836. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  837. std::map<ConstantInt*, uint64_t> WeightsForHandled;
  838. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  839. if (PredCases[i].Dest == BB) {
  840. PTIHandled.insert(PredCases[i].Value);
  841. if (PredHasWeights || SuccHasWeights) {
  842. WeightsForHandled[PredCases[i].Value] = Weights[i+1];
  843. std::swap(Weights[i+1], Weights.back());
  844. Weights.pop_back();
  845. }
  846. std::swap(PredCases[i], PredCases.back());
  847. PredCases.pop_back();
  848. --i; --e;
  849. }
  850. // Okay, now we know which constants were sent to BB from the
  851. // predecessor. Figure out where they will all go now.
  852. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  853. if (PTIHandled.count(BBCases[i].Value)) {
  854. // If this is one we are capable of getting...
  855. if (PredHasWeights || SuccHasWeights)
  856. Weights.push_back(WeightsForHandled[BBCases[i].Value]);
  857. PredCases.push_back(BBCases[i]);
  858. NewSuccessors.push_back(BBCases[i].Dest);
  859. PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
  860. }
  861. // If there are any constants vectored to BB that TI doesn't handle,
  862. // they must go to the default destination of TI.
  863. for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
  864. PTIHandled.begin(),
  865. E = PTIHandled.end(); I != E; ++I) {
  866. if (PredHasWeights || SuccHasWeights)
  867. Weights.push_back(WeightsForHandled[*I]);
  868. PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
  869. NewSuccessors.push_back(BBDefault);
  870. }
  871. }
  872. // Okay, at this point, we know which new successor Pred will get. Make
  873. // sure we update the number of entries in the PHI nodes for these
  874. // successors.
  875. for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
  876. AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
  877. Builder.SetInsertPoint(PTI);
  878. // Convert pointer to int before we switch.
  879. if (CV->getType()->isPointerTy()) {
  880. assert(DL && "Cannot switch on pointer without DataLayout");
  881. CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
  882. "magicptr");
  883. }
  884. // Now that the successors are updated, create the new Switch instruction.
  885. SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
  886. PredCases.size());
  887. NewSI->setDebugLoc(PTI->getDebugLoc());
  888. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  889. NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
  890. if (PredHasWeights || SuccHasWeights) {
  891. // Halve the weights if any of them cannot fit in an uint32_t
  892. FitWeights(Weights);
  893. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  894. NewSI->setMetadata(LLVMContext::MD_prof,
  895. MDBuilder(BB->getContext()).
  896. createBranchWeights(MDWeights));
  897. }
  898. EraseTerminatorInstAndDCECond(PTI);
  899. // Okay, last check. If BB is still a successor of PSI, then we must
  900. // have an infinite loop case. If so, add an infinitely looping block
  901. // to handle the case to preserve the behavior of the code.
  902. BasicBlock *InfLoopBlock = nullptr;
  903. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  904. if (NewSI->getSuccessor(i) == BB) {
  905. if (!InfLoopBlock) {
  906. // Insert it at the end of the function, because it's either code,
  907. // or it won't matter if it's hot. :)
  908. InfLoopBlock = BasicBlock::Create(BB->getContext(),
  909. "infloop", BB->getParent());
  910. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  911. }
  912. NewSI->setSuccessor(i, InfLoopBlock);
  913. }
  914. Changed = true;
  915. }
  916. }
  917. return Changed;
  918. }
  919. // isSafeToHoistInvoke - If we would need to insert a select that uses the
  920. // value of this invoke (comments in HoistThenElseCodeToIf explain why we
  921. // would need to do this), we can't hoist the invoke, as there is nowhere
  922. // to put the select in this case.
  923. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  924. Instruction *I1, Instruction *I2) {
  925. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  926. PHINode *PN;
  927. for (BasicBlock::iterator BBI = SI->begin();
  928. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  929. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  930. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  931. if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
  932. return false;
  933. }
  934. }
  935. }
  936. return true;
  937. }
  938. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
  939. /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
  940. /// BB2, hoist any common code in the two blocks up into the branch block. The
  941. /// caller of this function guarantees that BI's block dominates BB1 and BB2.
  942. static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
  943. // This does very trivial matching, with limited scanning, to find identical
  944. // instructions in the two blocks. In particular, we don't want to get into
  945. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  946. // such, we currently just scan for obviously identical instructions in an
  947. // identical order.
  948. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  949. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  950. BasicBlock::iterator BB1_Itr = BB1->begin();
  951. BasicBlock::iterator BB2_Itr = BB2->begin();
  952. Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
  953. // Skip debug info if it is not identical.
  954. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  955. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  956. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  957. while (isa<DbgInfoIntrinsic>(I1))
  958. I1 = BB1_Itr++;
  959. while (isa<DbgInfoIntrinsic>(I2))
  960. I2 = BB2_Itr++;
  961. }
  962. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  963. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
  964. return false;
  965. BasicBlock *BIParent = BI->getParent();
  966. bool Changed = false;
  967. do {
  968. // If we are hoisting the terminator instruction, don't move one (making a
  969. // broken BB), instead clone it, and remove BI.
  970. if (isa<TerminatorInst>(I1))
  971. goto HoistTerminator;
  972. // For a normal instruction, we just move one to right before the branch,
  973. // then replace all uses of the other with the first. Finally, we remove
  974. // the now redundant second instruction.
  975. BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
  976. if (!I2->use_empty())
  977. I2->replaceAllUsesWith(I1);
  978. I1->intersectOptionalDataWith(I2);
  979. unsigned KnownIDs[] = {
  980. LLVMContext::MD_tbaa,
  981. LLVMContext::MD_range,
  982. LLVMContext::MD_fpmath,
  983. LLVMContext::MD_invariant_load,
  984. LLVMContext::MD_nonnull
  985. };
  986. combineMetadata(I1, I2, KnownIDs);
  987. I2->eraseFromParent();
  988. Changed = true;
  989. I1 = BB1_Itr++;
  990. I2 = BB2_Itr++;
  991. // Skip debug info if it is not identical.
  992. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  993. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  994. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  995. while (isa<DbgInfoIntrinsic>(I1))
  996. I1 = BB1_Itr++;
  997. while (isa<DbgInfoIntrinsic>(I2))
  998. I2 = BB2_Itr++;
  999. }
  1000. } while (I1->isIdenticalToWhenDefined(I2));
  1001. return true;
  1002. HoistTerminator:
  1003. // It may not be possible to hoist an invoke.
  1004. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  1005. return Changed;
  1006. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  1007. PHINode *PN;
  1008. for (BasicBlock::iterator BBI = SI->begin();
  1009. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  1010. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1011. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1012. if (BB1V == BB2V)
  1013. continue;
  1014. // Check for passingValueIsAlwaysUndefined here because we would rather
  1015. // eliminate undefined control flow then converting it to a select.
  1016. if (passingValueIsAlwaysUndefined(BB1V, PN) ||
  1017. passingValueIsAlwaysUndefined(BB2V, PN))
  1018. return Changed;
  1019. if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
  1020. return Changed;
  1021. if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
  1022. return Changed;
  1023. }
  1024. }
  1025. // Okay, it is safe to hoist the terminator.
  1026. Instruction *NT = I1->clone();
  1027. BIParent->getInstList().insert(BI, NT);
  1028. if (!NT->getType()->isVoidTy()) {
  1029. I1->replaceAllUsesWith(NT);
  1030. I2->replaceAllUsesWith(NT);
  1031. NT->takeName(I1);
  1032. }
  1033. IRBuilder<true, NoFolder> Builder(NT);
  1034. // Hoisting one of the terminators from our successor is a great thing.
  1035. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  1036. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  1037. // nodes, so we insert select instruction to compute the final result.
  1038. std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
  1039. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  1040. PHINode *PN;
  1041. for (BasicBlock::iterator BBI = SI->begin();
  1042. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  1043. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1044. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1045. if (BB1V == BB2V) continue;
  1046. // These values do not agree. Insert a select instruction before NT
  1047. // that determines the right value.
  1048. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  1049. if (!SI)
  1050. SI = cast<SelectInst>
  1051. (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  1052. BB1V->getName()+"."+BB2V->getName()));
  1053. // Make the PHI node use the select for all incoming values for BB1/BB2
  1054. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  1055. if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
  1056. PN->setIncomingValue(i, SI);
  1057. }
  1058. }
  1059. // Update any PHI nodes in our new successors.
  1060. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
  1061. AddPredecessorToBlock(*SI, BIParent, BB1);
  1062. EraseTerminatorInstAndDCECond(BI);
  1063. return true;
  1064. }
  1065. /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
  1066. /// check whether BBEnd has only two predecessors and the other predecessor
  1067. /// ends with an unconditional branch. If it is true, sink any common code
  1068. /// in the two predecessors to BBEnd.
  1069. static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
  1070. assert(BI1->isUnconditional());
  1071. BasicBlock *BB1 = BI1->getParent();
  1072. BasicBlock *BBEnd = BI1->getSuccessor(0);
  1073. // Check that BBEnd has two predecessors and the other predecessor ends with
  1074. // an unconditional branch.
  1075. pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
  1076. BasicBlock *Pred0 = *PI++;
  1077. if (PI == PE) // Only one predecessor.
  1078. return false;
  1079. BasicBlock *Pred1 = *PI++;
  1080. if (PI != PE) // More than two predecessors.
  1081. return false;
  1082. BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
  1083. BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
  1084. if (!BI2 || !BI2->isUnconditional())
  1085. return false;
  1086. // Gather the PHI nodes in BBEnd.
  1087. std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
  1088. Instruction *FirstNonPhiInBBEnd = nullptr;
  1089. for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
  1090. I != E; ++I) {
  1091. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  1092. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1093. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1094. MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
  1095. } else {
  1096. FirstNonPhiInBBEnd = &*I;
  1097. break;
  1098. }
  1099. }
  1100. if (!FirstNonPhiInBBEnd)
  1101. return false;
  1102. // This does very trivial matching, with limited scanning, to find identical
  1103. // instructions in the two blocks. We scan backward for obviously identical
  1104. // instructions in an identical order.
  1105. BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
  1106. RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
  1107. RE2 = BB2->getInstList().rend();
  1108. // Skip debug info.
  1109. while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
  1110. if (RI1 == RE1)
  1111. return false;
  1112. while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
  1113. if (RI2 == RE2)
  1114. return false;
  1115. // Skip the unconditional branches.
  1116. ++RI1;
  1117. ++RI2;
  1118. bool Changed = false;
  1119. while (RI1 != RE1 && RI2 != RE2) {
  1120. // Skip debug info.
  1121. while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
  1122. if (RI1 == RE1)
  1123. return Changed;
  1124. while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
  1125. if (RI2 == RE2)
  1126. return Changed;
  1127. Instruction *I1 = &*RI1, *I2 = &*RI2;
  1128. // I1 and I2 should have a single use in the same PHI node, and they
  1129. // perform the same operation.
  1130. // Cannot move control-flow-involving, volatile loads, vaarg, etc.
  1131. if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
  1132. isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
  1133. isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
  1134. isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
  1135. I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
  1136. I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
  1137. !I1->hasOneUse() || !I2->hasOneUse() ||
  1138. MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
  1139. MapValueFromBB1ToBB2[I1].first != I2)
  1140. return Changed;
  1141. // Check whether we should swap the operands of ICmpInst.
  1142. ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
  1143. bool SwapOpnds = false;
  1144. if (ICmp1 && ICmp2 &&
  1145. ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
  1146. ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
  1147. (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
  1148. ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
  1149. ICmp2->swapOperands();
  1150. SwapOpnds = true;
  1151. }
  1152. if (!I1->isSameOperationAs(I2)) {
  1153. if (SwapOpnds)
  1154. ICmp2->swapOperands();
  1155. return Changed;
  1156. }
  1157. // The operands should be either the same or they need to be generated
  1158. // with a PHI node after sinking. We only handle the case where there is
  1159. // a single pair of different operands.
  1160. Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
  1161. unsigned Op1Idx = 0;
  1162. for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
  1163. if (I1->getOperand(I) == I2->getOperand(I))
  1164. continue;
  1165. // Early exit if we have more-than one pair of different operands or
  1166. // the different operand is already in MapValueFromBB1ToBB2.
  1167. // Early exit if we need a PHI node to replace a constant.
  1168. if (DifferentOp1 ||
  1169. MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
  1170. MapValueFromBB1ToBB2.end() ||
  1171. isa<Constant>(I1->getOperand(I)) ||
  1172. isa<Constant>(I2->getOperand(I))) {
  1173. // If we can't sink the instructions, undo the swapping.
  1174. if (SwapOpnds)
  1175. ICmp2->swapOperands();
  1176. return Changed;
  1177. }
  1178. DifferentOp1 = I1->getOperand(I);
  1179. Op1Idx = I;
  1180. DifferentOp2 = I2->getOperand(I);
  1181. }
  1182. // We insert the pair of different operands to MapValueFromBB1ToBB2 and
  1183. // remove (I1, I2) from MapValueFromBB1ToBB2.
  1184. if (DifferentOp1) {
  1185. PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
  1186. DifferentOp1->getName() + ".sink",
  1187. BBEnd->begin());
  1188. MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
  1189. // I1 should use NewPN instead of DifferentOp1.
  1190. I1->setOperand(Op1Idx, NewPN);
  1191. NewPN->addIncoming(DifferentOp1, BB1);
  1192. NewPN->addIncoming(DifferentOp2, BB2);
  1193. DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
  1194. }
  1195. PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
  1196. MapValueFromBB1ToBB2.erase(I1);
  1197. DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
  1198. DEBUG(dbgs() << " " << *I2 << "\n";);
  1199. // We need to update RE1 and RE2 if we are going to sink the first
  1200. // instruction in the basic block down.
  1201. bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
  1202. // Sink the instruction.
  1203. BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
  1204. if (!OldPN->use_empty())
  1205. OldPN->replaceAllUsesWith(I1);
  1206. OldPN->eraseFromParent();
  1207. if (!I2->use_empty())
  1208. I2->replaceAllUsesWith(I1);
  1209. I1->intersectOptionalDataWith(I2);
  1210. // TODO: Use combineMetadata here to preserve what metadata we can
  1211. // (analogous to the hoisting case above).
  1212. I2->eraseFromParent();
  1213. if (UpdateRE1)
  1214. RE1 = BB1->getInstList().rend();
  1215. if (UpdateRE2)
  1216. RE2 = BB2->getInstList().rend();
  1217. FirstNonPhiInBBEnd = I1;
  1218. NumSinkCommons++;
  1219. Changed = true;
  1220. }
  1221. return Changed;
  1222. }
  1223. /// \brief Determine if we can hoist sink a sole store instruction out of a
  1224. /// conditional block.
  1225. ///
  1226. /// We are looking for code like the following:
  1227. /// BrBB:
  1228. /// store i32 %add, i32* %arrayidx2
  1229. /// ... // No other stores or function calls (we could be calling a memory
  1230. /// ... // function).
  1231. /// %cmp = icmp ult %x, %y
  1232. /// br i1 %cmp, label %EndBB, label %ThenBB
  1233. /// ThenBB:
  1234. /// store i32 %add5, i32* %arrayidx2
  1235. /// br label EndBB
  1236. /// EndBB:
  1237. /// ...
  1238. /// We are going to transform this into:
  1239. /// BrBB:
  1240. /// store i32 %add, i32* %arrayidx2
  1241. /// ... //
  1242. /// %cmp = icmp ult %x, %y
  1243. /// %add.add5 = select i1 %cmp, i32 %add, %add5
  1244. /// store i32 %add.add5, i32* %arrayidx2
  1245. /// ...
  1246. ///
  1247. /// \return The pointer to the value of the previous store if the store can be
  1248. /// hoisted into the predecessor block. 0 otherwise.
  1249. static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
  1250. BasicBlock *StoreBB, BasicBlock *EndBB) {
  1251. StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
  1252. if (!StoreToHoist)
  1253. return nullptr;
  1254. // Volatile or atomic.
  1255. if (!StoreToHoist->isSimple())
  1256. return nullptr;
  1257. Value *StorePtr = StoreToHoist->getPointerOperand();
  1258. // Look for a store to the same pointer in BrBB.
  1259. unsigned MaxNumInstToLookAt = 10;
  1260. for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
  1261. RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
  1262. Instruction *CurI = &*RI;
  1263. // Could be calling an instruction that effects memory like free().
  1264. if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
  1265. return nullptr;
  1266. StoreInst *SI = dyn_cast<StoreInst>(CurI);
  1267. // Found the previous store make sure it stores to the same location.
  1268. if (SI && SI->getPointerOperand() == StorePtr)
  1269. // Found the previous store, return its value operand.
  1270. return SI->getValueOperand();
  1271. else if (SI)
  1272. return nullptr; // Unknown store.
  1273. }
  1274. return nullptr;
  1275. }
  1276. /// \brief Speculate a conditional basic block flattening the CFG.
  1277. ///
  1278. /// Note that this is a very risky transform currently. Speculating
  1279. /// instructions like this is most often not desirable. Instead, there is an MI
  1280. /// pass which can do it with full awareness of the resource constraints.
  1281. /// However, some cases are "obvious" and we should do directly. An example of
  1282. /// this is speculating a single, reasonably cheap instruction.
  1283. ///
  1284. /// There is only one distinct advantage to flattening the CFG at the IR level:
  1285. /// it makes very common but simplistic optimizations such as are common in
  1286. /// instcombine and the DAG combiner more powerful by removing CFG edges and
  1287. /// modeling their effects with easier to reason about SSA value graphs.
  1288. ///
  1289. ///
  1290. /// An illustration of this transform is turning this IR:
  1291. /// \code
  1292. /// BB:
  1293. /// %cmp = icmp ult %x, %y
  1294. /// br i1 %cmp, label %EndBB, label %ThenBB
  1295. /// ThenBB:
  1296. /// %sub = sub %x, %y
  1297. /// br label BB2
  1298. /// EndBB:
  1299. /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
  1300. /// ...
  1301. /// \endcode
  1302. ///
  1303. /// Into this IR:
  1304. /// \code
  1305. /// BB:
  1306. /// %cmp = icmp ult %x, %y
  1307. /// %sub = sub %x, %y
  1308. /// %cond = select i1 %cmp, 0, %sub
  1309. /// ...
  1310. /// \endcode
  1311. ///
  1312. /// \returns true if the conditional block is removed.
  1313. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
  1314. const DataLayout *DL) {
  1315. // Be conservative for now. FP select instruction can often be expensive.
  1316. Value *BrCond = BI->getCondition();
  1317. if (isa<FCmpInst>(BrCond))
  1318. return false;
  1319. BasicBlock *BB = BI->getParent();
  1320. BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
  1321. // If ThenBB is actually on the false edge of the conditional branch, remember
  1322. // to swap the select operands later.
  1323. bool Invert = false;
  1324. if (ThenBB != BI->getSuccessor(0)) {
  1325. assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
  1326. Invert = true;
  1327. }
  1328. assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
  1329. // Keep a count of how many times instructions are used within CondBB when
  1330. // they are candidates for sinking into CondBB. Specifically:
  1331. // - They are defined in BB, and
  1332. // - They have no side effects, and
  1333. // - All of their uses are in CondBB.
  1334. SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
  1335. unsigned SpeculationCost = 0;
  1336. Value *SpeculatedStoreValue = nullptr;
  1337. StoreInst *SpeculatedStore = nullptr;
  1338. for (BasicBlock::iterator BBI = ThenBB->begin(),
  1339. BBE = std::prev(ThenBB->end());
  1340. BBI != BBE; ++BBI) {
  1341. Instruction *I = BBI;
  1342. // Skip debug info.
  1343. if (isa<DbgInfoIntrinsic>(I))
  1344. continue;
  1345. // Only speculatively execution a single instruction (not counting the
  1346. // terminator) for now.
  1347. ++SpeculationCost;
  1348. if (SpeculationCost > 1)
  1349. return false;
  1350. // Don't hoist the instruction if it's unsafe or expensive.
  1351. if (!isSafeToSpeculativelyExecute(I, DL) &&
  1352. !(HoistCondStores &&
  1353. (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
  1354. EndBB))))
  1355. return false;
  1356. if (!SpeculatedStoreValue &&
  1357. ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
  1358. return false;
  1359. // Store the store speculation candidate.
  1360. if (SpeculatedStoreValue)
  1361. SpeculatedStore = cast<StoreInst>(I);
  1362. // Do not hoist the instruction if any of its operands are defined but not
  1363. // used in BB. The transformation will prevent the operand from
  1364. // being sunk into the use block.
  1365. for (User::op_iterator i = I->op_begin(), e = I->op_end();
  1366. i != e; ++i) {
  1367. Instruction *OpI = dyn_cast<Instruction>(*i);
  1368. if (!OpI || OpI->getParent() != BB ||
  1369. OpI->mayHaveSideEffects())
  1370. continue; // Not a candidate for sinking.
  1371. ++SinkCandidateUseCounts[OpI];
  1372. }
  1373. }
  1374. // Consider any sink candidates which are only used in CondBB as costs for
  1375. // speculation. Note, while we iterate over a DenseMap here, we are summing
  1376. // and so iteration order isn't significant.
  1377. for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
  1378. SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
  1379. I != E; ++I)
  1380. if (I->first->getNumUses() == I->second) {
  1381. ++SpeculationCost;
  1382. if (SpeculationCost > 1)
  1383. return false;
  1384. }
  1385. // Check that the PHI nodes can be converted to selects.
  1386. bool HaveRewritablePHIs = false;
  1387. for (BasicBlock::iterator I = EndBB->begin();
  1388. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1389. Value *OrigV = PN->getIncomingValueForBlock(BB);
  1390. Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
  1391. // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
  1392. // Skip PHIs which are trivial.
  1393. if (ThenV == OrigV)
  1394. continue;
  1395. // Don't convert to selects if we could remove undefined behavior instead.
  1396. if (passingValueIsAlwaysUndefined(OrigV, PN) ||
  1397. passingValueIsAlwaysUndefined(ThenV, PN))
  1398. return false;
  1399. HaveRewritablePHIs = true;
  1400. ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
  1401. ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
  1402. if (!OrigCE && !ThenCE)
  1403. continue; // Known safe and cheap.
  1404. if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
  1405. (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
  1406. return false;
  1407. unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
  1408. unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
  1409. if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
  1410. return false;
  1411. // Account for the cost of an unfolded ConstantExpr which could end up
  1412. // getting expanded into Instructions.
  1413. // FIXME: This doesn't account for how many operations are combined in the
  1414. // constant expression.
  1415. ++SpeculationCost;
  1416. if (SpeculationCost > 1)
  1417. return false;
  1418. }
  1419. // If there are no PHIs to process, bail early. This helps ensure idempotence
  1420. // as well.
  1421. if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
  1422. return false;
  1423. // If we get here, we can hoist the instruction and if-convert.
  1424. DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
  1425. // Insert a select of the value of the speculated store.
  1426. if (SpeculatedStoreValue) {
  1427. IRBuilder<true, NoFolder> Builder(BI);
  1428. Value *TrueV = SpeculatedStore->getValueOperand();
  1429. Value *FalseV = SpeculatedStoreValue;
  1430. if (Invert)
  1431. std::swap(TrueV, FalseV);
  1432. Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
  1433. "." + FalseV->getName());
  1434. SpeculatedStore->setOperand(0, S);
  1435. }
  1436. // Hoist the instructions.
  1437. BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
  1438. std::prev(ThenBB->end()));
  1439. // Insert selects and rewrite the PHI operands.
  1440. IRBuilder<true, NoFolder> Builder(BI);
  1441. for (BasicBlock::iterator I = EndBB->begin();
  1442. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1443. unsigned OrigI = PN->getBasicBlockIndex(BB);
  1444. unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
  1445. Value *OrigV = PN->getIncomingValue(OrigI);
  1446. Value *ThenV = PN->getIncomingValue(ThenI);
  1447. // Skip PHIs which are trivial.
  1448. if (OrigV == ThenV)
  1449. continue;
  1450. // Create a select whose true value is the speculatively executed value and
  1451. // false value is the preexisting value. Swap them if the branch
  1452. // destinations were inverted.
  1453. Value *TrueV = ThenV, *FalseV = OrigV;
  1454. if (Invert)
  1455. std::swap(TrueV, FalseV);
  1456. Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
  1457. TrueV->getName() + "." + FalseV->getName());
  1458. PN->setIncomingValue(OrigI, V);
  1459. PN->setIncomingValue(ThenI, V);
  1460. }
  1461. ++NumSpeculations;
  1462. return true;
  1463. }
  1464. /// \returns True if this block contains a CallInst with the NoDuplicate
  1465. /// attribute.
  1466. static bool HasNoDuplicateCall(const BasicBlock *BB) {
  1467. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  1468. const CallInst *CI = dyn_cast<CallInst>(I);
  1469. if (!CI)
  1470. continue;
  1471. if (CI->cannotDuplicate())
  1472. return true;
  1473. }
  1474. return false;
  1475. }
  1476. /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
  1477. /// across this block.
  1478. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  1479. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  1480. unsigned Size = 0;
  1481. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1482. if (isa<DbgInfoIntrinsic>(BBI))
  1483. continue;
  1484. if (Size > 10) return false; // Don't clone large BB's.
  1485. ++Size;
  1486. // We can only support instructions that do not define values that are
  1487. // live outside of the current basic block.
  1488. for (User *U : BBI->users()) {
  1489. Instruction *UI = cast<Instruction>(U);
  1490. if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
  1491. }
  1492. // Looks ok, continue checking.
  1493. }
  1494. return true;
  1495. }
  1496. /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
  1497. /// that is defined in the same block as the branch and if any PHI entries are
  1498. /// constants, thread edges corresponding to that entry to be branches to their
  1499. /// ultimate destination.
  1500. static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
  1501. BasicBlock *BB = BI->getParent();
  1502. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  1503. // NOTE: we currently cannot transform this case if the PHI node is used
  1504. // outside of the block.
  1505. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  1506. return false;
  1507. // Degenerate case of a single entry PHI.
  1508. if (PN->getNumIncomingValues() == 1) {
  1509. FoldSingleEntryPHINodes(PN->getParent());
  1510. return true;
  1511. }
  1512. // Now we know that this block has multiple preds and two succs.
  1513. if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
  1514. if (HasNoDuplicateCall(BB)) return false;
  1515. // Okay, this is a simple enough basic block. See if any phi values are
  1516. // constants.
  1517. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1518. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1519. if (!CB || !CB->getType()->isIntegerTy(1)) continue;
  1520. // Okay, we now know that all edges from PredBB should be revectored to
  1521. // branch to RealDest.
  1522. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1523. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1524. if (RealDest == BB) continue; // Skip self loops.
  1525. // Skip if the predecessor's terminator is an indirect branch.
  1526. if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
  1527. // The dest block might have PHI nodes, other predecessors and other
  1528. // difficult cases. Instead of being smart about this, just insert a new
  1529. // block that jumps to the destination block, effectively splitting
  1530. // the edge we are about to create.
  1531. BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
  1532. RealDest->getName()+".critedge",
  1533. RealDest->getParent(), RealDest);
  1534. BranchInst::Create(RealDest, EdgeBB);
  1535. // Update PHI nodes.
  1536. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1537. // BB may have instructions that are being threaded over. Clone these
  1538. // instructions into EdgeBB. We know that there will be no uses of the
  1539. // cloned instructions outside of EdgeBB.
  1540. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1541. DenseMap<Value*, Value*> TranslateMap; // Track translated values.
  1542. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1543. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1544. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1545. continue;
  1546. }
  1547. // Clone the instruction.
  1548. Instruction *N = BBI->clone();
  1549. if (BBI->hasName()) N->setName(BBI->getName()+".c");
  1550. // Update operands due to translation.
  1551. for (User::op_iterator i = N->op_begin(), e = N->op_end();
  1552. i != e; ++i) {
  1553. DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
  1554. if (PI != TranslateMap.end())
  1555. *i = PI->second;
  1556. }
  1557. // Check for trivial simplification.
  1558. if (Value *V = SimplifyInstruction(N, DL)) {
  1559. TranslateMap[BBI] = V;
  1560. delete N; // Instruction folded away, don't need actual inst
  1561. } else {
  1562. // Insert the new instruction into its new home.
  1563. EdgeBB->getInstList().insert(InsertPt, N);
  1564. if (!BBI->use_empty())
  1565. TranslateMap[BBI] = N;
  1566. }
  1567. }
  1568. // Loop over all of the edges from PredBB to BB, changing them to branch
  1569. // to EdgeBB instead.
  1570. TerminatorInst *PredBBTI = PredBB->getTerminator();
  1571. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1572. if (PredBBTI->getSuccessor(i) == BB) {
  1573. BB->removePredecessor(PredBB);
  1574. PredBBTI->setSuccessor(i, EdgeBB);
  1575. }
  1576. // Recurse, simplifying any other constants.
  1577. return FoldCondBranchOnPHI(BI, DL) | true;
  1578. }
  1579. return false;
  1580. }
  1581. /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
  1582. /// PHI node, see if we can eliminate it.
  1583. static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
  1584. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1585. // statement", which has a very simple dominance structure. Basically, we
  1586. // are trying to find the condition that is being branched on, which
  1587. // subsequently causes this merge to happen. We really want control
  1588. // dependence information for this check, but simplifycfg can't keep it up
  1589. // to date, and this catches most of the cases we care about anyway.
  1590. BasicBlock *BB = PN->getParent();
  1591. BasicBlock *IfTrue, *IfFalse;
  1592. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  1593. if (!IfCond ||
  1594. // Don't bother if the branch will be constant folded trivially.
  1595. isa<ConstantInt>(IfCond))
  1596. return false;
  1597. // Okay, we found that we can merge this two-entry phi node into a select.
  1598. // Doing so would require us to fold *all* two entry phi nodes in this block.
  1599. // At some point this becomes non-profitable (particularly if the target
  1600. // doesn't support cmov's). Only do this transformation if there are two or
  1601. // fewer PHI nodes in this block.
  1602. unsigned NumPhis = 0;
  1603. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  1604. if (NumPhis > 2)
  1605. return false;
  1606. // Loop over the PHI's seeing if we can promote them all to select
  1607. // instructions. While we are at it, keep track of the instructions
  1608. // that need to be moved to the dominating block.
  1609. SmallPtrSet<Instruction*, 4> AggressiveInsts;
  1610. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  1611. MaxCostVal1 = PHINodeFoldingThreshold;
  1612. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  1613. PHINode *PN = cast<PHINode>(II++);
  1614. if (Value *V = SimplifyInstruction(PN, DL)) {
  1615. PN->replaceAllUsesWith(V);
  1616. PN->eraseFromParent();
  1617. continue;
  1618. }
  1619. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
  1620. MaxCostVal0, DL) ||
  1621. !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
  1622. MaxCostVal1, DL))
  1623. return false;
  1624. }
  1625. // If we folded the first phi, PN dangles at this point. Refresh it. If
  1626. // we ran out of PHIs then we simplified them all.
  1627. PN = dyn_cast<PHINode>(BB->begin());
  1628. if (!PN) return true;
  1629. // Don't fold i1 branches on PHIs which contain binary operators. These can
  1630. // often be turned into switches and other things.
  1631. if (PN->getType()->isIntegerTy(1) &&
  1632. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  1633. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  1634. isa<BinaryOperator>(IfCond)))
  1635. return false;
  1636. // If we all PHI nodes are promotable, check to make sure that all
  1637. // instructions in the predecessor blocks can be promoted as well. If
  1638. // not, we won't be able to get rid of the control flow, so it's not
  1639. // worth promoting to select instructions.
  1640. BasicBlock *DomBlock = nullptr;
  1641. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  1642. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  1643. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  1644. IfBlock1 = nullptr;
  1645. } else {
  1646. DomBlock = *pred_begin(IfBlock1);
  1647. for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
  1648. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1649. // This is not an aggressive instruction that we can promote.
  1650. // Because of this, we won't be able to get rid of the control
  1651. // flow, so the xform is not worth it.
  1652. return false;
  1653. }
  1654. }
  1655. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  1656. IfBlock2 = nullptr;
  1657. } else {
  1658. DomBlock = *pred_begin(IfBlock2);
  1659. for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
  1660. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1661. // This is not an aggressive instruction that we can promote.
  1662. // Because of this, we won't be able to get rid of the control
  1663. // flow, so the xform is not worth it.
  1664. return false;
  1665. }
  1666. }
  1667. DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
  1668. << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
  1669. // If we can still promote the PHI nodes after this gauntlet of tests,
  1670. // do all of the PHI's now.
  1671. Instruction *InsertPt = DomBlock->getTerminator();
  1672. IRBuilder<true, NoFolder> Builder(InsertPt);
  1673. // Move all 'aggressive' instructions, which are defined in the
  1674. // conditional parts of the if's up to the dominating block.
  1675. if (IfBlock1)
  1676. DomBlock->getInstList().splice(InsertPt,
  1677. IfBlock1->getInstList(), IfBlock1->begin(),
  1678. IfBlock1->getTerminator());
  1679. if (IfBlock2)
  1680. DomBlock->getInstList().splice(InsertPt,
  1681. IfBlock2->getInstList(), IfBlock2->begin(),
  1682. IfBlock2->getTerminator());
  1683. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  1684. // Change the PHI node into a select instruction.
  1685. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  1686. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  1687. SelectInst *NV =
  1688. cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
  1689. PN->replaceAllUsesWith(NV);
  1690. NV->takeName(PN);
  1691. PN->eraseFromParent();
  1692. }
  1693. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  1694. // has been flattened. Change DomBlock to jump directly to our new block to
  1695. // avoid other simplifycfg's kicking in on the diamond.
  1696. TerminatorInst *OldTI = DomBlock->getTerminator();
  1697. Builder.SetInsertPoint(OldTI);
  1698. Builder.CreateBr(BB);
  1699. OldTI->eraseFromParent();
  1700. return true;
  1701. }
  1702. /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
  1703. /// to two returning blocks, try to merge them together into one return,
  1704. /// introducing a select if the return values disagree.
  1705. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  1706. IRBuilder<> &Builder) {
  1707. assert(BI->isConditional() && "Must be a conditional branch");
  1708. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1709. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1710. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  1711. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  1712. // Check to ensure both blocks are empty (just a return) or optionally empty
  1713. // with PHI nodes. If there are other instructions, merging would cause extra
  1714. // computation on one path or the other.
  1715. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  1716. return false;
  1717. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  1718. return false;
  1719. Builder.SetInsertPoint(BI);
  1720. // Okay, we found a branch that is going to two return nodes. If
  1721. // there is no return value for this function, just change the
  1722. // branch into a return.
  1723. if (FalseRet->getNumOperands() == 0) {
  1724. TrueSucc->removePredecessor(BI->getParent());
  1725. FalseSucc->removePredecessor(BI->getParent());
  1726. Builder.CreateRetVoid();
  1727. EraseTerminatorInstAndDCECond(BI);
  1728. return true;
  1729. }
  1730. // Otherwise, figure out what the true and false return values are
  1731. // so we can insert a new select instruction.
  1732. Value *TrueValue = TrueRet->getReturnValue();
  1733. Value *FalseValue = FalseRet->getReturnValue();
  1734. // Unwrap any PHI nodes in the return blocks.
  1735. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  1736. if (TVPN->getParent() == TrueSucc)
  1737. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  1738. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  1739. if (FVPN->getParent() == FalseSucc)
  1740. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  1741. // In order for this transformation to be safe, we must be able to
  1742. // unconditionally execute both operands to the return. This is
  1743. // normally the case, but we could have a potentially-trapping
  1744. // constant expression that prevents this transformation from being
  1745. // safe.
  1746. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  1747. if (TCV->canTrap())
  1748. return false;
  1749. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  1750. if (FCV->canTrap())
  1751. return false;
  1752. // Okay, we collected all the mapped values and checked them for sanity, and
  1753. // defined to really do this transformation. First, update the CFG.
  1754. TrueSucc->removePredecessor(BI->getParent());
  1755. FalseSucc->removePredecessor(BI->getParent());
  1756. // Insert select instructions where needed.
  1757. Value *BrCond = BI->getCondition();
  1758. if (TrueValue) {
  1759. // Insert a select if the results differ.
  1760. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  1761. } else if (isa<UndefValue>(TrueValue)) {
  1762. TrueValue = FalseValue;
  1763. } else {
  1764. TrueValue = Builder.CreateSelect(BrCond, TrueValue,
  1765. FalseValue, "retval");
  1766. }
  1767. }
  1768. Value *RI = !TrueValue ?
  1769. Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  1770. (void) RI;
  1771. DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  1772. << "\n " << *BI << "NewRet = " << *RI
  1773. << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
  1774. EraseTerminatorInstAndDCECond(BI);
  1775. return true;
  1776. }
  1777. /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
  1778. /// probabilities of the branch taking each edge. Fills in the two APInt
  1779. /// parameters and return true, or returns false if no or invalid metadata was
  1780. /// found.
  1781. static bool ExtractBranchMetadata(BranchInst *BI,
  1782. uint64_t &ProbTrue, uint64_t &ProbFalse) {
  1783. assert(BI->isConditional() &&
  1784. "Looking for probabilities on unconditional branch?");
  1785. MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  1786. if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
  1787. ConstantInt *CITrue =
  1788. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  1789. ConstantInt *CIFalse =
  1790. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  1791. if (!CITrue || !CIFalse) return false;
  1792. ProbTrue = CITrue->getValue().getZExtValue();
  1793. ProbFalse = CIFalse->getValue().getZExtValue();
  1794. return true;
  1795. }
  1796. /// checkCSEInPredecessor - Return true if the given instruction is available
  1797. /// in its predecessor block. If yes, the instruction will be removed.
  1798. ///
  1799. static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
  1800. if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
  1801. return false;
  1802. for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
  1803. Instruction *PBI = &*I;
  1804. // Check whether Inst and PBI generate the same value.
  1805. if (Inst->isIdenticalTo(PBI)) {
  1806. Inst->replaceAllUsesWith(PBI);
  1807. Inst->eraseFromParent();
  1808. return true;
  1809. }
  1810. }
  1811. return false;
  1812. }
  1813. /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
  1814. /// predecessor branches to us and one of our successors, fold the block into
  1815. /// the predecessor and use logical operations to pick the right destination.
  1816. bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
  1817. unsigned BonusInstThreshold) {
  1818. BasicBlock *BB = BI->getParent();
  1819. Instruction *Cond = nullptr;
  1820. if (BI->isConditional())
  1821. Cond = dyn_cast<Instruction>(BI->getCondition());
  1822. else {
  1823. // For unconditional branch, check for a simple CFG pattern, where
  1824. // BB has a single predecessor and BB's successor is also its predecessor's
  1825. // successor. If such pattern exisits, check for CSE between BB and its
  1826. // predecessor.
  1827. if (BasicBlock *PB = BB->getSinglePredecessor())
  1828. if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
  1829. if (PBI->isConditional() &&
  1830. (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
  1831. BI->getSuccessor(0) == PBI->getSuccessor(1))) {
  1832. for (BasicBlock::iterator I = BB->begin(), E = BB->end();
  1833. I != E; ) {
  1834. Instruction *Curr = I++;
  1835. if (isa<CmpInst>(Curr)) {
  1836. Cond = Curr;
  1837. break;
  1838. }
  1839. // Quit if we can't remove this instruction.
  1840. if (!checkCSEInPredecessor(Curr, PB))
  1841. return false;
  1842. }
  1843. }
  1844. if (!Cond)
  1845. return false;
  1846. }
  1847. if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  1848. Cond->getParent() != BB || !Cond->hasOneUse())
  1849. return false;
  1850. // Make sure the instruction after the condition is the cond branch.
  1851. BasicBlock::iterator CondIt = Cond; ++CondIt;
  1852. // Ignore dbg intrinsics.
  1853. while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
  1854. if (&*CondIt != BI)
  1855. return false;
  1856. // Only allow this transformation if computing the condition doesn't involve
  1857. // too many instructions and these involved instructions can be executed
  1858. // unconditionally. We denote all involved instructions except the condition
  1859. // as "bonus instructions", and only allow this transformation when the
  1860. // number of the bonus instructions does not exceed a certain threshold.
  1861. unsigned NumBonusInsts = 0;
  1862. for (auto I = BB->begin(); Cond != I; ++I) {
  1863. // Ignore dbg intrinsics.
  1864. if (isa<DbgInfoIntrinsic>(I))
  1865. continue;
  1866. if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
  1867. return false;
  1868. // I has only one use and can be executed unconditionally.
  1869. Instruction *User = dyn_cast<Instruction>(I->user_back());
  1870. if (User == nullptr || User->getParent() != BB)
  1871. return false;
  1872. // I is used in the same BB. Since BI uses Cond and doesn't have more slots
  1873. // to use any other instruction, User must be an instruction between next(I)
  1874. // and Cond.
  1875. ++NumBonusInsts;
  1876. // Early exits once we reach the limit.
  1877. if (NumBonusInsts > BonusInstThreshold)
  1878. return false;
  1879. }
  1880. // Cond is known to be a compare or binary operator. Check to make sure that
  1881. // neither operand is a potentially-trapping constant expression.
  1882. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  1883. if (CE->canTrap())
  1884. return false;
  1885. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  1886. if (CE->canTrap())
  1887. return false;
  1888. // Finally, don't infinitely unroll conditional loops.
  1889. BasicBlock *TrueDest = BI->getSuccessor(0);
  1890. BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
  1891. if (TrueDest == BB || FalseDest == BB)
  1892. return false;
  1893. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1894. BasicBlock *PredBlock = *PI;
  1895. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  1896. // Check that we have two conditional branches. If there is a PHI node in
  1897. // the common successor, verify that the same value flows in from both
  1898. // blocks.
  1899. SmallVector<PHINode*, 4> PHIs;
  1900. if (!PBI || PBI->isUnconditional() ||
  1901. (BI->isConditional() &&
  1902. !SafeToMergeTerminators(BI, PBI)) ||
  1903. (!BI->isConditional() &&
  1904. !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
  1905. continue;
  1906. // Determine if the two branches share a common destination.
  1907. Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
  1908. bool InvertPredCond = false;
  1909. if (BI->isConditional()) {
  1910. if (PBI->getSuccessor(0) == TrueDest)
  1911. Opc = Instruction::Or;
  1912. else if (PBI->getSuccessor(1) == FalseDest)
  1913. Opc = Instruction::And;
  1914. else if (PBI->getSuccessor(0) == FalseDest)
  1915. Opc = Instruction::And, InvertPredCond = true;
  1916. else if (PBI->getSuccessor(1) == TrueDest)
  1917. Opc = Instruction::Or, InvertPredCond = true;
  1918. else
  1919. continue;
  1920. } else {
  1921. if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
  1922. continue;
  1923. }
  1924. DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  1925. IRBuilder<> Builder(PBI);
  1926. // If we need to invert the condition in the pred block to match, do so now.
  1927. if (InvertPredCond) {
  1928. Value *NewCond = PBI->getCondition();
  1929. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  1930. CmpInst *CI = cast<CmpInst>(NewCond);
  1931. CI->setPredicate(CI->getInversePredicate());
  1932. } else {
  1933. NewCond = Builder.CreateNot(NewCond,
  1934. PBI->getCondition()->getName()+".not");
  1935. }
  1936. PBI->setCondition(NewCond);
  1937. PBI->swapSuccessors();
  1938. }
  1939. // If we have bonus instructions, clone them into the predecessor block.
  1940. // Note that there may be mutliple predecessor blocks, so we cannot move
  1941. // bonus instructions to a predecessor block.
  1942. ValueToValueMapTy VMap; // maps original values to cloned values
  1943. // We already make sure Cond is the last instruction before BI. Therefore,
  1944. // every instructions before Cond other than DbgInfoIntrinsic are bonus
  1945. // instructions.
  1946. for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
  1947. if (isa<DbgInfoIntrinsic>(BonusInst))
  1948. continue;
  1949. Instruction *NewBonusInst = BonusInst->clone();
  1950. RemapInstruction(NewBonusInst, VMap,
  1951. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1952. VMap[BonusInst] = NewBonusInst;
  1953. // If we moved a load, we cannot any longer claim any knowledge about
  1954. // its potential value. The previous information might have been valid
  1955. // only given the branch precondition.
  1956. // For an analogous reason, we must also drop all the metadata whose
  1957. // semantics we don't understand.
  1958. NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
  1959. PredBlock->getInstList().insert(PBI, NewBonusInst);
  1960. NewBonusInst->takeName(BonusInst);
  1961. BonusInst->setName(BonusInst->getName() + ".old");
  1962. }
  1963. // Clone Cond into the predecessor basic block, and or/and the
  1964. // two conditions together.
  1965. Instruction *New = Cond->clone();
  1966. RemapInstruction(New, VMap,
  1967. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1968. PredBlock->getInstList().insert(PBI, New);
  1969. New->takeName(Cond);
  1970. Cond->setName(New->getName() + ".old");
  1971. if (BI->isConditional()) {
  1972. Instruction *NewCond =
  1973. cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
  1974. New, "or.cond"));
  1975. PBI->setCondition(NewCond);
  1976. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  1977. bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
  1978. PredFalseWeight);
  1979. bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
  1980. SuccFalseWeight);
  1981. SmallVector<uint64_t, 8> NewWeights;
  1982. if (PBI->getSuccessor(0) == BB) {
  1983. if (PredHasWeights && SuccHasWeights) {
  1984. // PBI: br i1 %x, BB, FalseDest
  1985. // BI: br i1 %y, TrueDest, FalseDest
  1986. //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
  1987. NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
  1988. //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
  1989. // TrueWeight for PBI * FalseWeight for BI.
  1990. // We assume that total weights of a BranchInst can fit into 32 bits.
  1991. // Therefore, we will not have overflow using 64-bit arithmetic.
  1992. NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
  1993. SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
  1994. }
  1995. AddPredecessorToBlock(TrueDest, PredBlock, BB);
  1996. PBI->setSuccessor(0, TrueDest);
  1997. }
  1998. if (PBI->getSuccessor(1) == BB) {
  1999. if (PredHasWeights && SuccHasWeights) {
  2000. // PBI: br i1 %x, TrueDest, BB
  2001. // BI: br i1 %y, TrueDest, FalseDest
  2002. //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
  2003. // FalseWeight for PBI * TrueWeight for BI.
  2004. NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
  2005. SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
  2006. //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
  2007. NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
  2008. }
  2009. AddPredecessorToBlock(FalseDest, PredBlock, BB);
  2010. PBI->setSuccessor(1, FalseDest);
  2011. }
  2012. if (NewWeights.size() == 2) {
  2013. // Halve the weights if any of them cannot fit in an uint32_t
  2014. FitWeights(NewWeights);
  2015. SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
  2016. PBI->setMetadata(LLVMContext::MD_prof,
  2017. MDBuilder(BI->getContext()).
  2018. createBranchWeights(MDWeights));
  2019. } else
  2020. PBI->setMetadata(LLVMContext::MD_prof, nullptr);
  2021. } else {
  2022. // Update PHI nodes in the common successors.
  2023. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  2024. ConstantInt *PBI_C = cast<ConstantInt>(
  2025. PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
  2026. assert(PBI_C->getType()->isIntegerTy(1));
  2027. Instruction *MergedCond = nullptr;
  2028. if (PBI->getSuccessor(0) == TrueDest) {
  2029. // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
  2030. // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
  2031. // is false: !PBI_Cond and BI_Value
  2032. Instruction *NotCond =
  2033. cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
  2034. "not.cond"));
  2035. MergedCond =
  2036. cast<Instruction>(Builder.CreateBinOp(Instruction::And,
  2037. NotCond, New,
  2038. "and.cond"));
  2039. if (PBI_C->isOne())
  2040. MergedCond =
  2041. cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
  2042. PBI->getCondition(), MergedCond,
  2043. "or.cond"));
  2044. } else {
  2045. // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
  2046. // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
  2047. // is false: PBI_Cond and BI_Value
  2048. MergedCond =
  2049. cast<Instruction>(Builder.CreateBinOp(Instruction::And,
  2050. PBI->getCondition(), New,
  2051. "and.cond"));
  2052. if (PBI_C->isOne()) {
  2053. Instruction *NotCond =
  2054. cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
  2055. "not.cond"));
  2056. MergedCond =
  2057. cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
  2058. NotCond, MergedCond,
  2059. "or.cond"));
  2060. }
  2061. }
  2062. // Update PHI Node.
  2063. PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
  2064. MergedCond);
  2065. }
  2066. // Change PBI from Conditional to Unconditional.
  2067. BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
  2068. EraseTerminatorInstAndDCECond(PBI);
  2069. PBI = New_PBI;
  2070. }
  2071. // TODO: If BB is reachable from all paths through PredBlock, then we
  2072. // could replace PBI's branch probabilities with BI's.
  2073. // Copy any debug value intrinsics into the end of PredBlock.
  2074. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  2075. if (isa<DbgInfoIntrinsic>(*I))
  2076. I->clone()->insertBefore(PBI);
  2077. return true;
  2078. }
  2079. return false;
  2080. }
  2081. /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
  2082. /// predecessor of another block, this function tries to simplify it. We know
  2083. /// that PBI and BI are both conditional branches, and BI is in one of the
  2084. /// successor blocks of PBI - PBI branches to BI.
  2085. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
  2086. assert(PBI->isConditional() && BI->isConditional());
  2087. BasicBlock *BB = BI->getParent();
  2088. // If this block ends with a branch instruction, and if there is a
  2089. // predecessor that ends on a branch of the same condition, make
  2090. // this conditional branch redundant.
  2091. if (PBI->getCondition() == BI->getCondition() &&
  2092. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2093. // Okay, the outcome of this conditional branch is statically
  2094. // knowable. If this block had a single pred, handle specially.
  2095. if (BB->getSinglePredecessor()) {
  2096. // Turn this into a branch on constant.
  2097. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2098. BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  2099. CondIsTrue));
  2100. return true; // Nuke the branch on constant.
  2101. }
  2102. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  2103. // in the constant and simplify the block result. Subsequent passes of
  2104. // simplifycfg will thread the block.
  2105. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  2106. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  2107. PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
  2108. std::distance(PB, PE),
  2109. BI->getCondition()->getName() + ".pr",
  2110. BB->begin());
  2111. // Okay, we're going to insert the PHI node. Since PBI is not the only
  2112. // predecessor, compute the PHI'd conditional value for all of the preds.
  2113. // Any predecessor where the condition is not computable we keep symbolic.
  2114. for (pred_iterator PI = PB; PI != PE; ++PI) {
  2115. BasicBlock *P = *PI;
  2116. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
  2117. PBI != BI && PBI->isConditional() &&
  2118. PBI->getCondition() == BI->getCondition() &&
  2119. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2120. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2121. NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  2122. CondIsTrue), P);
  2123. } else {
  2124. NewPN->addIncoming(BI->getCondition(), P);
  2125. }
  2126. }
  2127. BI->setCondition(NewPN);
  2128. return true;
  2129. }
  2130. }
  2131. // If this is a conditional branch in an empty block, and if any
  2132. // predecessors are a conditional branch to one of our destinations,
  2133. // fold the conditions into logical ops and one cond br.
  2134. BasicBlock::iterator BBI = BB->begin();
  2135. // Ignore dbg intrinsics.
  2136. while (isa<DbgInfoIntrinsic>(BBI))
  2137. ++BBI;
  2138. if (&*BBI != BI)
  2139. return false;
  2140. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  2141. if (CE->canTrap())
  2142. return false;
  2143. int PBIOp, BIOp;
  2144. if (PBI->getSuccessor(0) == BI->getSuccessor(0))
  2145. PBIOp = BIOp = 0;
  2146. else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
  2147. PBIOp = 0, BIOp = 1;
  2148. else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
  2149. PBIOp = 1, BIOp = 0;
  2150. else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
  2151. PBIOp = BIOp = 1;
  2152. else
  2153. return false;
  2154. // Check to make sure that the other destination of this branch
  2155. // isn't BB itself. If so, this is an infinite loop that will
  2156. // keep getting unwound.
  2157. if (PBI->getSuccessor(PBIOp) == BB)
  2158. return false;
  2159. // Do not perform this transformation if it would require
  2160. // insertion of a large number of select instructions. For targets
  2161. // without predication/cmovs, this is a big pessimization.
  2162. // Also do not perform this transformation if any phi node in the common
  2163. // destination block can trap when reached by BB or PBB (PR17073). In that
  2164. // case, it would be unsafe to hoist the operation into a select instruction.
  2165. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  2166. unsigned NumPhis = 0;
  2167. for (BasicBlock::iterator II = CommonDest->begin();
  2168. isa<PHINode>(II); ++II, ++NumPhis) {
  2169. if (NumPhis > 2) // Disable this xform.
  2170. return false;
  2171. PHINode *PN = cast<PHINode>(II);
  2172. Value *BIV = PN->getIncomingValueForBlock(BB);
  2173. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
  2174. if (CE->canTrap())
  2175. return false;
  2176. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2177. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2178. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
  2179. if (CE->canTrap())
  2180. return false;
  2181. }
  2182. // Finally, if everything is ok, fold the branches to logical ops.
  2183. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  2184. DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  2185. << "AND: " << *BI->getParent());
  2186. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  2187. // branch in it, where one edge (OtherDest) goes back to itself but the other
  2188. // exits. We don't *know* that the program avoids the infinite loop
  2189. // (even though that seems likely). If we do this xform naively, we'll end up
  2190. // recursively unpeeling the loop. Since we know that (after the xform is
  2191. // done) that the block *is* infinite if reached, we just make it an obviously
  2192. // infinite loop with no cond branch.
  2193. if (OtherDest == BB) {
  2194. // Insert it at the end of the function, because it's either code,
  2195. // or it won't matter if it's hot. :)
  2196. BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
  2197. "infloop", BB->getParent());
  2198. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  2199. OtherDest = InfLoopBlock;
  2200. }
  2201. DEBUG(dbgs() << *PBI->getParent()->getParent());
  2202. // BI may have other predecessors. Because of this, we leave
  2203. // it alone, but modify PBI.
  2204. // Make sure we get to CommonDest on True&True directions.
  2205. Value *PBICond = PBI->getCondition();
  2206. IRBuilder<true, NoFolder> Builder(PBI);
  2207. if (PBIOp)
  2208. PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
  2209. Value *BICond = BI->getCondition();
  2210. if (BIOp)
  2211. BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
  2212. // Merge the conditions.
  2213. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  2214. // Modify PBI to branch on the new condition to the new dests.
  2215. PBI->setCondition(Cond);
  2216. PBI->setSuccessor(0, CommonDest);
  2217. PBI->setSuccessor(1, OtherDest);
  2218. // Update branch weight for PBI.
  2219. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2220. bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
  2221. PredFalseWeight);
  2222. bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
  2223. SuccFalseWeight);
  2224. if (PredHasWeights && SuccHasWeights) {
  2225. uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2226. uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
  2227. uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2228. uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2229. // The weight to CommonDest should be PredCommon * SuccTotal +
  2230. // PredOther * SuccCommon.
  2231. // The weight to OtherDest should be PredOther * SuccOther.
  2232. SmallVector<uint64_t, 2> NewWeights;
  2233. NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
  2234. PredOther * SuccCommon);
  2235. NewWeights.push_back(PredOther * SuccOther);
  2236. // Halve the weights if any of them cannot fit in an uint32_t
  2237. FitWeights(NewWeights);
  2238. SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
  2239. PBI->setMetadata(LLVMContext::MD_prof,
  2240. MDBuilder(BI->getContext()).
  2241. createBranchWeights(MDWeights));
  2242. }
  2243. // OtherDest may have phi nodes. If so, add an entry from PBI's
  2244. // block that are identical to the entries for BI's block.
  2245. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  2246. // We know that the CommonDest already had an edge from PBI to
  2247. // it. If it has PHIs though, the PHIs may have different
  2248. // entries for BB and PBI's BB. If so, insert a select to make
  2249. // them agree.
  2250. PHINode *PN;
  2251. for (BasicBlock::iterator II = CommonDest->begin();
  2252. (PN = dyn_cast<PHINode>(II)); ++II) {
  2253. Value *BIV = PN->getIncomingValueForBlock(BB);
  2254. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2255. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2256. if (BIV != PBIV) {
  2257. // Insert a select in PBI to pick the right value.
  2258. Value *NV = cast<SelectInst>
  2259. (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
  2260. PN->setIncomingValue(PBBIdx, NV);
  2261. }
  2262. }
  2263. DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  2264. DEBUG(dbgs() << *PBI->getParent()->getParent());
  2265. // This basic block is probably dead. We know it has at least
  2266. // one fewer predecessor.
  2267. return true;
  2268. }
  2269. // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
  2270. // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
  2271. // Takes care of updating the successors and removing the old terminator.
  2272. // Also makes sure not to introduce new successors by assuming that edges to
  2273. // non-successor TrueBBs and FalseBBs aren't reachable.
  2274. static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
  2275. BasicBlock *TrueBB, BasicBlock *FalseBB,
  2276. uint32_t TrueWeight,
  2277. uint32_t FalseWeight){
  2278. // Remove any superfluous successor edges from the CFG.
  2279. // First, figure out which successors to preserve.
  2280. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  2281. // successor.
  2282. BasicBlock *KeepEdge1 = TrueBB;
  2283. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
  2284. // Then remove the rest.
  2285. for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
  2286. BasicBlock *Succ = OldTerm->getSuccessor(I);
  2287. // Make sure only to keep exactly one copy of each edge.
  2288. if (Succ == KeepEdge1)
  2289. KeepEdge1 = nullptr;
  2290. else if (Succ == KeepEdge2)
  2291. KeepEdge2 = nullptr;
  2292. else
  2293. Succ->removePredecessor(OldTerm->getParent());
  2294. }
  2295. IRBuilder<> Builder(OldTerm);
  2296. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  2297. // Insert an appropriate new terminator.
  2298. if (!KeepEdge1 && !KeepEdge2) {
  2299. if (TrueBB == FalseBB)
  2300. // We were only looking for one successor, and it was present.
  2301. // Create an unconditional branch to it.
  2302. Builder.CreateBr(TrueBB);
  2303. else {
  2304. // We found both of the successors we were looking for.
  2305. // Create a conditional branch sharing the condition of the select.
  2306. BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  2307. if (TrueWeight != FalseWeight)
  2308. NewBI->setMetadata(LLVMContext::MD_prof,
  2309. MDBuilder(OldTerm->getContext()).
  2310. createBranchWeights(TrueWeight, FalseWeight));
  2311. }
  2312. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  2313. // Neither of the selected blocks were successors, so this
  2314. // terminator must be unreachable.
  2315. new UnreachableInst(OldTerm->getContext(), OldTerm);
  2316. } else {
  2317. // One of the selected values was a successor, but the other wasn't.
  2318. // Insert an unconditional branch to the one that was found;
  2319. // the edge to the one that wasn't must be unreachable.
  2320. if (!KeepEdge1)
  2321. // Only TrueBB was found.
  2322. Builder.CreateBr(TrueBB);
  2323. else
  2324. // Only FalseBB was found.
  2325. Builder.CreateBr(FalseBB);
  2326. }
  2327. EraseTerminatorInstAndDCECond(OldTerm);
  2328. return true;
  2329. }
  2330. // SimplifySwitchOnSelect - Replaces
  2331. // (switch (select cond, X, Y)) on constant X, Y
  2332. // with a branch - conditional if X and Y lead to distinct BBs,
  2333. // unconditional otherwise.
  2334. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  2335. // Check for constant integer values in the select.
  2336. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  2337. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  2338. if (!TrueVal || !FalseVal)
  2339. return false;
  2340. // Find the relevant condition and destinations.
  2341. Value *Condition = Select->getCondition();
  2342. BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
  2343. BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
  2344. // Get weight for TrueBB and FalseBB.
  2345. uint32_t TrueWeight = 0, FalseWeight = 0;
  2346. SmallVector<uint64_t, 8> Weights;
  2347. bool HasWeights = HasBranchWeights(SI);
  2348. if (HasWeights) {
  2349. GetBranchWeights(SI, Weights);
  2350. if (Weights.size() == 1 + SI->getNumCases()) {
  2351. TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
  2352. getSuccessorIndex()];
  2353. FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
  2354. getSuccessorIndex()];
  2355. }
  2356. }
  2357. // Perform the actual simplification.
  2358. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
  2359. TrueWeight, FalseWeight);
  2360. }
  2361. // SimplifyIndirectBrOnSelect - Replaces
  2362. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  2363. // blockaddress(@fn, BlockB)))
  2364. // with
  2365. // (br cond, BlockA, BlockB).
  2366. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  2367. // Check that both operands of the select are block addresses.
  2368. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  2369. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  2370. if (!TBA || !FBA)
  2371. return false;
  2372. // Extract the actual blocks.
  2373. BasicBlock *TrueBB = TBA->getBasicBlock();
  2374. BasicBlock *FalseBB = FBA->getBasicBlock();
  2375. // Perform the actual simplification.
  2376. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
  2377. 0, 0);
  2378. }
  2379. /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
  2380. /// instruction (a seteq/setne with a constant) as the only instruction in a
  2381. /// block that ends with an uncond branch. We are looking for a very specific
  2382. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  2383. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  2384. /// default value goes to an uncond block with a seteq in it, we get something
  2385. /// like:
  2386. ///
  2387. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  2388. /// DEFAULT:
  2389. /// %tmp = icmp eq i8 %A, 92
  2390. /// br label %end
  2391. /// end:
  2392. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  2393. ///
  2394. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  2395. /// the PHI, merging the third icmp into the switch.
  2396. static bool TryToSimplifyUncondBranchWithICmpInIt(
  2397. ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
  2398. unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
  2399. BasicBlock *BB = ICI->getParent();
  2400. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  2401. // complex.
  2402. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
  2403. Value *V = ICI->getOperand(0);
  2404. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  2405. // The pattern we're looking for is where our only predecessor is a switch on
  2406. // 'V' and this block is the default case for the switch. In this case we can
  2407. // fold the compared value into the switch to simplify things.
  2408. BasicBlock *Pred = BB->getSinglePredecessor();
  2409. if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
  2410. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  2411. if (SI->getCondition() != V)
  2412. return false;
  2413. // If BB is reachable on a non-default case, then we simply know the value of
  2414. // V in this block. Substitute it and constant fold the icmp instruction
  2415. // away.
  2416. if (SI->getDefaultDest() != BB) {
  2417. ConstantInt *VVal = SI->findCaseDest(BB);
  2418. assert(VVal && "Should have a unique destination value");
  2419. ICI->setOperand(0, VVal);
  2420. if (Value *V = SimplifyInstruction(ICI, DL)) {
  2421. ICI->replaceAllUsesWith(V);
  2422. ICI->eraseFromParent();
  2423. }
  2424. // BB is now empty, so it is likely to simplify away.
  2425. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  2426. }
  2427. // Ok, the block is reachable from the default dest. If the constant we're
  2428. // comparing exists in one of the other edges, then we can constant fold ICI
  2429. // and zap it.
  2430. if (SI->findCaseValue(Cst) != SI->case_default()) {
  2431. Value *V;
  2432. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  2433. V = ConstantInt::getFalse(BB->getContext());
  2434. else
  2435. V = ConstantInt::getTrue(BB->getContext());
  2436. ICI->replaceAllUsesWith(V);
  2437. ICI->eraseFromParent();
  2438. // BB is now empty, so it is likely to simplify away.
  2439. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  2440. }
  2441. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  2442. // the block.
  2443. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  2444. PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
  2445. if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
  2446. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  2447. return false;
  2448. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  2449. // true in the PHI.
  2450. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  2451. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  2452. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  2453. std::swap(DefaultCst, NewCst);
  2454. // Replace ICI (which is used by the PHI for the default value) with true or
  2455. // false depending on if it is EQ or NE.
  2456. ICI->replaceAllUsesWith(DefaultCst);
  2457. ICI->eraseFromParent();
  2458. // Okay, the switch goes to this block on a default value. Add an edge from
  2459. // the switch to the merge point on the compared value.
  2460. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
  2461. BB->getParent(), BB);
  2462. SmallVector<uint64_t, 8> Weights;
  2463. bool HasWeights = HasBranchWeights(SI);
  2464. if (HasWeights) {
  2465. GetBranchWeights(SI, Weights);
  2466. if (Weights.size() == 1 + SI->getNumCases()) {
  2467. // Split weight for default case to case for "Cst".
  2468. Weights[0] = (Weights[0]+1) >> 1;
  2469. Weights.push_back(Weights[0]);
  2470. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  2471. SI->setMetadata(LLVMContext::MD_prof,
  2472. MDBuilder(SI->getContext()).
  2473. createBranchWeights(MDWeights));
  2474. }
  2475. }
  2476. SI->addCase(Cst, NewBB);
  2477. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  2478. Builder.SetInsertPoint(NewBB);
  2479. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  2480. Builder.CreateBr(SuccBlock);
  2481. PHIUse->addIncoming(NewCst, NewBB);
  2482. return true;
  2483. }
  2484. /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
  2485. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  2486. /// fold it into a switch instruction if so.
  2487. static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
  2488. IRBuilder<> &Builder) {
  2489. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  2490. if (!Cond) return false;
  2491. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  2492. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  2493. // 'setne's and'ed together, collect them.
  2494. // Try to gather values from a chain of and/or to be turned into a switch
  2495. ConstantComparesGatherer ConstantCompare(Cond, DL);
  2496. // Unpack the result
  2497. SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
  2498. Value *CompVal = ConstantCompare.CompValue;
  2499. unsigned UsedICmps = ConstantCompare.UsedICmps;
  2500. Value *ExtraCase = ConstantCompare.Extra;
  2501. // If we didn't have a multiply compared value, fail.
  2502. if (!CompVal) return false;
  2503. // Avoid turning single icmps into a switch.
  2504. if (UsedICmps <= 1)
  2505. return false;
  2506. bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
  2507. // There might be duplicate constants in the list, which the switch
  2508. // instruction can't handle, remove them now.
  2509. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  2510. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  2511. // If Extra was used, we require at least two switch values to do the
  2512. // transformation. A switch with one value is just an cond branch.
  2513. if (ExtraCase && Values.size() < 2) return false;
  2514. // TODO: Preserve branch weight metadata, similarly to how
  2515. // FoldValueComparisonIntoPredecessors preserves it.
  2516. // Figure out which block is which destination.
  2517. BasicBlock *DefaultBB = BI->getSuccessor(1);
  2518. BasicBlock *EdgeBB = BI->getSuccessor(0);
  2519. if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
  2520. BasicBlock *BB = BI->getParent();
  2521. DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  2522. << " cases into SWITCH. BB is:\n" << *BB);
  2523. // If there are any extra values that couldn't be folded into the switch
  2524. // then we evaluate them with an explicit branch first. Split the block
  2525. // right before the condbr to handle it.
  2526. if (ExtraCase) {
  2527. BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
  2528. // Remove the uncond branch added to the old block.
  2529. TerminatorInst *OldTI = BB->getTerminator();
  2530. Builder.SetInsertPoint(OldTI);
  2531. if (TrueWhenEqual)
  2532. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  2533. else
  2534. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  2535. OldTI->eraseFromParent();
  2536. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  2537. // for the edge we just added.
  2538. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  2539. DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  2540. << "\nEXTRABB = " << *BB);
  2541. BB = NewBB;
  2542. }
  2543. Builder.SetInsertPoint(BI);
  2544. // Convert pointer to int before we switch.
  2545. if (CompVal->getType()->isPointerTy()) {
  2546. assert(DL && "Cannot switch on pointer without DataLayout");
  2547. CompVal = Builder.CreatePtrToInt(CompVal,
  2548. DL->getIntPtrType(CompVal->getType()),
  2549. "magicptr");
  2550. }
  2551. // Create the new switch instruction now.
  2552. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  2553. // Add all of the 'cases' to the switch instruction.
  2554. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  2555. New->addCase(Values[i], EdgeBB);
  2556. // We added edges from PI to the EdgeBB. As such, if there were any
  2557. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  2558. // the number of edges added.
  2559. for (BasicBlock::iterator BBI = EdgeBB->begin();
  2560. isa<PHINode>(BBI); ++BBI) {
  2561. PHINode *PN = cast<PHINode>(BBI);
  2562. Value *InVal = PN->getIncomingValueForBlock(BB);
  2563. for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
  2564. PN->addIncoming(InVal, BB);
  2565. }
  2566. // Erase the old branch instruction.
  2567. EraseTerminatorInstAndDCECond(BI);
  2568. DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  2569. return true;
  2570. }
  2571. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  2572. // If this is a trivial landing pad that just continues unwinding the caught
  2573. // exception then zap the landing pad, turning its invokes into calls.
  2574. BasicBlock *BB = RI->getParent();
  2575. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  2576. if (RI->getValue() != LPInst)
  2577. // Not a landing pad, or the resume is not unwinding the exception that
  2578. // caused control to branch here.
  2579. return false;
  2580. // Check that there are no other instructions except for debug intrinsics.
  2581. BasicBlock::iterator I = LPInst, E = RI;
  2582. while (++I != E)
  2583. if (!isa<DbgInfoIntrinsic>(I))
  2584. return false;
  2585. // Turn all invokes that unwind here into calls and delete the basic block.
  2586. bool InvokeRequiresTableEntry = false;
  2587. bool Changed = false;
  2588. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  2589. InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
  2590. if (II->hasFnAttr(Attribute::UWTable)) {
  2591. // Don't remove an `invoke' instruction if the ABI requires an entry into
  2592. // the table.
  2593. InvokeRequiresTableEntry = true;
  2594. continue;
  2595. }
  2596. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  2597. // Insert a call instruction before the invoke.
  2598. CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
  2599. Call->takeName(II);
  2600. Call->setCallingConv(II->getCallingConv());
  2601. Call->setAttributes(II->getAttributes());
  2602. Call->setDebugLoc(II->getDebugLoc());
  2603. // Anything that used the value produced by the invoke instruction now uses
  2604. // the value produced by the call instruction. Note that we do this even
  2605. // for void functions and calls with no uses so that the callgraph edge is
  2606. // updated.
  2607. II->replaceAllUsesWith(Call);
  2608. BB->removePredecessor(II->getParent());
  2609. // Insert a branch to the normal destination right before the invoke.
  2610. BranchInst::Create(II->getNormalDest(), II);
  2611. // Finally, delete the invoke instruction!
  2612. II->eraseFromParent();
  2613. Changed = true;
  2614. }
  2615. if (!InvokeRequiresTableEntry)
  2616. // The landingpad is now unreachable. Zap it.
  2617. BB->eraseFromParent();
  2618. return Changed;
  2619. }
  2620. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  2621. BasicBlock *BB = RI->getParent();
  2622. if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
  2623. // Find predecessors that end with branches.
  2624. SmallVector<BasicBlock*, 8> UncondBranchPreds;
  2625. SmallVector<BranchInst*, 8> CondBranchPreds;
  2626. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2627. BasicBlock *P = *PI;
  2628. TerminatorInst *PTI = P->getTerminator();
  2629. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  2630. if (BI->isUnconditional())
  2631. UncondBranchPreds.push_back(P);
  2632. else
  2633. CondBranchPreds.push_back(BI);
  2634. }
  2635. }
  2636. // If we found some, do the transformation!
  2637. if (!UncondBranchPreds.empty() && DupRet) {
  2638. while (!UncondBranchPreds.empty()) {
  2639. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  2640. DEBUG(dbgs() << "FOLDING: " << *BB
  2641. << "INTO UNCOND BRANCH PRED: " << *Pred);
  2642. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  2643. }
  2644. // If we eliminated all predecessors of the block, delete the block now.
  2645. if (pred_begin(BB) == pred_end(BB))
  2646. // We know there are no successors, so just nuke the block.
  2647. BB->eraseFromParent();
  2648. return true;
  2649. }
  2650. // Check out all of the conditional branches going to this return
  2651. // instruction. If any of them just select between returns, change the
  2652. // branch itself into a select/return pair.
  2653. while (!CondBranchPreds.empty()) {
  2654. BranchInst *BI = CondBranchPreds.pop_back_val();
  2655. // Check to see if the non-BB successor is also a return block.
  2656. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  2657. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  2658. SimplifyCondBranchToTwoReturns(BI, Builder))
  2659. return true;
  2660. }
  2661. return false;
  2662. }
  2663. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  2664. BasicBlock *BB = UI->getParent();
  2665. bool Changed = false;
  2666. // If there are any instructions immediately before the unreachable that can
  2667. // be removed, do so.
  2668. while (UI != BB->begin()) {
  2669. BasicBlock::iterator BBI = UI;
  2670. --BBI;
  2671. // Do not delete instructions that can have side effects which might cause
  2672. // the unreachable to not be reachable; specifically, calls and volatile
  2673. // operations may have this effect.
  2674. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
  2675. if (BBI->mayHaveSideEffects()) {
  2676. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  2677. if (SI->isVolatile())
  2678. break;
  2679. } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  2680. if (LI->isVolatile())
  2681. break;
  2682. } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  2683. if (RMWI->isVolatile())
  2684. break;
  2685. } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  2686. if (CXI->isVolatile())
  2687. break;
  2688. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  2689. !isa<LandingPadInst>(BBI)) {
  2690. break;
  2691. }
  2692. // Note that deleting LandingPad's here is in fact okay, although it
  2693. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  2694. // all the predecessors of this block will be the unwind edges of Invokes,
  2695. // and we can therefore guarantee this block will be erased.
  2696. }
  2697. // Delete this instruction (any uses are guaranteed to be dead)
  2698. if (!BBI->use_empty())
  2699. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  2700. BBI->eraseFromParent();
  2701. Changed = true;
  2702. }
  2703. // If the unreachable instruction is the first in the block, take a gander
  2704. // at all of the predecessors of this instruction, and simplify them.
  2705. if (&BB->front() != UI) return Changed;
  2706. SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
  2707. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  2708. TerminatorInst *TI = Preds[i]->getTerminator();
  2709. IRBuilder<> Builder(TI);
  2710. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2711. if (BI->isUnconditional()) {
  2712. if (BI->getSuccessor(0) == BB) {
  2713. new UnreachableInst(TI->getContext(), TI);
  2714. TI->eraseFromParent();
  2715. Changed = true;
  2716. }
  2717. } else {
  2718. if (BI->getSuccessor(0) == BB) {
  2719. Builder.CreateBr(BI->getSuccessor(1));
  2720. EraseTerminatorInstAndDCECond(BI);
  2721. } else if (BI->getSuccessor(1) == BB) {
  2722. Builder.CreateBr(BI->getSuccessor(0));
  2723. EraseTerminatorInstAndDCECond(BI);
  2724. Changed = true;
  2725. }
  2726. }
  2727. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2728. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2729. i != e; ++i)
  2730. if (i.getCaseSuccessor() == BB) {
  2731. BB->removePredecessor(SI->getParent());
  2732. SI->removeCase(i);
  2733. --i; --e;
  2734. Changed = true;
  2735. }
  2736. // If the default value is unreachable, figure out the most popular
  2737. // destination and make it the default.
  2738. if (SI->getDefaultDest() == BB) {
  2739. std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
  2740. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2741. i != e; ++i) {
  2742. std::pair<unsigned, unsigned> &entry =
  2743. Popularity[i.getCaseSuccessor()];
  2744. if (entry.first == 0) {
  2745. entry.first = 1;
  2746. entry.second = i.getCaseIndex();
  2747. } else {
  2748. entry.first++;
  2749. }
  2750. }
  2751. // Find the most popular block.
  2752. unsigned MaxPop = 0;
  2753. unsigned MaxIndex = 0;
  2754. BasicBlock *MaxBlock = nullptr;
  2755. for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
  2756. I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
  2757. if (I->second.first > MaxPop ||
  2758. (I->second.first == MaxPop && MaxIndex > I->second.second)) {
  2759. MaxPop = I->second.first;
  2760. MaxIndex = I->second.second;
  2761. MaxBlock = I->first;
  2762. }
  2763. }
  2764. if (MaxBlock) {
  2765. // Make this the new default, allowing us to delete any explicit
  2766. // edges to it.
  2767. SI->setDefaultDest(MaxBlock);
  2768. Changed = true;
  2769. // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
  2770. // it.
  2771. if (isa<PHINode>(MaxBlock->begin()))
  2772. for (unsigned i = 0; i != MaxPop-1; ++i)
  2773. MaxBlock->removePredecessor(SI->getParent());
  2774. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2775. i != e; ++i)
  2776. if (i.getCaseSuccessor() == MaxBlock) {
  2777. SI->removeCase(i);
  2778. --i; --e;
  2779. }
  2780. }
  2781. }
  2782. } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
  2783. if (II->getUnwindDest() == BB) {
  2784. // Convert the invoke to a call instruction. This would be a good
  2785. // place to note that the call does not throw though.
  2786. BranchInst *BI = Builder.CreateBr(II->getNormalDest());
  2787. II->removeFromParent(); // Take out of symbol table
  2788. // Insert the call now...
  2789. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
  2790. Builder.SetInsertPoint(BI);
  2791. CallInst *CI = Builder.CreateCall(II->getCalledValue(),
  2792. Args, II->getName());
  2793. CI->setCallingConv(II->getCallingConv());
  2794. CI->setAttributes(II->getAttributes());
  2795. // If the invoke produced a value, the call does now instead.
  2796. II->replaceAllUsesWith(CI);
  2797. delete II;
  2798. Changed = true;
  2799. }
  2800. }
  2801. }
  2802. // If this block is now dead, remove it.
  2803. if (pred_begin(BB) == pred_end(BB) &&
  2804. BB != &BB->getParent()->getEntryBlock()) {
  2805. // We know there are no successors, so just nuke the block.
  2806. BB->eraseFromParent();
  2807. return true;
  2808. }
  2809. return Changed;
  2810. }
  2811. /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
  2812. /// integer range comparison into a sub, an icmp and a branch.
  2813. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  2814. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  2815. // Make sure all cases point to the same destination and gather the values.
  2816. SmallVector<ConstantInt *, 16> Cases;
  2817. SwitchInst::CaseIt I = SI->case_begin();
  2818. Cases.push_back(I.getCaseValue());
  2819. SwitchInst::CaseIt PrevI = I++;
  2820. for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
  2821. if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
  2822. return false;
  2823. Cases.push_back(I.getCaseValue());
  2824. }
  2825. assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
  2826. // Sort the case values, then check if they form a range we can transform.
  2827. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  2828. for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
  2829. if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
  2830. return false;
  2831. }
  2832. Constant *Offset = ConstantExpr::getNeg(Cases.back());
  2833. Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
  2834. Value *Sub = SI->getCondition();
  2835. if (!Offset->isNullValue())
  2836. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
  2837. Value *Cmp;
  2838. // If NumCases overflowed, then all possible values jump to the successor.
  2839. if (NumCases->isNullValue() && SI->getNumCases() != 0)
  2840. Cmp = ConstantInt::getTrue(SI->getContext());
  2841. else
  2842. Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  2843. BranchInst *NewBI = Builder.CreateCondBr(
  2844. Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
  2845. // Update weight for the newly-created conditional branch.
  2846. SmallVector<uint64_t, 8> Weights;
  2847. bool HasWeights = HasBranchWeights(SI);
  2848. if (HasWeights) {
  2849. GetBranchWeights(SI, Weights);
  2850. if (Weights.size() == 1 + SI->getNumCases()) {
  2851. // Combine all weights for the cases to be the true weight of NewBI.
  2852. // We assume that the sum of all weights for a Terminator can fit into 32
  2853. // bits.
  2854. uint32_t NewTrueWeight = 0;
  2855. for (unsigned I = 1, E = Weights.size(); I != E; ++I)
  2856. NewTrueWeight += (uint32_t)Weights[I];
  2857. NewBI->setMetadata(LLVMContext::MD_prof,
  2858. MDBuilder(SI->getContext()).
  2859. createBranchWeights(NewTrueWeight,
  2860. (uint32_t)Weights[0]));
  2861. }
  2862. }
  2863. // Prune obsolete incoming values off the successor's PHI nodes.
  2864. for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
  2865. isa<PHINode>(BBI); ++BBI) {
  2866. for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
  2867. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2868. }
  2869. SI->eraseFromParent();
  2870. return true;
  2871. }
  2872. /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
  2873. /// and use it to remove dead cases.
  2874. static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
  2875. AssumptionTracker *AT) {
  2876. Value *Cond = SI->getCondition();
  2877. unsigned Bits = Cond->getType()->getIntegerBitWidth();
  2878. APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
  2879. computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
  2880. // Gather dead cases.
  2881. SmallVector<ConstantInt*, 8> DeadCases;
  2882. for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
  2883. if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
  2884. (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
  2885. DeadCases.push_back(I.getCaseValue());
  2886. DEBUG(dbgs() << "SimplifyCFG: switch case '"
  2887. << I.getCaseValue() << "' is dead.\n");
  2888. }
  2889. }
  2890. SmallVector<uint64_t, 8> Weights;
  2891. bool HasWeight = HasBranchWeights(SI);
  2892. if (HasWeight) {
  2893. GetBranchWeights(SI, Weights);
  2894. HasWeight = (Weights.size() == 1 + SI->getNumCases());
  2895. }
  2896. // Remove dead cases from the switch.
  2897. for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
  2898. SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
  2899. assert(Case != SI->case_default() &&
  2900. "Case was not found. Probably mistake in DeadCases forming.");
  2901. if (HasWeight) {
  2902. std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
  2903. Weights.pop_back();
  2904. }
  2905. // Prune unused values from PHI nodes.
  2906. Case.getCaseSuccessor()->removePredecessor(SI->getParent());
  2907. SI->removeCase(Case);
  2908. }
  2909. if (HasWeight && Weights.size() >= 2) {
  2910. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  2911. SI->setMetadata(LLVMContext::MD_prof,
  2912. MDBuilder(SI->getParent()->getContext()).
  2913. createBranchWeights(MDWeights));
  2914. }
  2915. return !DeadCases.empty();
  2916. }
  2917. /// FindPHIForConditionForwarding - If BB would be eligible for simplification
  2918. /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  2919. /// by an unconditional branch), look at the phi node for BB in the successor
  2920. /// block and see if the incoming value is equal to CaseValue. If so, return
  2921. /// the phi node, and set PhiIndex to BB's index in the phi node.
  2922. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  2923. BasicBlock *BB,
  2924. int *PhiIndex) {
  2925. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  2926. return nullptr; // BB must be empty to be a candidate for simplification.
  2927. if (!BB->getSinglePredecessor())
  2928. return nullptr; // BB must be dominated by the switch.
  2929. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  2930. if (!Branch || !Branch->isUnconditional())
  2931. return nullptr; // Terminator must be unconditional branch.
  2932. BasicBlock *Succ = Branch->getSuccessor(0);
  2933. BasicBlock::iterator I = Succ->begin();
  2934. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  2935. int Idx = PHI->getBasicBlockIndex(BB);
  2936. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  2937. Value *InValue = PHI->getIncomingValue(Idx);
  2938. if (InValue != CaseValue) continue;
  2939. *PhiIndex = Idx;
  2940. return PHI;
  2941. }
  2942. return nullptr;
  2943. }
  2944. /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
  2945. /// instruction to a phi node dominated by the switch, if that would mean that
  2946. /// some of the destination blocks of the switch can be folded away.
  2947. /// Returns true if a change is made.
  2948. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  2949. typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
  2950. ForwardingNodesMap ForwardingNodes;
  2951. for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
  2952. ConstantInt *CaseValue = I.getCaseValue();
  2953. BasicBlock *CaseDest = I.getCaseSuccessor();
  2954. int PhiIndex;
  2955. PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
  2956. &PhiIndex);
  2957. if (!PHI) continue;
  2958. ForwardingNodes[PHI].push_back(PhiIndex);
  2959. }
  2960. bool Changed = false;
  2961. for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
  2962. E = ForwardingNodes.end(); I != E; ++I) {
  2963. PHINode *Phi = I->first;
  2964. SmallVectorImpl<int> &Indexes = I->second;
  2965. if (Indexes.size() < 2) continue;
  2966. for (size_t I = 0, E = Indexes.size(); I != E; ++I)
  2967. Phi->setIncomingValue(Indexes[I], SI->getCondition());
  2968. Changed = true;
  2969. }
  2970. return Changed;
  2971. }
  2972. /// ValidLookupTableConstant - Return true if the backend will be able to handle
  2973. /// initializing an array of constants like C.
  2974. static bool ValidLookupTableConstant(Constant *C) {
  2975. if (C->isThreadDependent())
  2976. return false;
  2977. if (C->isDLLImportDependent())
  2978. return false;
  2979. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
  2980. return CE->isGEPWithNoNotionalOverIndexing();
  2981. return isa<ConstantFP>(C) ||
  2982. isa<ConstantInt>(C) ||
  2983. isa<ConstantPointerNull>(C) ||
  2984. isa<GlobalValue>(C) ||
  2985. isa<UndefValue>(C);
  2986. }
  2987. /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
  2988. /// its constant value in ConstantPool, returning 0 if it's not there.
  2989. static Constant *LookupConstant(Value *V,
  2990. const SmallDenseMap<Value*, Constant*>& ConstantPool) {
  2991. if (Constant *C = dyn_cast<Constant>(V))
  2992. return C;
  2993. return ConstantPool.lookup(V);
  2994. }
  2995. /// ConstantFold - Try to fold instruction I into a constant. This works for
  2996. /// simple instructions such as binary operations where both operands are
  2997. /// constant or can be replaced by constants from the ConstantPool. Returns the
  2998. /// resulting constant on success, 0 otherwise.
  2999. static Constant *
  3000. ConstantFold(Instruction *I,
  3001. const SmallDenseMap<Value *, Constant *> &ConstantPool,
  3002. const DataLayout *DL) {
  3003. if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  3004. Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
  3005. if (!A)
  3006. return nullptr;
  3007. if (A->isAllOnesValue())
  3008. return LookupConstant(Select->getTrueValue(), ConstantPool);
  3009. if (A->isNullValue())
  3010. return LookupConstant(Select->getFalseValue(), ConstantPool);
  3011. return nullptr;
  3012. }
  3013. SmallVector<Constant *, 4> COps;
  3014. for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
  3015. if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
  3016. COps.push_back(A);
  3017. else
  3018. return nullptr;
  3019. }
  3020. if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
  3021. return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
  3022. COps[1], DL);
  3023. return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
  3024. }
  3025. /// GetCaseResults - Try to determine the resulting constant values in phi nodes
  3026. /// at the common destination basic block, *CommonDest, for one of the case
  3027. /// destionations CaseDest corresponding to value CaseVal (0 for the default
  3028. /// case), of a switch instruction SI.
  3029. static bool
  3030. GetCaseResults(SwitchInst *SI,
  3031. ConstantInt *CaseVal,
  3032. BasicBlock *CaseDest,
  3033. BasicBlock **CommonDest,
  3034. SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
  3035. const DataLayout *DL) {
  3036. // The block from which we enter the common destination.
  3037. BasicBlock *Pred = SI->getParent();
  3038. // If CaseDest is empty except for some side-effect free instructions through
  3039. // which we can constant-propagate the CaseVal, continue to its successor.
  3040. SmallDenseMap<Value*, Constant*> ConstantPool;
  3041. ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
  3042. for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
  3043. ++I) {
  3044. if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
  3045. // If the terminator is a simple branch, continue to the next block.
  3046. if (T->getNumSuccessors() != 1)
  3047. return false;
  3048. Pred = CaseDest;
  3049. CaseDest = T->getSuccessor(0);
  3050. } else if (isa<DbgInfoIntrinsic>(I)) {
  3051. // Skip debug intrinsic.
  3052. continue;
  3053. } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
  3054. // Instruction is side-effect free and constant.
  3055. ConstantPool.insert(std::make_pair(I, C));
  3056. } else {
  3057. break;
  3058. }
  3059. }
  3060. // If we did not have a CommonDest before, use the current one.
  3061. if (!*CommonDest)
  3062. *CommonDest = CaseDest;
  3063. // If the destination isn't the common one, abort.
  3064. if (CaseDest != *CommonDest)
  3065. return false;
  3066. // Get the values for this case from phi nodes in the destination block.
  3067. BasicBlock::iterator I = (*CommonDest)->begin();
  3068. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  3069. int Idx = PHI->getBasicBlockIndex(Pred);
  3070. if (Idx == -1)
  3071. continue;
  3072. Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
  3073. ConstantPool);
  3074. if (!ConstVal)
  3075. return false;
  3076. // Note: If the constant comes from constant-propagating the case value
  3077. // through the CaseDest basic block, it will be safe to remove the
  3078. // instructions in that block. They cannot be used (except in the phi nodes
  3079. // we visit) outside CaseDest, because that block does not dominate its
  3080. // successor. If it did, we would not be in this phi node.
  3081. // Be conservative about which kinds of constants we support.
  3082. if (!ValidLookupTableConstant(ConstVal))
  3083. return false;
  3084. Res.push_back(std::make_pair(PHI, ConstVal));
  3085. }
  3086. return Res.size() > 0;
  3087. }
  3088. // MapCaseToResult - Helper function used to
  3089. // add CaseVal to the list of cases that generate Result.
  3090. static void MapCaseToResult(ConstantInt *CaseVal,
  3091. SwitchCaseResultVectorTy &UniqueResults,
  3092. Constant *Result) {
  3093. for (auto &I : UniqueResults) {
  3094. if (I.first == Result) {
  3095. I.second.push_back(CaseVal);
  3096. return;
  3097. }
  3098. }
  3099. UniqueResults.push_back(std::make_pair(Result,
  3100. SmallVector<ConstantInt*, 4>(1, CaseVal)));
  3101. }
  3102. // InitializeUniqueCases - Helper function that initializes a map containing
  3103. // results for the PHI node of the common destination block for a switch
  3104. // instruction. Returns false if multiple PHI nodes have been found or if
  3105. // there is not a common destination block for the switch.
  3106. static bool InitializeUniqueCases(
  3107. SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
  3108. BasicBlock *&CommonDest,
  3109. SwitchCaseResultVectorTy &UniqueResults,
  3110. Constant *&DefaultResult) {
  3111. for (auto &I : SI->cases()) {
  3112. ConstantInt *CaseVal = I.getCaseValue();
  3113. // Resulting value at phi nodes for this case value.
  3114. SwitchCaseResultsTy Results;
  3115. if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
  3116. DL))
  3117. return false;
  3118. // Only one value per case is permitted
  3119. if (Results.size() > 1)
  3120. return false;
  3121. MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
  3122. // Check the PHI consistency.
  3123. if (!PHI)
  3124. PHI = Results[0].first;
  3125. else if (PHI != Results[0].first)
  3126. return false;
  3127. }
  3128. // Find the default result value.
  3129. SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
  3130. BasicBlock *DefaultDest = SI->getDefaultDest();
  3131. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
  3132. DL);
  3133. // If the default value is not found abort unless the default destination
  3134. // is unreachable.
  3135. DefaultResult =
  3136. DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
  3137. if ((!DefaultResult &&
  3138. !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
  3139. return false;
  3140. return true;
  3141. }
  3142. // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
  3143. // transform a switch with only two cases (or two cases + default)
  3144. // that produces a result into a value select.
  3145. // Example:
  3146. // switch (a) {
  3147. // case 10: %0 = icmp eq i32 %a, 10
  3148. // return 10; %1 = select i1 %0, i32 10, i32 4
  3149. // case 20: ----> %2 = icmp eq i32 %a, 20
  3150. // return 2; %3 = select i1 %2, i32 2, i32 %1
  3151. // default:
  3152. // return 4;
  3153. // }
  3154. static Value *
  3155. ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
  3156. Constant *DefaultResult, Value *Condition,
  3157. IRBuilder<> &Builder) {
  3158. assert(ResultVector.size() == 2 &&
  3159. "We should have exactly two unique results at this point");
  3160. // If we are selecting between only two cases transform into a simple
  3161. // select or a two-way select if default is possible.
  3162. if (ResultVector[0].second.size() == 1 &&
  3163. ResultVector[1].second.size() == 1) {
  3164. ConstantInt *const FirstCase = ResultVector[0].second[0];
  3165. ConstantInt *const SecondCase = ResultVector[1].second[0];
  3166. bool DefaultCanTrigger = DefaultResult;
  3167. Value *SelectValue = ResultVector[1].first;
  3168. if (DefaultCanTrigger) {
  3169. Value *const ValueCompare =
  3170. Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
  3171. SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
  3172. DefaultResult, "switch.select");
  3173. }
  3174. Value *const ValueCompare =
  3175. Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
  3176. return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
  3177. "switch.select");
  3178. }
  3179. return nullptr;
  3180. }
  3181. // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
  3182. // instruction that has been converted into a select, fixing up PHI nodes and
  3183. // basic blocks.
  3184. static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
  3185. Value *SelectValue,
  3186. IRBuilder<> &Builder) {
  3187. BasicBlock *SelectBB = SI->getParent();
  3188. while (PHI->getBasicBlockIndex(SelectBB) >= 0)
  3189. PHI->removeIncomingValue(SelectBB);
  3190. PHI->addIncoming(SelectValue, SelectBB);
  3191. Builder.CreateBr(PHI->getParent());
  3192. // Remove the switch.
  3193. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  3194. BasicBlock *Succ = SI->getSuccessor(i);
  3195. if (Succ == PHI->getParent())
  3196. continue;
  3197. Succ->removePredecessor(SelectBB);
  3198. }
  3199. SI->eraseFromParent();
  3200. }
  3201. /// SwitchToSelect - If the switch is only used to initialize one or more
  3202. /// phi nodes in a common successor block with only two different
  3203. /// constant values, replace the switch with select.
  3204. static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
  3205. const DataLayout *DL, AssumptionTracker *AT) {
  3206. Value *const Cond = SI->getCondition();
  3207. PHINode *PHI = nullptr;
  3208. BasicBlock *CommonDest = nullptr;
  3209. Constant *DefaultResult;
  3210. SwitchCaseResultVectorTy UniqueResults;
  3211. // Collect all the cases that will deliver the same value from the switch.
  3212. if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
  3213. DefaultResult))
  3214. return false;
  3215. // Selects choose between maximum two values.
  3216. if (UniqueResults.size() != 2)
  3217. return false;
  3218. assert(PHI != nullptr && "PHI for value select not found");
  3219. Builder.SetInsertPoint(SI);
  3220. Value *SelectValue = ConvertTwoCaseSwitch(
  3221. UniqueResults,
  3222. DefaultResult, Cond, Builder);
  3223. if (SelectValue) {
  3224. RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
  3225. return true;
  3226. }
  3227. // The switch couldn't be converted into a select.
  3228. return false;
  3229. }
  3230. namespace {
  3231. /// SwitchLookupTable - This class represents a lookup table that can be used
  3232. /// to replace a switch.
  3233. class SwitchLookupTable {
  3234. public:
  3235. /// SwitchLookupTable - Create a lookup table to use as a switch replacement
  3236. /// with the contents of Values, using DefaultValue to fill any holes in the
  3237. /// table.
  3238. SwitchLookupTable(Module &M,
  3239. uint64_t TableSize,
  3240. ConstantInt *Offset,
  3241. const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
  3242. Constant *DefaultValue,
  3243. const DataLayout *DL);
  3244. /// BuildLookup - Build instructions with Builder to retrieve the value at
  3245. /// the position given by Index in the lookup table.
  3246. Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
  3247. /// WouldFitInRegister - Return true if a table with TableSize elements of
  3248. /// type ElementType would fit in a target-legal register.
  3249. static bool WouldFitInRegister(const DataLayout *DL,
  3250. uint64_t TableSize,
  3251. const Type *ElementType);
  3252. private:
  3253. // Depending on the contents of the table, it can be represented in
  3254. // different ways.
  3255. enum {
  3256. // For tables where each element contains the same value, we just have to
  3257. // store that single value and return it for each lookup.
  3258. SingleValueKind,
  3259. // For tables where there is a linear relationship between table index
  3260. // and values. We calculate the result with a simple multiplication
  3261. // and addition instead of a table lookup.
  3262. LinearMapKind,
  3263. // For small tables with integer elements, we can pack them into a bitmap
  3264. // that fits into a target-legal register. Values are retrieved by
  3265. // shift and mask operations.
  3266. BitMapKind,
  3267. // The table is stored as an array of values. Values are retrieved by load
  3268. // instructions from the table.
  3269. ArrayKind
  3270. } Kind;
  3271. // For SingleValueKind, this is the single value.
  3272. Constant *SingleValue;
  3273. // For BitMapKind, this is the bitmap.
  3274. ConstantInt *BitMap;
  3275. IntegerType *BitMapElementTy;
  3276. // For LinearMapKind, these are the constants used to derive the value.
  3277. ConstantInt *LinearOffset;
  3278. ConstantInt *LinearMultiplier;
  3279. // For ArrayKind, this is the array.
  3280. GlobalVariable *Array;
  3281. };
  3282. }
  3283. SwitchLookupTable::SwitchLookupTable(Module &M,
  3284. uint64_t TableSize,
  3285. ConstantInt *Offset,
  3286. const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
  3287. Constant *DefaultValue,
  3288. const DataLayout *DL)
  3289. : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
  3290. LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
  3291. assert(Values.size() && "Can't build lookup table without values!");
  3292. assert(TableSize >= Values.size() && "Can't fit values in table!");
  3293. // If all values in the table are equal, this is that value.
  3294. SingleValue = Values.begin()->second;
  3295. Type *ValueType = Values.begin()->second->getType();
  3296. // Build up the table contents.
  3297. SmallVector<Constant*, 64> TableContents(TableSize);
  3298. for (size_t I = 0, E = Values.size(); I != E; ++I) {
  3299. ConstantInt *CaseVal = Values[I].first;
  3300. Constant *CaseRes = Values[I].second;
  3301. assert(CaseRes->getType() == ValueType);
  3302. uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
  3303. .getLimitedValue();
  3304. TableContents[Idx] = CaseRes;
  3305. if (CaseRes != SingleValue)
  3306. SingleValue = nullptr;
  3307. }
  3308. // Fill in any holes in the table with the default result.
  3309. if (Values.size() < TableSize) {
  3310. assert(DefaultValue &&
  3311. "Need a default value to fill the lookup table holes.");
  3312. assert(DefaultValue->getType() == ValueType);
  3313. for (uint64_t I = 0; I < TableSize; ++I) {
  3314. if (!TableContents[I])
  3315. TableContents[I] = DefaultValue;
  3316. }
  3317. if (DefaultValue != SingleValue)
  3318. SingleValue = nullptr;
  3319. }
  3320. // If each element in the table contains the same value, we only need to store
  3321. // that single value.
  3322. if (SingleValue) {
  3323. Kind = SingleValueKind;
  3324. return;
  3325. }
  3326. // Check if we can derive the value with a linear transformation from the
  3327. // table index.
  3328. if (isa<IntegerType>(ValueType)) {
  3329. bool LinearMappingPossible = true;
  3330. APInt PrevVal;
  3331. APInt DistToPrev;
  3332. assert(TableSize >= 2 && "Should be a SingleValue table.");
  3333. // Check if there is the same distance between two consecutive values.
  3334. for (uint64_t I = 0; I < TableSize; ++I) {
  3335. ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
  3336. if (!ConstVal) {
  3337. // This is an undef. We could deal with it, but undefs in lookup tables
  3338. // are very seldom. It's probably not worth the additional complexity.
  3339. LinearMappingPossible = false;
  3340. break;
  3341. }
  3342. APInt Val = ConstVal->getValue();
  3343. if (I != 0) {
  3344. APInt Dist = Val - PrevVal;
  3345. if (I == 1) {
  3346. DistToPrev = Dist;
  3347. } else if (Dist != DistToPrev) {
  3348. LinearMappingPossible = false;
  3349. break;
  3350. }
  3351. }
  3352. PrevVal = Val;
  3353. }
  3354. if (LinearMappingPossible) {
  3355. LinearOffset = cast<ConstantInt>(TableContents[0]);
  3356. LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
  3357. Kind = LinearMapKind;
  3358. ++NumLinearMaps;
  3359. return;
  3360. }
  3361. }
  3362. // If the type is integer and the table fits in a register, build a bitmap.
  3363. if (WouldFitInRegister(DL, TableSize, ValueType)) {
  3364. IntegerType *IT = cast<IntegerType>(ValueType);
  3365. APInt TableInt(TableSize * IT->getBitWidth(), 0);
  3366. for (uint64_t I = TableSize; I > 0; --I) {
  3367. TableInt <<= IT->getBitWidth();
  3368. // Insert values into the bitmap. Undef values are set to zero.
  3369. if (!isa<UndefValue>(TableContents[I - 1])) {
  3370. ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
  3371. TableInt |= Val->getValue().zext(TableInt.getBitWidth());
  3372. }
  3373. }
  3374. BitMap = ConstantInt::get(M.getContext(), TableInt);
  3375. BitMapElementTy = IT;
  3376. Kind = BitMapKind;
  3377. ++NumBitMaps;
  3378. return;
  3379. }
  3380. // Store the table in an array.
  3381. ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
  3382. Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
  3383. Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
  3384. GlobalVariable::PrivateLinkage,
  3385. Initializer,
  3386. "switch.table");
  3387. Array->setUnnamedAddr(true);
  3388. Kind = ArrayKind;
  3389. }
  3390. Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
  3391. switch (Kind) {
  3392. case SingleValueKind:
  3393. return SingleValue;
  3394. case LinearMapKind: {
  3395. // Derive the result value from the input value.
  3396. Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
  3397. false, "switch.idx.cast");
  3398. if (!LinearMultiplier->isOne())
  3399. Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
  3400. if (!LinearOffset->isZero())
  3401. Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
  3402. return Result;
  3403. }
  3404. case BitMapKind: {
  3405. // Type of the bitmap (e.g. i59).
  3406. IntegerType *MapTy = BitMap->getType();
  3407. // Cast Index to the same type as the bitmap.
  3408. // Note: The Index is <= the number of elements in the table, so
  3409. // truncating it to the width of the bitmask is safe.
  3410. Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
  3411. // Multiply the shift amount by the element width.
  3412. ShiftAmt = Builder.CreateMul(ShiftAmt,
  3413. ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
  3414. "switch.shiftamt");
  3415. // Shift down.
  3416. Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
  3417. "switch.downshift");
  3418. // Mask off.
  3419. return Builder.CreateTrunc(DownShifted, BitMapElementTy,
  3420. "switch.masked");
  3421. }
  3422. case ArrayKind: {
  3423. // Make sure the table index will not overflow when treated as signed.
  3424. IntegerType *IT = cast<IntegerType>(Index->getType());
  3425. uint64_t TableSize = Array->getInitializer()->getType()
  3426. ->getArrayNumElements();
  3427. if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
  3428. Index = Builder.CreateZExt(Index,
  3429. IntegerType::get(IT->getContext(),
  3430. IT->getBitWidth() + 1),
  3431. "switch.tableidx.zext");
  3432. Value *GEPIndices[] = { Builder.getInt32(0), Index };
  3433. Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
  3434. "switch.gep");
  3435. return Builder.CreateLoad(GEP, "switch.load");
  3436. }
  3437. }
  3438. llvm_unreachable("Unknown lookup table kind!");
  3439. }
  3440. bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
  3441. uint64_t TableSize,
  3442. const Type *ElementType) {
  3443. if (!DL)
  3444. return false;
  3445. const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
  3446. if (!IT)
  3447. return false;
  3448. // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
  3449. // are <= 15, we could try to narrow the type.
  3450. // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
  3451. if (TableSize >= UINT_MAX/IT->getBitWidth())
  3452. return false;
  3453. return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
  3454. }
  3455. /// ShouldBuildLookupTable - Determine whether a lookup table should be built
  3456. /// for this switch, based on the number of cases, size of the table and the
  3457. /// types of the results.
  3458. static bool ShouldBuildLookupTable(SwitchInst *SI,
  3459. uint64_t TableSize,
  3460. const TargetTransformInfo &TTI,
  3461. const DataLayout *DL,
  3462. const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
  3463. if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
  3464. return false; // TableSize overflowed, or mul below might overflow.
  3465. bool AllTablesFitInRegister = true;
  3466. bool HasIllegalType = false;
  3467. for (const auto &I : ResultTypes) {
  3468. Type *Ty = I.second;
  3469. // Saturate this flag to true.
  3470. HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
  3471. // Saturate this flag to false.
  3472. AllTablesFitInRegister = AllTablesFitInRegister &&
  3473. SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
  3474. // If both flags saturate, we're done. NOTE: This *only* works with
  3475. // saturating flags, and all flags have to saturate first due to the
  3476. // non-deterministic behavior of iterating over a dense map.
  3477. if (HasIllegalType && !AllTablesFitInRegister)
  3478. break;
  3479. }
  3480. // If each table would fit in a register, we should build it anyway.
  3481. if (AllTablesFitInRegister)
  3482. return true;
  3483. // Don't build a table that doesn't fit in-register if it has illegal types.
  3484. if (HasIllegalType)
  3485. return false;
  3486. // The table density should be at least 40%. This is the same criterion as for
  3487. // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
  3488. // FIXME: Find the best cut-off.
  3489. return SI->getNumCases() * 10 >= TableSize * 4;
  3490. }
  3491. /// Try to reuse the switch table index compare. Following pattern:
  3492. /// \code
  3493. /// if (idx < tablesize)
  3494. /// r = table[idx]; // table does not contain default_value
  3495. /// else
  3496. /// r = default_value;
  3497. /// if (r != default_value)
  3498. /// ...
  3499. /// \endcode
  3500. /// Is optimized to:
  3501. /// \code
  3502. /// cond = idx < tablesize;
  3503. /// if (cond)
  3504. /// r = table[idx];
  3505. /// else
  3506. /// r = default_value;
  3507. /// if (cond)
  3508. /// ...
  3509. /// \endcode
  3510. /// Jump threading will then eliminate the second if(cond).
  3511. static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
  3512. BranchInst *RangeCheckBranch, Constant *DefaultValue,
  3513. const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
  3514. ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
  3515. if (!CmpInst)
  3516. return;
  3517. // We require that the compare is in the same block as the phi so that jump
  3518. // threading can do its work afterwards.
  3519. if (CmpInst->getParent() != PhiBlock)
  3520. return;
  3521. Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
  3522. if (!CmpOp1)
  3523. return;
  3524. Value *RangeCmp = RangeCheckBranch->getCondition();
  3525. Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
  3526. Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
  3527. // Check if the compare with the default value is constant true or false.
  3528. Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  3529. DefaultValue, CmpOp1, true);
  3530. if (DefaultConst != TrueConst && DefaultConst != FalseConst)
  3531. return;
  3532. // Check if the compare with the case values is distinct from the default
  3533. // compare result.
  3534. for (auto ValuePair : Values) {
  3535. Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  3536. ValuePair.second, CmpOp1, true);
  3537. if (!CaseConst || CaseConst == DefaultConst)
  3538. return;
  3539. assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
  3540. "Expect true or false as compare result.");
  3541. }
  3542. // Check if the branch instruction dominates the phi node. It's a simple
  3543. // dominance check, but sufficient for our needs.
  3544. // Although this check is invariant in the calling loops, it's better to do it
  3545. // at this late stage. Practically we do it at most once for a switch.
  3546. BasicBlock *BranchBlock = RangeCheckBranch->getParent();
  3547. for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
  3548. BasicBlock *Pred = *PI;
  3549. if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
  3550. return;
  3551. }
  3552. if (DefaultConst == FalseConst) {
  3553. // The compare yields the same result. We can replace it.
  3554. CmpInst->replaceAllUsesWith(RangeCmp);
  3555. ++NumTableCmpReuses;
  3556. } else {
  3557. // The compare yields the same result, just inverted. We can replace it.
  3558. Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
  3559. ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
  3560. RangeCheckBranch);
  3561. CmpInst->replaceAllUsesWith(InvertedTableCmp);
  3562. ++NumTableCmpReuses;
  3563. }
  3564. }
  3565. /// SwitchToLookupTable - If the switch is only used to initialize one or more
  3566. /// phi nodes in a common successor block with different constant values,
  3567. /// replace the switch with lookup tables.
  3568. static bool SwitchToLookupTable(SwitchInst *SI,
  3569. IRBuilder<> &Builder,
  3570. const TargetTransformInfo &TTI,
  3571. const DataLayout* DL) {
  3572. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  3573. // Only build lookup table when we have a target that supports it.
  3574. if (!TTI.shouldBuildLookupTables())
  3575. return false;
  3576. // FIXME: If the switch is too sparse for a lookup table, perhaps we could
  3577. // split off a dense part and build a lookup table for that.
  3578. // FIXME: This creates arrays of GEPs to constant strings, which means each
  3579. // GEP needs a runtime relocation in PIC code. We should just build one big
  3580. // string and lookup indices into that.
  3581. // Ignore switches with less than three cases. Lookup tables will not make them
  3582. // faster, so we don't analyze them.
  3583. if (SI->getNumCases() < 3)
  3584. return false;
  3585. // Figure out the corresponding result for each case value and phi node in the
  3586. // common destination, as well as the the min and max case values.
  3587. assert(SI->case_begin() != SI->case_end());
  3588. SwitchInst::CaseIt CI = SI->case_begin();
  3589. ConstantInt *MinCaseVal = CI.getCaseValue();
  3590. ConstantInt *MaxCaseVal = CI.getCaseValue();
  3591. BasicBlock *CommonDest = nullptr;
  3592. typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
  3593. SmallDenseMap<PHINode*, ResultListTy> ResultLists;
  3594. SmallDenseMap<PHINode*, Constant*> DefaultResults;
  3595. SmallDenseMap<PHINode*, Type*> ResultTypes;
  3596. SmallVector<PHINode*, 4> PHIs;
  3597. for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
  3598. ConstantInt *CaseVal = CI.getCaseValue();
  3599. if (CaseVal->getValue().slt(MinCaseVal->getValue()))
  3600. MinCaseVal = CaseVal;
  3601. if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
  3602. MaxCaseVal = CaseVal;
  3603. // Resulting value at phi nodes for this case value.
  3604. typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
  3605. ResultsTy Results;
  3606. if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
  3607. Results, DL))
  3608. return false;
  3609. // Append the result from this case to the list for each phi.
  3610. for (const auto &I : Results) {
  3611. PHINode *PHI = I.first;
  3612. Constant *Value = I.second;
  3613. if (!ResultLists.count(PHI))
  3614. PHIs.push_back(PHI);
  3615. ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
  3616. }
  3617. }
  3618. // Keep track of the result types.
  3619. for (PHINode *PHI : PHIs) {
  3620. ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
  3621. }
  3622. uint64_t NumResults = ResultLists[PHIs[0]].size();
  3623. APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
  3624. uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
  3625. bool TableHasHoles = (NumResults < TableSize);
  3626. // If the table has holes, we need a constant result for the default case
  3627. // or a bitmask that fits in a register.
  3628. SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
  3629. bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
  3630. &CommonDest, DefaultResultsList, DL);
  3631. bool NeedMask = (TableHasHoles && !HasDefaultResults);
  3632. if (NeedMask) {
  3633. // As an extra penalty for the validity test we require more cases.
  3634. if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
  3635. return false;
  3636. if (!(DL && DL->fitsInLegalInteger(TableSize)))
  3637. return false;
  3638. }
  3639. for (const auto &I : DefaultResultsList) {
  3640. PHINode *PHI = I.first;
  3641. Constant *Result = I.second;
  3642. DefaultResults[PHI] = Result;
  3643. }
  3644. if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
  3645. return false;
  3646. // Create the BB that does the lookups.
  3647. Module &Mod = *CommonDest->getParent()->getParent();
  3648. BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
  3649. "switch.lookup",
  3650. CommonDest->getParent(),
  3651. CommonDest);
  3652. // Compute the table index value.
  3653. Builder.SetInsertPoint(SI);
  3654. Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
  3655. "switch.tableidx");
  3656. // Compute the maximum table size representable by the integer type we are
  3657. // switching upon.
  3658. unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
  3659. uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
  3660. assert(MaxTableSize >= TableSize &&
  3661. "It is impossible for a switch to have more entries than the max "
  3662. "representable value of its input integer type's size.");
  3663. // If we have a fully covered lookup table, unconditionally branch to the
  3664. // lookup table BB. Otherwise, check if the condition value is within the case
  3665. // range. If it is so, branch to the new BB. Otherwise branch to SI's default
  3666. // destination.
  3667. BranchInst *RangeCheckBranch = nullptr;
  3668. const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
  3669. if (GeneratingCoveredLookupTable) {
  3670. Builder.CreateBr(LookupBB);
  3671. // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
  3672. // do not delete PHINodes here.
  3673. SI->getDefaultDest()->removePredecessor(SI->getParent(),
  3674. true/*DontDeleteUselessPHIs*/);
  3675. } else {
  3676. Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
  3677. MinCaseVal->getType(), TableSize));
  3678. RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
  3679. }
  3680. // Populate the BB that does the lookups.
  3681. Builder.SetInsertPoint(LookupBB);
  3682. if (NeedMask) {
  3683. // Before doing the lookup we do the hole check.
  3684. // The LookupBB is therefore re-purposed to do the hole check
  3685. // and we create a new LookupBB.
  3686. BasicBlock *MaskBB = LookupBB;
  3687. MaskBB->setName("switch.hole_check");
  3688. LookupBB = BasicBlock::Create(Mod.getContext(),
  3689. "switch.lookup",
  3690. CommonDest->getParent(),
  3691. CommonDest);
  3692. // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
  3693. // unnecessary illegal types.
  3694. uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
  3695. APInt MaskInt(TableSizePowOf2, 0);
  3696. APInt One(TableSizePowOf2, 1);
  3697. // Build bitmask; fill in a 1 bit for every case.
  3698. const ResultListTy &ResultList = ResultLists[PHIs[0]];
  3699. for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
  3700. uint64_t Idx = (ResultList[I].first->getValue() -
  3701. MinCaseVal->getValue()).getLimitedValue();
  3702. MaskInt |= One << Idx;
  3703. }
  3704. ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
  3705. // Get the TableIndex'th bit of the bitmask.
  3706. // If this bit is 0 (meaning hole) jump to the default destination,
  3707. // else continue with table lookup.
  3708. IntegerType *MapTy = TableMask->getType();
  3709. Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
  3710. "switch.maskindex");
  3711. Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
  3712. "switch.shifted");
  3713. Value *LoBit = Builder.CreateTrunc(Shifted,
  3714. Type::getInt1Ty(Mod.getContext()),
  3715. "switch.lobit");
  3716. Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
  3717. Builder.SetInsertPoint(LookupBB);
  3718. AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
  3719. }
  3720. bool ReturnedEarly = false;
  3721. for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
  3722. PHINode *PHI = PHIs[I];
  3723. const ResultListTy &ResultList = ResultLists[PHI];
  3724. // If using a bitmask, use any value to fill the lookup table holes.
  3725. Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
  3726. SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
  3727. Value *Result = Table.BuildLookup(TableIndex, Builder);
  3728. // If the result is used to return immediately from the function, we want to
  3729. // do that right here.
  3730. if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
  3731. PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
  3732. Builder.CreateRet(Result);
  3733. ReturnedEarly = true;
  3734. break;
  3735. }
  3736. // Do a small peephole optimization: re-use the switch table compare if
  3737. // possible.
  3738. if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
  3739. BasicBlock *PhiBlock = PHI->getParent();
  3740. // Search for compare instructions which use the phi.
  3741. for (auto *User : PHI->users()) {
  3742. reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
  3743. }
  3744. }
  3745. PHI->addIncoming(Result, LookupBB);
  3746. }
  3747. if (!ReturnedEarly)
  3748. Builder.CreateBr(CommonDest);
  3749. // Remove the switch.
  3750. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  3751. BasicBlock *Succ = SI->getSuccessor(i);
  3752. if (Succ == SI->getDefaultDest())
  3753. continue;
  3754. Succ->removePredecessor(SI->getParent());
  3755. }
  3756. SI->eraseFromParent();
  3757. ++NumLookupTables;
  3758. if (NeedMask)
  3759. ++NumLookupTablesHoles;
  3760. return true;
  3761. }
  3762. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  3763. BasicBlock *BB = SI->getParent();
  3764. if (isValueEqualityComparison(SI)) {
  3765. // If we only have one predecessor, and if it is a branch on this value,
  3766. // see if that predecessor totally determines the outcome of this switch.
  3767. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  3768. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  3769. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3770. Value *Cond = SI->getCondition();
  3771. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  3772. if (SimplifySwitchOnSelect(SI, Select))
  3773. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3774. // If the block only contains the switch, see if we can fold the block
  3775. // away into any preds.
  3776. BasicBlock::iterator BBI = BB->begin();
  3777. // Ignore dbg intrinsics.
  3778. while (isa<DbgInfoIntrinsic>(BBI))
  3779. ++BBI;
  3780. if (SI == &*BBI)
  3781. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  3782. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3783. }
  3784. // Try to transform the switch into an icmp and a branch.
  3785. if (TurnSwitchRangeIntoICmp(SI, Builder))
  3786. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3787. // Remove unreachable cases.
  3788. if (EliminateDeadSwitchCases(SI, DL, AT))
  3789. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3790. if (SwitchToSelect(SI, Builder, DL, AT))
  3791. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3792. if (ForwardSwitchConditionToPHI(SI))
  3793. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3794. if (SwitchToLookupTable(SI, Builder, TTI, DL))
  3795. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3796. return false;
  3797. }
  3798. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  3799. BasicBlock *BB = IBI->getParent();
  3800. bool Changed = false;
  3801. // Eliminate redundant destinations.
  3802. SmallPtrSet<Value *, 8> Succs;
  3803. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  3804. BasicBlock *Dest = IBI->getDestination(i);
  3805. if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
  3806. Dest->removePredecessor(BB);
  3807. IBI->removeDestination(i);
  3808. --i; --e;
  3809. Changed = true;
  3810. }
  3811. }
  3812. if (IBI->getNumDestinations() == 0) {
  3813. // If the indirectbr has no successors, change it to unreachable.
  3814. new UnreachableInst(IBI->getContext(), IBI);
  3815. EraseTerminatorInstAndDCECond(IBI);
  3816. return true;
  3817. }
  3818. if (IBI->getNumDestinations() == 1) {
  3819. // If the indirectbr has one successor, change it to a direct branch.
  3820. BranchInst::Create(IBI->getDestination(0), IBI);
  3821. EraseTerminatorInstAndDCECond(IBI);
  3822. return true;
  3823. }
  3824. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  3825. if (SimplifyIndirectBrOnSelect(IBI, SI))
  3826. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3827. }
  3828. return Changed;
  3829. }
  3830. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
  3831. BasicBlock *BB = BI->getParent();
  3832. if (SinkCommon && SinkThenElseCodeToEnd(BI))
  3833. return true;
  3834. // If the Terminator is the only non-phi instruction, simplify the block.
  3835. BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
  3836. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  3837. TryToSimplifyUncondBranchFromEmptyBlock(BB))
  3838. return true;
  3839. // If the only instruction in the block is a seteq/setne comparison
  3840. // against a constant, try to simplify the block.
  3841. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  3842. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  3843. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  3844. ;
  3845. if (I->isTerminator() &&
  3846. TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
  3847. BonusInstThreshold, DL, AT))
  3848. return true;
  3849. }
  3850. // If this basic block is ONLY a compare and a branch, and if a predecessor
  3851. // branches to us and our successor, fold the comparison into the
  3852. // predecessor and use logical operations to update the incoming value
  3853. // for PHI nodes in common successor.
  3854. if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
  3855. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3856. return false;
  3857. }
  3858. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  3859. BasicBlock *BB = BI->getParent();
  3860. // Conditional branch
  3861. if (isValueEqualityComparison(BI)) {
  3862. // If we only have one predecessor, and if it is a branch on this value,
  3863. // see if that predecessor totally determines the outcome of this
  3864. // switch.
  3865. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  3866. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  3867. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3868. // This block must be empty, except for the setcond inst, if it exists.
  3869. // Ignore dbg intrinsics.
  3870. BasicBlock::iterator I = BB->begin();
  3871. // Ignore dbg intrinsics.
  3872. while (isa<DbgInfoIntrinsic>(I))
  3873. ++I;
  3874. if (&*I == BI) {
  3875. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  3876. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3877. } else if (&*I == cast<Instruction>(BI->getCondition())){
  3878. ++I;
  3879. // Ignore dbg intrinsics.
  3880. while (isa<DbgInfoIntrinsic>(I))
  3881. ++I;
  3882. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  3883. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3884. }
  3885. }
  3886. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  3887. if (SimplifyBranchOnICmpChain(BI, DL, Builder))
  3888. return true;
  3889. // If this basic block is ONLY a compare and a branch, and if a predecessor
  3890. // branches to us and one of our successors, fold the comparison into the
  3891. // predecessor and use logical operations to pick the right destination.
  3892. if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
  3893. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3894. // We have a conditional branch to two blocks that are only reachable
  3895. // from BI. We know that the condbr dominates the two blocks, so see if
  3896. // there is any identical code in the "then" and "else" blocks. If so, we
  3897. // can hoist it up to the branching block.
  3898. if (BI->getSuccessor(0)->getSinglePredecessor()) {
  3899. if (BI->getSuccessor(1)->getSinglePredecessor()) {
  3900. if (HoistThenElseCodeToIf(BI, DL))
  3901. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3902. } else {
  3903. // If Successor #1 has multiple preds, we may be able to conditionally
  3904. // execute Successor #0 if it branches to Successor #1.
  3905. TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
  3906. if (Succ0TI->getNumSuccessors() == 1 &&
  3907. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  3908. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
  3909. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3910. }
  3911. } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
  3912. // If Successor #0 has multiple preds, we may be able to conditionally
  3913. // execute Successor #1 if it branches to Successor #0.
  3914. TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
  3915. if (Succ1TI->getNumSuccessors() == 1 &&
  3916. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  3917. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
  3918. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3919. }
  3920. // If this is a branch on a phi node in the current block, thread control
  3921. // through this block if any PHI node entries are constants.
  3922. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  3923. if (PN->getParent() == BI->getParent())
  3924. if (FoldCondBranchOnPHI(BI, DL))
  3925. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3926. // Scan predecessor blocks for conditional branches.
  3927. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  3928. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  3929. if (PBI != BI && PBI->isConditional())
  3930. if (SimplifyCondBranchToCondBranch(PBI, BI))
  3931. return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
  3932. return false;
  3933. }
  3934. /// Check if passing a value to an instruction will cause undefined behavior.
  3935. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  3936. Constant *C = dyn_cast<Constant>(V);
  3937. if (!C)
  3938. return false;
  3939. if (I->use_empty())
  3940. return false;
  3941. if (C->isNullValue()) {
  3942. // Only look at the first use, avoid hurting compile time with long uselists
  3943. User *Use = *I->user_begin();
  3944. // Now make sure that there are no instructions in between that can alter
  3945. // control flow (eg. calls)
  3946. for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
  3947. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  3948. return false;
  3949. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  3950. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  3951. if (GEP->getPointerOperand() == I)
  3952. return passingValueIsAlwaysUndefined(V, GEP);
  3953. // Look through bitcasts.
  3954. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  3955. return passingValueIsAlwaysUndefined(V, BC);
  3956. // Load from null is undefined.
  3957. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  3958. if (!LI->isVolatile())
  3959. return LI->getPointerAddressSpace() == 0;
  3960. // Store to null is undefined.
  3961. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  3962. if (!SI->isVolatile())
  3963. return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
  3964. }
  3965. return false;
  3966. }
  3967. /// If BB has an incoming value that will always trigger undefined behavior
  3968. /// (eg. null pointer dereference), remove the branch leading here.
  3969. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  3970. for (BasicBlock::iterator i = BB->begin();
  3971. PHINode *PHI = dyn_cast<PHINode>(i); ++i)
  3972. for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
  3973. if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
  3974. TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
  3975. IRBuilder<> Builder(T);
  3976. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  3977. BB->removePredecessor(PHI->getIncomingBlock(i));
  3978. // Turn uncoditional branches into unreachables and remove the dead
  3979. // destination from conditional branches.
  3980. if (BI->isUnconditional())
  3981. Builder.CreateUnreachable();
  3982. else
  3983. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
  3984. BI->getSuccessor(0));
  3985. BI->eraseFromParent();
  3986. return true;
  3987. }
  3988. // TODO: SwitchInst.
  3989. }
  3990. return false;
  3991. }
  3992. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  3993. bool Changed = false;
  3994. assert(BB && BB->getParent() && "Block not embedded in function!");
  3995. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  3996. // Remove basic blocks that have no predecessors (except the entry block)...
  3997. // or that just have themself as a predecessor. These are unreachable.
  3998. if ((pred_begin(BB) == pred_end(BB) &&
  3999. BB != &BB->getParent()->getEntryBlock()) ||
  4000. BB->getSinglePredecessor() == BB) {
  4001. DEBUG(dbgs() << "Removing BB: \n" << *BB);
  4002. DeleteDeadBlock(BB);
  4003. return true;
  4004. }
  4005. // Check to see if we can constant propagate this terminator instruction
  4006. // away...
  4007. Changed |= ConstantFoldTerminator(BB, true);
  4008. // Check for and eliminate duplicate PHI nodes in this block.
  4009. Changed |= EliminateDuplicatePHINodes(BB);
  4010. // Check for and remove branches that will always cause undefined behavior.
  4011. Changed |= removeUndefIntroducingPredecessor(BB);
  4012. // Merge basic blocks into their predecessor if there is only one distinct
  4013. // pred, and if there is only one distinct successor of the predecessor, and
  4014. // if there are no PHI nodes.
  4015. //
  4016. if (MergeBlockIntoPredecessor(BB))
  4017. return true;
  4018. IRBuilder<> Builder(BB);
  4019. // If there is a trivial two-entry PHI node in this basic block, and we can
  4020. // eliminate it, do so now.
  4021. if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
  4022. if (PN->getNumIncomingValues() == 2)
  4023. Changed |= FoldTwoEntryPHINode(PN, DL);
  4024. Builder.SetInsertPoint(BB->getTerminator());
  4025. if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  4026. if (BI->isUnconditional()) {
  4027. if (SimplifyUncondBranch(BI, Builder)) return true;
  4028. } else {
  4029. if (SimplifyCondBranch(BI, Builder)) return true;
  4030. }
  4031. } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  4032. if (SimplifyReturn(RI, Builder)) return true;
  4033. } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  4034. if (SimplifyResume(RI, Builder)) return true;
  4035. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  4036. if (SimplifySwitch(SI, Builder)) return true;
  4037. } else if (UnreachableInst *UI =
  4038. dyn_cast<UnreachableInst>(BB->getTerminator())) {
  4039. if (SimplifyUnreachable(UI)) return true;
  4040. } else if (IndirectBrInst *IBI =
  4041. dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  4042. if (SimplifyIndirectBr(IBI)) return true;
  4043. }
  4044. return Changed;
  4045. }
  4046. /// SimplifyCFG - This function is used to do simplification of a CFG. For
  4047. /// example, it adjusts branches to branches to eliminate the extra hop, it
  4048. /// eliminates unreachable basic blocks, and does other "peephole" optimization
  4049. /// of the CFG. It returns true if a modification was made.
  4050. ///
  4051. bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  4052. unsigned BonusInstThreshold,
  4053. const DataLayout *DL, AssumptionTracker *AT) {
  4054. return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);
  4055. }