SimplifyCFG.cpp 182 KB

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