SimplifyCFG.cpp 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983
  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. #define DEBUG_TYPE "simplifycfg"
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/GlobalVariable.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/IntrinsicInst.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/Metadata.h"
  22. #include "llvm/Operator.h"
  23. #include "llvm/Type.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/SetVector.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/Support/CFG.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/ConstantRange.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/IRBuilder.h"
  39. #include "llvm/Support/NoFolder.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <algorithm>
  42. #include <set>
  43. #include <map>
  44. using namespace llvm;
  45. static cl::opt<unsigned>
  46. PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
  47. cl::desc("Control the amount of phi node folding to perform (default = 1)"));
  48. static cl::opt<bool>
  49. DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  50. cl::desc("Duplicate return instructions into unconditional branches"));
  51. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  52. namespace {
  53. class SimplifyCFGOpt {
  54. const TargetData *const TD;
  55. Value *isValueEqualityComparison(TerminatorInst *TI);
  56. BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
  57. std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
  58. bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  59. BasicBlock *Pred,
  60. IRBuilder<> &Builder);
  61. bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  62. IRBuilder<> &Builder);
  63. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  64. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  65. bool SimplifyUnreachable(UnreachableInst *UI);
  66. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  67. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  68. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
  69. bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
  70. public:
  71. explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
  72. bool run(BasicBlock *BB);
  73. };
  74. }
  75. /// SafeToMergeTerminators - Return true if it is safe to merge these two
  76. /// terminator instructions together.
  77. ///
  78. static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
  79. if (SI1 == SI2) return false; // Can't merge with self!
  80. // It is not safe to merge these two switch instructions if they have a common
  81. // successor, and if that successor has a PHI node, and if *that* PHI node has
  82. // conflicting incoming values from the two switch blocks.
  83. BasicBlock *SI1BB = SI1->getParent();
  84. BasicBlock *SI2BB = SI2->getParent();
  85. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  86. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  87. if (SI1Succs.count(*I))
  88. for (BasicBlock::iterator BBI = (*I)->begin();
  89. isa<PHINode>(BBI); ++BBI) {
  90. PHINode *PN = cast<PHINode>(BBI);
  91. if (PN->getIncomingValueForBlock(SI1BB) !=
  92. PN->getIncomingValueForBlock(SI2BB))
  93. return false;
  94. }
  95. return true;
  96. }
  97. /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
  98. /// now be entries in it from the 'NewPred' block. The values that will be
  99. /// flowing into the PHI nodes will be the same as those coming in from
  100. /// ExistPred, an existing predecessor of Succ.
  101. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  102. BasicBlock *ExistPred) {
  103. if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
  104. PHINode *PN;
  105. for (BasicBlock::iterator I = Succ->begin();
  106. (PN = dyn_cast<PHINode>(I)); ++I)
  107. PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
  108. }
  109. /// GetIfCondition - Given a basic block (BB) with two predecessors (and at
  110. /// least one PHI node in it), check to see if the merge at this block is due
  111. /// to an "if condition". If so, return the boolean condition that determines
  112. /// which entry into BB will be taken. Also, return by references the block
  113. /// that will be entered from if the condition is true, and the block that will
  114. /// be entered if the condition is false.
  115. ///
  116. /// This does no checking to see if the true/false blocks have large or unsavory
  117. /// instructions in them.
  118. static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  119. BasicBlock *&IfFalse) {
  120. PHINode *SomePHI = cast<PHINode>(BB->begin());
  121. assert(SomePHI->getNumIncomingValues() == 2 &&
  122. "Function can only handle blocks with 2 predecessors!");
  123. BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
  124. BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
  125. // We can only handle branches. Other control flow will be lowered to
  126. // branches if possible anyway.
  127. BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
  128. BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
  129. if (Pred1Br == 0 || Pred2Br == 0)
  130. return 0;
  131. // Eliminate code duplication by ensuring that Pred1Br is conditional if
  132. // either are.
  133. if (Pred2Br->isConditional()) {
  134. // If both branches are conditional, we don't have an "if statement". In
  135. // reality, we could transform this case, but since the condition will be
  136. // required anyway, we stand no chance of eliminating it, so the xform is
  137. // probably not profitable.
  138. if (Pred1Br->isConditional())
  139. return 0;
  140. std::swap(Pred1, Pred2);
  141. std::swap(Pred1Br, Pred2Br);
  142. }
  143. if (Pred1Br->isConditional()) {
  144. // The only thing we have to watch out for here is to make sure that Pred2
  145. // doesn't have incoming edges from other blocks. If it does, the condition
  146. // doesn't dominate BB.
  147. if (Pred2->getSinglePredecessor() == 0)
  148. return 0;
  149. // If we found a conditional branch predecessor, make sure that it branches
  150. // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
  151. if (Pred1Br->getSuccessor(0) == BB &&
  152. Pred1Br->getSuccessor(1) == Pred2) {
  153. IfTrue = Pred1;
  154. IfFalse = Pred2;
  155. } else if (Pred1Br->getSuccessor(0) == Pred2 &&
  156. Pred1Br->getSuccessor(1) == BB) {
  157. IfTrue = Pred2;
  158. IfFalse = Pred1;
  159. } else {
  160. // We know that one arm of the conditional goes to BB, so the other must
  161. // go somewhere unrelated, and this must not be an "if statement".
  162. return 0;
  163. }
  164. return Pred1Br->getCondition();
  165. }
  166. // Ok, if we got here, both predecessors end with an unconditional branch to
  167. // BB. Don't panic! If both blocks only have a single (identical)
  168. // predecessor, and THAT is a conditional branch, then we're all ok!
  169. BasicBlock *CommonPred = Pred1->getSinglePredecessor();
  170. if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
  171. return 0;
  172. // Otherwise, if this is a conditional branch, then we can use it!
  173. BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
  174. if (BI == 0) return 0;
  175. assert(BI->isConditional() && "Two successors but not conditional?");
  176. if (BI->getSuccessor(0) == Pred1) {
  177. IfTrue = Pred1;
  178. IfFalse = Pred2;
  179. } else {
  180. IfTrue = Pred2;
  181. IfFalse = Pred1;
  182. }
  183. return BI->getCondition();
  184. }
  185. /// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
  186. /// given instruction, which is assumed to be safe to speculate. 1 means
  187. /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
  188. static unsigned ComputeSpeculationCost(const User *I) {
  189. assert(isSafeToSpeculativelyExecute(I) &&
  190. "Instruction is not safe to speculatively execute!");
  191. switch (Operator::getOpcode(I)) {
  192. default:
  193. // In doubt, be conservative.
  194. return UINT_MAX;
  195. case Instruction::GetElementPtr:
  196. // GEPs are cheap if all indices are constant.
  197. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  198. return UINT_MAX;
  199. return 1;
  200. case Instruction::Load:
  201. case Instruction::Add:
  202. case Instruction::Sub:
  203. case Instruction::And:
  204. case Instruction::Or:
  205. case Instruction::Xor:
  206. case Instruction::Shl:
  207. case Instruction::LShr:
  208. case Instruction::AShr:
  209. case Instruction::ICmp:
  210. case Instruction::Trunc:
  211. case Instruction::ZExt:
  212. case Instruction::SExt:
  213. return 1; // These are all cheap.
  214. case Instruction::Call:
  215. case Instruction::Select:
  216. return 2;
  217. }
  218. }
  219. /// DominatesMergePoint - If we have a merge point of an "if condition" as
  220. /// accepted above, return true if the specified value dominates the block. We
  221. /// don't handle the true generality of domination here, just a special case
  222. /// which works well enough for us.
  223. ///
  224. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  225. /// see if V (which must be an instruction) and its recursive operands
  226. /// that do not dominate BB have a combined cost lower than CostRemaining and
  227. /// are non-trapping. If both are true, the instruction is inserted into the
  228. /// set and true is returned.
  229. ///
  230. /// The cost for most non-trapping instructions is defined as 1 except for
  231. /// Select whose cost is 2.
  232. ///
  233. /// After this function returns, CostRemaining is decreased by the cost of
  234. /// V plus its non-dominating operands. If that cost is greater than
  235. /// CostRemaining, false is returned and CostRemaining is undefined.
  236. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  237. SmallPtrSet<Instruction*, 4> *AggressiveInsts,
  238. unsigned &CostRemaining) {
  239. Instruction *I = dyn_cast<Instruction>(V);
  240. if (!I) {
  241. // Non-instructions all dominate instructions, but not all constantexprs
  242. // can be executed unconditionally.
  243. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  244. if (C->canTrap())
  245. return false;
  246. return true;
  247. }
  248. BasicBlock *PBB = I->getParent();
  249. // We don't want to allow weird loops that might have the "if condition" in
  250. // the bottom of this block.
  251. if (PBB == BB) return false;
  252. // If this instruction is defined in a block that contains an unconditional
  253. // branch to BB, then it must be in the 'conditional' part of the "if
  254. // statement". If not, it definitely dominates the region.
  255. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  256. if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
  257. return true;
  258. // If we aren't allowing aggressive promotion anymore, then don't consider
  259. // instructions in the 'if region'.
  260. if (AggressiveInsts == 0) return false;
  261. // If we have seen this instruction before, don't count it again.
  262. if (AggressiveInsts->count(I)) return true;
  263. // Okay, it looks like the instruction IS in the "condition". Check to
  264. // see if it's a cheap instruction to unconditionally compute, and if it
  265. // only uses stuff defined outside of the condition. If so, hoist it out.
  266. if (!isSafeToSpeculativelyExecute(I))
  267. return false;
  268. unsigned Cost = ComputeSpeculationCost(I);
  269. if (Cost > CostRemaining)
  270. return false;
  271. CostRemaining -= Cost;
  272. // Okay, we can only really hoist these out if their operands do
  273. // not take us over the cost threshold.
  274. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  275. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
  276. return false;
  277. // Okay, it's safe to do this! Remember this instruction.
  278. AggressiveInsts->insert(I);
  279. return true;
  280. }
  281. /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
  282. /// and PointerNullValue. Return NULL if value is not a constant int.
  283. static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
  284. // Normal constant int.
  285. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  286. if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
  287. return CI;
  288. // This is some kind of pointer constant. Turn it into a pointer-sized
  289. // ConstantInt if possible.
  290. IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
  291. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  292. if (isa<ConstantPointerNull>(V))
  293. return ConstantInt::get(PtrTy, 0);
  294. // IntToPtr const int.
  295. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  296. if (CE->getOpcode() == Instruction::IntToPtr)
  297. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  298. // The constant is very likely to have the right type already.
  299. if (CI->getType() == PtrTy)
  300. return CI;
  301. else
  302. return cast<ConstantInt>
  303. (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  304. }
  305. return 0;
  306. }
  307. /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
  308. /// collection of icmp eq/ne instructions that compare a value against a
  309. /// constant, return the value being compared, and stick the constant into the
  310. /// Values vector.
  311. static Value *
  312. GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
  313. const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
  314. Instruction *I = dyn_cast<Instruction>(V);
  315. if (I == 0) return 0;
  316. // If this is an icmp against a constant, handle this as one of the cases.
  317. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
  318. if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
  319. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
  320. UsedICmps++;
  321. Vals.push_back(C);
  322. return I->getOperand(0);
  323. }
  324. // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
  325. // the set.
  326. ConstantRange Span =
  327. ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
  328. // If this is an and/!= check then we want to optimize "x ugt 2" into
  329. // x != 0 && x != 1.
  330. if (!isEQ)
  331. Span = Span.inverse();
  332. // If there are a ton of values, we don't want to make a ginormous switch.
  333. if (Span.getSetSize().ugt(8) || Span.isEmptySet())
  334. return 0;
  335. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  336. Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
  337. UsedICmps++;
  338. return I->getOperand(0);
  339. }
  340. return 0;
  341. }
  342. // Otherwise, we can only handle an | or &, depending on isEQ.
  343. if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
  344. return 0;
  345. unsigned NumValsBeforeLHS = Vals.size();
  346. unsigned UsedICmpsBeforeLHS = UsedICmps;
  347. if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
  348. isEQ, UsedICmps)) {
  349. unsigned NumVals = Vals.size();
  350. unsigned UsedICmpsBeforeRHS = UsedICmps;
  351. if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
  352. isEQ, UsedICmps)) {
  353. if (LHS == RHS)
  354. return LHS;
  355. Vals.resize(NumVals);
  356. UsedICmps = UsedICmpsBeforeRHS;
  357. }
  358. // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
  359. // set it and return success.
  360. if (Extra == 0 || Extra == I->getOperand(1)) {
  361. Extra = I->getOperand(1);
  362. return LHS;
  363. }
  364. Vals.resize(NumValsBeforeLHS);
  365. UsedICmps = UsedICmpsBeforeLHS;
  366. return 0;
  367. }
  368. // If the LHS can't be folded in, but Extra is available and RHS can, try to
  369. // use LHS as Extra.
  370. if (Extra == 0 || Extra == I->getOperand(0)) {
  371. Value *OldExtra = Extra;
  372. Extra = I->getOperand(0);
  373. if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
  374. isEQ, UsedICmps))
  375. return RHS;
  376. assert(Vals.size() == NumValsBeforeLHS);
  377. Extra = OldExtra;
  378. }
  379. return 0;
  380. }
  381. static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
  382. Instruction *Cond = 0;
  383. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  384. Cond = dyn_cast<Instruction>(SI->getCondition());
  385. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  386. if (BI->isConditional())
  387. Cond = dyn_cast<Instruction>(BI->getCondition());
  388. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  389. Cond = dyn_cast<Instruction>(IBI->getAddress());
  390. }
  391. TI->eraseFromParent();
  392. if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
  393. }
  394. /// isValueEqualityComparison - Return true if the specified terminator checks
  395. /// to see if a value is equal to constant integer value.
  396. Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
  397. Value *CV = 0;
  398. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  399. // Do not permit merging of large switch instructions into their
  400. // predecessors unless there is only one predecessor.
  401. if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
  402. pred_end(SI->getParent())) <= 128)
  403. CV = SI->getCondition();
  404. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  405. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  406. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
  407. if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
  408. ICI->getPredicate() == ICmpInst::ICMP_NE) &&
  409. GetConstantInt(ICI->getOperand(1), TD))
  410. CV = ICI->getOperand(0);
  411. // Unwrap any lossless ptrtoint cast.
  412. if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
  413. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
  414. CV = PTII->getOperand(0);
  415. return CV;
  416. }
  417. /// GetValueEqualityComparisonCases - Given a value comparison instruction,
  418. /// decode all of the 'cases' that it represents and return the 'default' block.
  419. BasicBlock *SimplifyCFGOpt::
  420. GetValueEqualityComparisonCases(TerminatorInst *TI,
  421. std::vector<std::pair<ConstantInt*,
  422. BasicBlock*> > &Cases) {
  423. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  424. Cases.reserve(SI->getNumCases());
  425. for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
  426. Cases.push_back(std::make_pair(SI->getCaseValue(i),
  427. SI->getCaseSuccessor(i)));
  428. return SI->getDefaultDest();
  429. }
  430. BranchInst *BI = cast<BranchInst>(TI);
  431. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  432. Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
  433. BI->getSuccessor(ICI->getPredicate() ==
  434. ICmpInst::ICMP_NE)));
  435. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  436. }
  437. /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
  438. /// in the list that match the specified block.
  439. static void EliminateBlockCases(BasicBlock *BB,
  440. std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
  441. for (unsigned i = 0, e = Cases.size(); i != e; ++i)
  442. if (Cases[i].second == BB) {
  443. Cases.erase(Cases.begin()+i);
  444. --i; --e;
  445. }
  446. }
  447. /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
  448. /// well.
  449. static bool
  450. ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
  451. std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
  452. std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
  453. // Make V1 be smaller than V2.
  454. if (V1->size() > V2->size())
  455. std::swap(V1, V2);
  456. if (V1->size() == 0) return false;
  457. if (V1->size() == 1) {
  458. // Just scan V2.
  459. ConstantInt *TheVal = (*V1)[0].first;
  460. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  461. if (TheVal == (*V2)[i].first)
  462. return true;
  463. }
  464. // Otherwise, just sort both lists and compare element by element.
  465. array_pod_sort(V1->begin(), V1->end());
  466. array_pod_sort(V2->begin(), V2->end());
  467. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  468. while (i1 != e1 && i2 != e2) {
  469. if ((*V1)[i1].first == (*V2)[i2].first)
  470. return true;
  471. if ((*V1)[i1].first < (*V2)[i2].first)
  472. ++i1;
  473. else
  474. ++i2;
  475. }
  476. return false;
  477. }
  478. /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
  479. /// terminator instruction and its block is known to only have a single
  480. /// predecessor block, check to see if that predecessor is also a value
  481. /// comparison with the same value, and if that comparison determines the
  482. /// outcome of this comparison. If so, simplify TI. This does a very limited
  483. /// form of jump threading.
  484. bool SimplifyCFGOpt::
  485. SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  486. BasicBlock *Pred,
  487. IRBuilder<> &Builder) {
  488. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  489. if (!PredVal) return false; // Not a value comparison in predecessor.
  490. Value *ThisVal = isValueEqualityComparison(TI);
  491. assert(ThisVal && "This isn't a value comparison!!");
  492. if (ThisVal != PredVal) return false; // Different predicates.
  493. // Find out information about when control will move from Pred to TI's block.
  494. std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
  495. BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
  496. PredCases);
  497. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  498. // Find information about how control leaves this block.
  499. std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
  500. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  501. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  502. // If TI's block is the default block from Pred's comparison, potentially
  503. // simplify TI based on this knowledge.
  504. if (PredDef == TI->getParent()) {
  505. // If we are here, we know that the value is none of those cases listed in
  506. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  507. // can simplify TI.
  508. if (!ValuesOverlap(PredCases, ThisCases))
  509. return false;
  510. if (isa<BranchInst>(TI)) {
  511. // Okay, one of the successors of this condbr is dead. Convert it to a
  512. // uncond br.
  513. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  514. // Insert the new branch.
  515. Instruction *NI = Builder.CreateBr(ThisDef);
  516. (void) NI;
  517. // Remove PHI node entries for the dead edge.
  518. ThisCases[0].second->removePredecessor(TI->getParent());
  519. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  520. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  521. EraseTerminatorInstAndDCECond(TI);
  522. return true;
  523. }
  524. SwitchInst *SI = cast<SwitchInst>(TI);
  525. // Okay, TI has cases that are statically dead, prune them away.
  526. SmallPtrSet<Constant*, 16> DeadCases;
  527. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  528. DeadCases.insert(PredCases[i].first);
  529. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  530. << "Through successor TI: " << *TI);
  531. for (unsigned i = SI->getNumCases(); i != 0;) {
  532. --i;
  533. if (DeadCases.count(SI->getCaseValue(i))) {
  534. SI->getCaseSuccessor(i)->removePredecessor(TI->getParent());
  535. SI->removeCase(i);
  536. }
  537. }
  538. DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  539. return true;
  540. }
  541. // Otherwise, TI's block must correspond to some matched value. Find out
  542. // which value (or set of values) this is.
  543. ConstantInt *TIV = 0;
  544. BasicBlock *TIBB = TI->getParent();
  545. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  546. if (PredCases[i].second == TIBB) {
  547. if (TIV != 0)
  548. return false; // Cannot handle multiple values coming to this block.
  549. TIV = PredCases[i].first;
  550. }
  551. assert(TIV && "No edge from pred to succ?");
  552. // Okay, we found the one constant that our value can be if we get into TI's
  553. // BB. Find out which successor will unconditionally be branched to.
  554. BasicBlock *TheRealDest = 0;
  555. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  556. if (ThisCases[i].first == TIV) {
  557. TheRealDest = ThisCases[i].second;
  558. break;
  559. }
  560. // If not handled by any explicit cases, it is handled by the default case.
  561. if (TheRealDest == 0) TheRealDest = ThisDef;
  562. // Remove PHI node entries for dead edges.
  563. BasicBlock *CheckEdge = TheRealDest;
  564. for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
  565. if (*SI != CheckEdge)
  566. (*SI)->removePredecessor(TIBB);
  567. else
  568. CheckEdge = 0;
  569. // Insert the new branch.
  570. Instruction *NI = Builder.CreateBr(TheRealDest);
  571. (void) NI;
  572. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  573. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  574. EraseTerminatorInstAndDCECond(TI);
  575. return true;
  576. }
  577. namespace {
  578. /// ConstantIntOrdering - This class implements a stable ordering of constant
  579. /// integers that does not depend on their address. This is important for
  580. /// applications that sort ConstantInt's to ensure uniqueness.
  581. struct ConstantIntOrdering {
  582. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  583. return LHS->getValue().ult(RHS->getValue());
  584. }
  585. };
  586. }
  587. static int ConstantIntSortPredicate(const void *P1, const void *P2) {
  588. const ConstantInt *LHS = *(const ConstantInt**)P1;
  589. const ConstantInt *RHS = *(const ConstantInt**)P2;
  590. if (LHS->getValue().ult(RHS->getValue()))
  591. return 1;
  592. if (LHS->getValue() == RHS->getValue())
  593. return 0;
  594. return -1;
  595. }
  596. /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
  597. /// equality comparison instruction (either a switch or a branch on "X == c").
  598. /// See if any of the predecessors of the terminator block are value comparisons
  599. /// on the same value. If so, and if safe to do so, fold them together.
  600. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  601. IRBuilder<> &Builder) {
  602. BasicBlock *BB = TI->getParent();
  603. Value *CV = isValueEqualityComparison(TI); // CondVal
  604. assert(CV && "Not a comparison?");
  605. bool Changed = false;
  606. SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
  607. while (!Preds.empty()) {
  608. BasicBlock *Pred = Preds.pop_back_val();
  609. // See if the predecessor is a comparison with the same value.
  610. TerminatorInst *PTI = Pred->getTerminator();
  611. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  612. if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
  613. // Figure out which 'cases' to copy from SI to PSI.
  614. std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
  615. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  616. std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
  617. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  618. // Based on whether the default edge from PTI goes to BB or not, fill in
  619. // PredCases and PredDefault with the new switch cases we would like to
  620. // build.
  621. SmallVector<BasicBlock*, 8> NewSuccessors;
  622. if (PredDefault == BB) {
  623. // If this is the default destination from PTI, only the edges in TI
  624. // that don't occur in PTI, or that branch to BB will be activated.
  625. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  626. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  627. if (PredCases[i].second != BB)
  628. PTIHandled.insert(PredCases[i].first);
  629. else {
  630. // The default destination is BB, we don't need explicit targets.
  631. std::swap(PredCases[i], PredCases.back());
  632. PredCases.pop_back();
  633. --i; --e;
  634. }
  635. // Reconstruct the new switch statement we will be building.
  636. if (PredDefault != BBDefault) {
  637. PredDefault->removePredecessor(Pred);
  638. PredDefault = BBDefault;
  639. NewSuccessors.push_back(BBDefault);
  640. }
  641. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  642. if (!PTIHandled.count(BBCases[i].first) &&
  643. BBCases[i].second != BBDefault) {
  644. PredCases.push_back(BBCases[i]);
  645. NewSuccessors.push_back(BBCases[i].second);
  646. }
  647. } else {
  648. // If this is not the default destination from PSI, only the edges
  649. // in SI that occur in PSI with a destination of BB will be
  650. // activated.
  651. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  652. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  653. if (PredCases[i].second == BB) {
  654. PTIHandled.insert(PredCases[i].first);
  655. std::swap(PredCases[i], PredCases.back());
  656. PredCases.pop_back();
  657. --i; --e;
  658. }
  659. // Okay, now we know which constants were sent to BB from the
  660. // predecessor. Figure out where they will all go now.
  661. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  662. if (PTIHandled.count(BBCases[i].first)) {
  663. // If this is one we are capable of getting...
  664. PredCases.push_back(BBCases[i]);
  665. NewSuccessors.push_back(BBCases[i].second);
  666. PTIHandled.erase(BBCases[i].first);// This constant is taken care of
  667. }
  668. // If there are any constants vectored to BB that TI doesn't handle,
  669. // they must go to the default destination of TI.
  670. for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
  671. PTIHandled.begin(),
  672. E = PTIHandled.end(); I != E; ++I) {
  673. PredCases.push_back(std::make_pair(*I, BBDefault));
  674. NewSuccessors.push_back(BBDefault);
  675. }
  676. }
  677. // Okay, at this point, we know which new successor Pred will get. Make
  678. // sure we update the number of entries in the PHI nodes for these
  679. // successors.
  680. for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
  681. AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
  682. Builder.SetInsertPoint(PTI);
  683. // Convert pointer to int before we switch.
  684. if (CV->getType()->isPointerTy()) {
  685. assert(TD && "Cannot switch on pointer without TargetData");
  686. CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
  687. "magicptr");
  688. }
  689. // Now that the successors are updated, create the new Switch instruction.
  690. SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
  691. PredCases.size());
  692. NewSI->setDebugLoc(PTI->getDebugLoc());
  693. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  694. NewSI->addCase(PredCases[i].first, PredCases[i].second);
  695. EraseTerminatorInstAndDCECond(PTI);
  696. // Okay, last check. If BB is still a successor of PSI, then we must
  697. // have an infinite loop case. If so, add an infinitely looping block
  698. // to handle the case to preserve the behavior of the code.
  699. BasicBlock *InfLoopBlock = 0;
  700. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  701. if (NewSI->getSuccessor(i) == BB) {
  702. if (InfLoopBlock == 0) {
  703. // Insert it at the end of the function, because it's either code,
  704. // or it won't matter if it's hot. :)
  705. InfLoopBlock = BasicBlock::Create(BB->getContext(),
  706. "infloop", BB->getParent());
  707. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  708. }
  709. NewSI->setSuccessor(i, InfLoopBlock);
  710. }
  711. Changed = true;
  712. }
  713. }
  714. return Changed;
  715. }
  716. // isSafeToHoistInvoke - If we would need to insert a select that uses the
  717. // value of this invoke (comments in HoistThenElseCodeToIf explain why we
  718. // would need to do this), we can't hoist the invoke, as there is nowhere
  719. // to put the select in this case.
  720. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  721. Instruction *I1, Instruction *I2) {
  722. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  723. PHINode *PN;
  724. for (BasicBlock::iterator BBI = SI->begin();
  725. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  726. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  727. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  728. if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
  729. return false;
  730. }
  731. }
  732. }
  733. return true;
  734. }
  735. /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
  736. /// BB2, hoist any common code in the two blocks up into the branch block. The
  737. /// caller of this function guarantees that BI's block dominates BB1 and BB2.
  738. static bool HoistThenElseCodeToIf(BranchInst *BI) {
  739. // This does very trivial matching, with limited scanning, to find identical
  740. // instructions in the two blocks. In particular, we don't want to get into
  741. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  742. // such, we currently just scan for obviously identical instructions in an
  743. // identical order.
  744. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  745. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  746. BasicBlock::iterator BB1_Itr = BB1->begin();
  747. BasicBlock::iterator BB2_Itr = BB2->begin();
  748. Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
  749. // Skip debug info if it is not identical.
  750. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  751. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  752. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  753. while (isa<DbgInfoIntrinsic>(I1))
  754. I1 = BB1_Itr++;
  755. while (isa<DbgInfoIntrinsic>(I2))
  756. I2 = BB2_Itr++;
  757. }
  758. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  759. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
  760. return false;
  761. // If we get here, we can hoist at least one instruction.
  762. BasicBlock *BIParent = BI->getParent();
  763. do {
  764. // If we are hoisting the terminator instruction, don't move one (making a
  765. // broken BB), instead clone it, and remove BI.
  766. if (isa<TerminatorInst>(I1))
  767. goto HoistTerminator;
  768. // For a normal instruction, we just move one to right before the branch,
  769. // then replace all uses of the other with the first. Finally, we remove
  770. // the now redundant second instruction.
  771. BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
  772. if (!I2->use_empty())
  773. I2->replaceAllUsesWith(I1);
  774. I1->intersectOptionalDataWith(I2);
  775. I2->eraseFromParent();
  776. I1 = BB1_Itr++;
  777. I2 = BB2_Itr++;
  778. // Skip debug info if it is not identical.
  779. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  780. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  781. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  782. while (isa<DbgInfoIntrinsic>(I1))
  783. I1 = BB1_Itr++;
  784. while (isa<DbgInfoIntrinsic>(I2))
  785. I2 = BB2_Itr++;
  786. }
  787. } while (I1->isIdenticalToWhenDefined(I2));
  788. return true;
  789. HoistTerminator:
  790. // It may not be possible to hoist an invoke.
  791. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  792. return true;
  793. // Okay, it is safe to hoist the terminator.
  794. Instruction *NT = I1->clone();
  795. BIParent->getInstList().insert(BI, NT);
  796. if (!NT->getType()->isVoidTy()) {
  797. I1->replaceAllUsesWith(NT);
  798. I2->replaceAllUsesWith(NT);
  799. NT->takeName(I1);
  800. }
  801. IRBuilder<true, NoFolder> Builder(NT);
  802. // Hoisting one of the terminators from our successor is a great thing.
  803. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  804. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  805. // nodes, so we insert select instruction to compute the final result.
  806. std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
  807. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  808. PHINode *PN;
  809. for (BasicBlock::iterator BBI = SI->begin();
  810. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  811. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  812. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  813. if (BB1V == BB2V) continue;
  814. // These values do not agree. Insert a select instruction before NT
  815. // that determines the right value.
  816. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  817. if (SI == 0)
  818. SI = cast<SelectInst>
  819. (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  820. BB1V->getName()+"."+BB2V->getName()));
  821. // Make the PHI node use the select for all incoming values for BB1/BB2
  822. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  823. if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
  824. PN->setIncomingValue(i, SI);
  825. }
  826. }
  827. // Update any PHI nodes in our new successors.
  828. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
  829. AddPredecessorToBlock(*SI, BIParent, BB1);
  830. EraseTerminatorInstAndDCECond(BI);
  831. return true;
  832. }
  833. /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
  834. /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
  835. /// (for now, restricted to a single instruction that's side effect free) from
  836. /// the BB1 into the branch block to speculatively execute it.
  837. ///
  838. /// Turn
  839. /// BB:
  840. /// %t1 = icmp
  841. /// br i1 %t1, label %BB1, label %BB2
  842. /// BB1:
  843. /// %t3 = add %t2, c
  844. /// br label BB2
  845. /// BB2:
  846. /// =>
  847. /// BB:
  848. /// %t1 = icmp
  849. /// %t4 = add %t2, c
  850. /// %t3 = select i1 %t1, %t2, %t3
  851. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
  852. // Only speculatively execution a single instruction (not counting the
  853. // terminator) for now.
  854. Instruction *HInst = NULL;
  855. Instruction *Term = BB1->getTerminator();
  856. for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
  857. BBI != BBE; ++BBI) {
  858. Instruction *I = BBI;
  859. // Skip debug info.
  860. if (isa<DbgInfoIntrinsic>(I)) continue;
  861. if (I == Term) break;
  862. if (HInst)
  863. return false;
  864. HInst = I;
  865. }
  866. BasicBlock *BIParent = BI->getParent();
  867. // Check the instruction to be hoisted, if there is one.
  868. if (HInst) {
  869. // Don't hoist the instruction if it's unsafe or expensive.
  870. if (!isSafeToSpeculativelyExecute(HInst))
  871. return false;
  872. if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
  873. return false;
  874. // Do not hoist the instruction if any of its operands are defined but not
  875. // used in this BB. The transformation will prevent the operand from
  876. // being sunk into the use block.
  877. for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
  878. i != e; ++i) {
  879. Instruction *OpI = dyn_cast<Instruction>(*i);
  880. if (OpI && OpI->getParent() == BIParent &&
  881. !OpI->mayHaveSideEffects() &&
  882. !OpI->isUsedInBasicBlock(BIParent))
  883. return false;
  884. }
  885. }
  886. // Be conservative for now. FP select instruction can often be expensive.
  887. Value *BrCond = BI->getCondition();
  888. if (isa<FCmpInst>(BrCond))
  889. return false;
  890. // If BB1 is actually on the false edge of the conditional branch, remember
  891. // to swap the select operands later.
  892. bool Invert = false;
  893. if (BB1 != BI->getSuccessor(0)) {
  894. assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
  895. Invert = true;
  896. }
  897. // Collect interesting PHIs, and scan for hazards.
  898. SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
  899. BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
  900. for (BasicBlock::iterator I = BB2->begin();
  901. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  902. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  903. Value *BIParentV = PN->getIncomingValueForBlock(BIParent);
  904. // Skip PHIs which are trivial.
  905. if (BB1V == BIParentV)
  906. continue;
  907. // Check for saftey.
  908. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BB1V)) {
  909. // An unfolded ConstantExpr could end up getting expanded into
  910. // Instructions. Don't speculate this and another instruction at
  911. // the same time.
  912. if (HInst)
  913. return false;
  914. if (!isSafeToSpeculativelyExecute(CE))
  915. return false;
  916. if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
  917. return false;
  918. }
  919. // Ok, we may insert a select for this PHI.
  920. PHIs.insert(std::make_pair(BB1V, BIParentV));
  921. }
  922. // If there are no PHIs to process, bail early. This helps ensure idempotence
  923. // as well.
  924. if (PHIs.empty())
  925. return false;
  926. // If we get here, we can hoist the instruction and if-convert.
  927. DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
  928. // Hoist the instruction.
  929. if (HInst)
  930. BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
  931. // Insert selects and rewrite the PHI operands.
  932. IRBuilder<true, NoFolder> Builder(BI);
  933. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  934. Value *TrueV = PHIs[i].first;
  935. Value *FalseV = PHIs[i].second;
  936. // Create a select whose true value is the speculatively executed value and
  937. // false value is the previously determined FalseV.
  938. SelectInst *SI;
  939. if (Invert)
  940. SI = cast<SelectInst>
  941. (Builder.CreateSelect(BrCond, FalseV, TrueV,
  942. FalseV->getName() + "." + TrueV->getName()));
  943. else
  944. SI = cast<SelectInst>
  945. (Builder.CreateSelect(BrCond, TrueV, FalseV,
  946. TrueV->getName() + "." + FalseV->getName()));
  947. // Make the PHI node use the select for all incoming values for "then" and
  948. // "if" blocks.
  949. for (BasicBlock::iterator I = BB2->begin();
  950. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  951. unsigned BB1I = PN->getBasicBlockIndex(BB1);
  952. unsigned BIParentI = PN->getBasicBlockIndex(BIParent);
  953. Value *BB1V = PN->getIncomingValue(BB1I);
  954. Value *BIParentV = PN->getIncomingValue(BIParentI);
  955. if (TrueV == BB1V && FalseV == BIParentV) {
  956. PN->setIncomingValue(BB1I, SI);
  957. PN->setIncomingValue(BIParentI, SI);
  958. }
  959. }
  960. }
  961. ++NumSpeculations;
  962. return true;
  963. }
  964. /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
  965. /// across this block.
  966. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  967. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  968. unsigned Size = 0;
  969. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  970. if (isa<DbgInfoIntrinsic>(BBI))
  971. continue;
  972. if (Size > 10) return false; // Don't clone large BB's.
  973. ++Size;
  974. // We can only support instructions that do not define values that are
  975. // live outside of the current basic block.
  976. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  977. UI != E; ++UI) {
  978. Instruction *U = cast<Instruction>(*UI);
  979. if (U->getParent() != BB || isa<PHINode>(U)) return false;
  980. }
  981. // Looks ok, continue checking.
  982. }
  983. return true;
  984. }
  985. /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
  986. /// that is defined in the same block as the branch and if any PHI entries are
  987. /// constants, thread edges corresponding to that entry to be branches to their
  988. /// ultimate destination.
  989. static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
  990. BasicBlock *BB = BI->getParent();
  991. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  992. // NOTE: we currently cannot transform this case if the PHI node is used
  993. // outside of the block.
  994. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  995. return false;
  996. // Degenerate case of a single entry PHI.
  997. if (PN->getNumIncomingValues() == 1) {
  998. FoldSingleEntryPHINodes(PN->getParent());
  999. return true;
  1000. }
  1001. // Now we know that this block has multiple preds and two succs.
  1002. if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
  1003. // Okay, this is a simple enough basic block. See if any phi values are
  1004. // constants.
  1005. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1006. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1007. if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
  1008. // Okay, we now know that all edges from PredBB should be revectored to
  1009. // branch to RealDest.
  1010. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1011. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1012. if (RealDest == BB) continue; // Skip self loops.
  1013. // Skip if the predecessor's terminator is an indirect branch.
  1014. if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
  1015. // The dest block might have PHI nodes, other predecessors and other
  1016. // difficult cases. Instead of being smart about this, just insert a new
  1017. // block that jumps to the destination block, effectively splitting
  1018. // the edge we are about to create.
  1019. BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
  1020. RealDest->getName()+".critedge",
  1021. RealDest->getParent(), RealDest);
  1022. BranchInst::Create(RealDest, EdgeBB);
  1023. // Update PHI nodes.
  1024. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1025. // BB may have instructions that are being threaded over. Clone these
  1026. // instructions into EdgeBB. We know that there will be no uses of the
  1027. // cloned instructions outside of EdgeBB.
  1028. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1029. DenseMap<Value*, Value*> TranslateMap; // Track translated values.
  1030. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1031. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1032. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1033. continue;
  1034. }
  1035. // Clone the instruction.
  1036. Instruction *N = BBI->clone();
  1037. if (BBI->hasName()) N->setName(BBI->getName()+".c");
  1038. // Update operands due to translation.
  1039. for (User::op_iterator i = N->op_begin(), e = N->op_end();
  1040. i != e; ++i) {
  1041. DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
  1042. if (PI != TranslateMap.end())
  1043. *i = PI->second;
  1044. }
  1045. // Check for trivial simplification.
  1046. if (Value *V = SimplifyInstruction(N, TD)) {
  1047. TranslateMap[BBI] = V;
  1048. delete N; // Instruction folded away, don't need actual inst
  1049. } else {
  1050. // Insert the new instruction into its new home.
  1051. EdgeBB->getInstList().insert(InsertPt, N);
  1052. if (!BBI->use_empty())
  1053. TranslateMap[BBI] = N;
  1054. }
  1055. }
  1056. // Loop over all of the edges from PredBB to BB, changing them to branch
  1057. // to EdgeBB instead.
  1058. TerminatorInst *PredBBTI = PredBB->getTerminator();
  1059. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1060. if (PredBBTI->getSuccessor(i) == BB) {
  1061. BB->removePredecessor(PredBB);
  1062. PredBBTI->setSuccessor(i, EdgeBB);
  1063. }
  1064. // Recurse, simplifying any other constants.
  1065. return FoldCondBranchOnPHI(BI, TD) | true;
  1066. }
  1067. return false;
  1068. }
  1069. /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
  1070. /// PHI node, see if we can eliminate it.
  1071. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
  1072. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1073. // statement", which has a very simple dominance structure. Basically, we
  1074. // are trying to find the condition that is being branched on, which
  1075. // subsequently causes this merge to happen. We really want control
  1076. // dependence information for this check, but simplifycfg can't keep it up
  1077. // to date, and this catches most of the cases we care about anyway.
  1078. BasicBlock *BB = PN->getParent();
  1079. BasicBlock *IfTrue, *IfFalse;
  1080. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  1081. if (!IfCond ||
  1082. // Don't bother if the branch will be constant folded trivially.
  1083. isa<ConstantInt>(IfCond))
  1084. return false;
  1085. // Okay, we found that we can merge this two-entry phi node into a select.
  1086. // Doing so would require us to fold *all* two entry phi nodes in this block.
  1087. // At some point this becomes non-profitable (particularly if the target
  1088. // doesn't support cmov's). Only do this transformation if there are two or
  1089. // fewer PHI nodes in this block.
  1090. unsigned NumPhis = 0;
  1091. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  1092. if (NumPhis > 2)
  1093. return false;
  1094. // Loop over the PHI's seeing if we can promote them all to select
  1095. // instructions. While we are at it, keep track of the instructions
  1096. // that need to be moved to the dominating block.
  1097. SmallPtrSet<Instruction*, 4> AggressiveInsts;
  1098. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  1099. MaxCostVal1 = PHINodeFoldingThreshold;
  1100. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  1101. PHINode *PN = cast<PHINode>(II++);
  1102. if (Value *V = SimplifyInstruction(PN, TD)) {
  1103. PN->replaceAllUsesWith(V);
  1104. PN->eraseFromParent();
  1105. continue;
  1106. }
  1107. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
  1108. MaxCostVal0) ||
  1109. !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
  1110. MaxCostVal1))
  1111. return false;
  1112. }
  1113. // If we folded the the first phi, PN dangles at this point. Refresh it. If
  1114. // we ran out of PHIs then we simplified them all.
  1115. PN = dyn_cast<PHINode>(BB->begin());
  1116. if (PN == 0) return true;
  1117. // Don't fold i1 branches on PHIs which contain binary operators. These can
  1118. // often be turned into switches and other things.
  1119. if (PN->getType()->isIntegerTy(1) &&
  1120. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  1121. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  1122. isa<BinaryOperator>(IfCond)))
  1123. return false;
  1124. // If we all PHI nodes are promotable, check to make sure that all
  1125. // instructions in the predecessor blocks can be promoted as well. If
  1126. // not, we won't be able to get rid of the control flow, so it's not
  1127. // worth promoting to select instructions.
  1128. BasicBlock *DomBlock = 0;
  1129. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  1130. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  1131. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  1132. IfBlock1 = 0;
  1133. } else {
  1134. DomBlock = *pred_begin(IfBlock1);
  1135. for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
  1136. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1137. // This is not an aggressive instruction that we can promote.
  1138. // Because of this, we won't be able to get rid of the control
  1139. // flow, so the xform is not worth it.
  1140. return false;
  1141. }
  1142. }
  1143. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  1144. IfBlock2 = 0;
  1145. } else {
  1146. DomBlock = *pred_begin(IfBlock2);
  1147. for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
  1148. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1149. // This is not an aggressive instruction that we can promote.
  1150. // Because of this, we won't be able to get rid of the control
  1151. // flow, so the xform is not worth it.
  1152. return false;
  1153. }
  1154. }
  1155. DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
  1156. << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
  1157. // If we can still promote the PHI nodes after this gauntlet of tests,
  1158. // do all of the PHI's now.
  1159. Instruction *InsertPt = DomBlock->getTerminator();
  1160. IRBuilder<true, NoFolder> Builder(InsertPt);
  1161. // Move all 'aggressive' instructions, which are defined in the
  1162. // conditional parts of the if's up to the dominating block.
  1163. if (IfBlock1)
  1164. DomBlock->getInstList().splice(InsertPt,
  1165. IfBlock1->getInstList(), IfBlock1->begin(),
  1166. IfBlock1->getTerminator());
  1167. if (IfBlock2)
  1168. DomBlock->getInstList().splice(InsertPt,
  1169. IfBlock2->getInstList(), IfBlock2->begin(),
  1170. IfBlock2->getTerminator());
  1171. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  1172. // Change the PHI node into a select instruction.
  1173. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  1174. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  1175. SelectInst *NV =
  1176. cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
  1177. PN->replaceAllUsesWith(NV);
  1178. NV->takeName(PN);
  1179. PN->eraseFromParent();
  1180. }
  1181. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  1182. // has been flattened. Change DomBlock to jump directly to our new block to
  1183. // avoid other simplifycfg's kicking in on the diamond.
  1184. TerminatorInst *OldTI = DomBlock->getTerminator();
  1185. Builder.SetInsertPoint(OldTI);
  1186. Builder.CreateBr(BB);
  1187. OldTI->eraseFromParent();
  1188. return true;
  1189. }
  1190. /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
  1191. /// to two returning blocks, try to merge them together into one return,
  1192. /// introducing a select if the return values disagree.
  1193. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  1194. IRBuilder<> &Builder) {
  1195. assert(BI->isConditional() && "Must be a conditional branch");
  1196. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1197. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1198. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  1199. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  1200. // Check to ensure both blocks are empty (just a return) or optionally empty
  1201. // with PHI nodes. If there are other instructions, merging would cause extra
  1202. // computation on one path or the other.
  1203. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  1204. return false;
  1205. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  1206. return false;
  1207. Builder.SetInsertPoint(BI);
  1208. // Okay, we found a branch that is going to two return nodes. If
  1209. // there is no return value for this function, just change the
  1210. // branch into a return.
  1211. if (FalseRet->getNumOperands() == 0) {
  1212. TrueSucc->removePredecessor(BI->getParent());
  1213. FalseSucc->removePredecessor(BI->getParent());
  1214. Builder.CreateRetVoid();
  1215. EraseTerminatorInstAndDCECond(BI);
  1216. return true;
  1217. }
  1218. // Otherwise, figure out what the true and false return values are
  1219. // so we can insert a new select instruction.
  1220. Value *TrueValue = TrueRet->getReturnValue();
  1221. Value *FalseValue = FalseRet->getReturnValue();
  1222. // Unwrap any PHI nodes in the return blocks.
  1223. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  1224. if (TVPN->getParent() == TrueSucc)
  1225. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  1226. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  1227. if (FVPN->getParent() == FalseSucc)
  1228. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  1229. // In order for this transformation to be safe, we must be able to
  1230. // unconditionally execute both operands to the return. This is
  1231. // normally the case, but we could have a potentially-trapping
  1232. // constant expression that prevents this transformation from being
  1233. // safe.
  1234. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  1235. if (TCV->canTrap())
  1236. return false;
  1237. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  1238. if (FCV->canTrap())
  1239. return false;
  1240. // Okay, we collected all the mapped values and checked them for sanity, and
  1241. // defined to really do this transformation. First, update the CFG.
  1242. TrueSucc->removePredecessor(BI->getParent());
  1243. FalseSucc->removePredecessor(BI->getParent());
  1244. // Insert select instructions where needed.
  1245. Value *BrCond = BI->getCondition();
  1246. if (TrueValue) {
  1247. // Insert a select if the results differ.
  1248. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  1249. } else if (isa<UndefValue>(TrueValue)) {
  1250. TrueValue = FalseValue;
  1251. } else {
  1252. TrueValue = Builder.CreateSelect(BrCond, TrueValue,
  1253. FalseValue, "retval");
  1254. }
  1255. }
  1256. Value *RI = !TrueValue ?
  1257. Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  1258. (void) RI;
  1259. DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  1260. << "\n " << *BI << "NewRet = " << *RI
  1261. << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
  1262. EraseTerminatorInstAndDCECond(BI);
  1263. return true;
  1264. }
  1265. /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
  1266. /// probabilities of the branch taking each edge. Fills in the two APInt
  1267. /// parameters and return true, or returns false if no or invalid metadata was
  1268. /// found.
  1269. static bool ExtractBranchMetadata(BranchInst *BI,
  1270. APInt &ProbTrue, APInt &ProbFalse) {
  1271. assert(BI->isConditional() &&
  1272. "Looking for probabilities on unconditional branch?");
  1273. MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  1274. if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
  1275. ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
  1276. ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
  1277. if (!CITrue || !CIFalse) return false;
  1278. ProbTrue = CITrue->getValue();
  1279. ProbFalse = CIFalse->getValue();
  1280. assert(ProbTrue.getBitWidth() == 32 && ProbFalse.getBitWidth() == 32 &&
  1281. "Branch probability metadata must be 32-bit integers");
  1282. return true;
  1283. }
  1284. /// MultiplyAndLosePrecision - Multiplies A and B, then returns the result. In
  1285. /// the event of overflow, logically-shifts all four inputs right until the
  1286. /// multiply fits.
  1287. static APInt MultiplyAndLosePrecision(APInt &A, APInt &B, APInt &C, APInt &D,
  1288. unsigned &BitsLost) {
  1289. BitsLost = 0;
  1290. bool Overflow = false;
  1291. APInt Result = A.umul_ov(B, Overflow);
  1292. if (Overflow) {
  1293. APInt MaxB = APInt::getMaxValue(A.getBitWidth()).udiv(A);
  1294. do {
  1295. B = B.lshr(1);
  1296. ++BitsLost;
  1297. } while (B.ugt(MaxB));
  1298. A = A.lshr(BitsLost);
  1299. C = C.lshr(BitsLost);
  1300. D = D.lshr(BitsLost);
  1301. Result = A * B;
  1302. }
  1303. return Result;
  1304. }
  1305. /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
  1306. /// predecessor branches to us and one of our successors, fold the block into
  1307. /// the predecessor and use logical operations to pick the right destination.
  1308. bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
  1309. BasicBlock *BB = BI->getParent();
  1310. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  1311. if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  1312. Cond->getParent() != BB || !Cond->hasOneUse())
  1313. return false;
  1314. // Only allow this if the condition is a simple instruction that can be
  1315. // executed unconditionally. It must be in the same block as the branch, and
  1316. // must be at the front of the block.
  1317. BasicBlock::iterator FrontIt = BB->front();
  1318. // Ignore dbg intrinsics.
  1319. while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
  1320. // Allow a single instruction to be hoisted in addition to the compare
  1321. // that feeds the branch. We later ensure that any values that _it_ uses
  1322. // were also live in the predecessor, so that we don't unnecessarily create
  1323. // register pressure or inhibit out-of-order execution.
  1324. Instruction *BonusInst = 0;
  1325. if (&*FrontIt != Cond &&
  1326. FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
  1327. isSafeToSpeculativelyExecute(FrontIt)) {
  1328. BonusInst = &*FrontIt;
  1329. ++FrontIt;
  1330. // Ignore dbg intrinsics.
  1331. while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
  1332. }
  1333. // Only a single bonus inst is allowed.
  1334. if (&*FrontIt != Cond)
  1335. return false;
  1336. // Make sure the instruction after the condition is the cond branch.
  1337. BasicBlock::iterator CondIt = Cond; ++CondIt;
  1338. // Ingore dbg intrinsics.
  1339. while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
  1340. if (&*CondIt != BI)
  1341. return false;
  1342. // Cond is known to be a compare or binary operator. Check to make sure that
  1343. // neither operand is a potentially-trapping constant expression.
  1344. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  1345. if (CE->canTrap())
  1346. return false;
  1347. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  1348. if (CE->canTrap())
  1349. return false;
  1350. // Finally, don't infinitely unroll conditional loops.
  1351. BasicBlock *TrueDest = BI->getSuccessor(0);
  1352. BasicBlock *FalseDest = BI->getSuccessor(1);
  1353. if (TrueDest == BB || FalseDest == BB)
  1354. return false;
  1355. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1356. BasicBlock *PredBlock = *PI;
  1357. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  1358. // Check that we have two conditional branches. If there is a PHI node in
  1359. // the common successor, verify that the same value flows in from both
  1360. // blocks.
  1361. if (PBI == 0 || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
  1362. continue;
  1363. // Determine if the two branches share a common destination.
  1364. Instruction::BinaryOps Opc;
  1365. bool InvertPredCond = false;
  1366. if (PBI->getSuccessor(0) == TrueDest)
  1367. Opc = Instruction::Or;
  1368. else if (PBI->getSuccessor(1) == FalseDest)
  1369. Opc = Instruction::And;
  1370. else if (PBI->getSuccessor(0) == FalseDest)
  1371. Opc = Instruction::And, InvertPredCond = true;
  1372. else if (PBI->getSuccessor(1) == TrueDest)
  1373. Opc = Instruction::Or, InvertPredCond = true;
  1374. else
  1375. continue;
  1376. // Ensure that any values used in the bonus instruction are also used
  1377. // by the terminator of the predecessor. This means that those values
  1378. // must already have been resolved, so we won't be inhibiting the
  1379. // out-of-order core by speculating them earlier.
  1380. if (BonusInst) {
  1381. // Collect the values used by the bonus inst
  1382. SmallPtrSet<Value*, 4> UsedValues;
  1383. for (Instruction::op_iterator OI = BonusInst->op_begin(),
  1384. OE = BonusInst->op_end(); OI != OE; ++OI) {
  1385. Value *V = *OI;
  1386. if (!isa<Constant>(V))
  1387. UsedValues.insert(V);
  1388. }
  1389. SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
  1390. Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
  1391. // Walk up to four levels back up the use-def chain of the predecessor's
  1392. // terminator to see if all those values were used. The choice of four
  1393. // levels is arbitrary, to provide a compile-time-cost bound.
  1394. while (!Worklist.empty()) {
  1395. std::pair<Value*, unsigned> Pair = Worklist.back();
  1396. Worklist.pop_back();
  1397. if (Pair.second >= 4) continue;
  1398. UsedValues.erase(Pair.first);
  1399. if (UsedValues.empty()) break;
  1400. if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
  1401. for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
  1402. OI != OE; ++OI)
  1403. Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
  1404. }
  1405. }
  1406. if (!UsedValues.empty()) return false;
  1407. }
  1408. DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  1409. IRBuilder<> Builder(PBI);
  1410. // If we need to invert the condition in the pred block to match, do so now.
  1411. if (InvertPredCond) {
  1412. Value *NewCond = PBI->getCondition();
  1413. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  1414. CmpInst *CI = cast<CmpInst>(NewCond);
  1415. CI->setPredicate(CI->getInversePredicate());
  1416. } else {
  1417. NewCond = Builder.CreateNot(NewCond,
  1418. PBI->getCondition()->getName()+".not");
  1419. }
  1420. PBI->setCondition(NewCond);
  1421. PBI->swapSuccessors();
  1422. }
  1423. // If we have a bonus inst, clone it into the predecessor block.
  1424. Instruction *NewBonus = 0;
  1425. if (BonusInst) {
  1426. NewBonus = BonusInst->clone();
  1427. PredBlock->getInstList().insert(PBI, NewBonus);
  1428. NewBonus->takeName(BonusInst);
  1429. BonusInst->setName(BonusInst->getName()+".old");
  1430. }
  1431. // Clone Cond into the predecessor basic block, and or/and the
  1432. // two conditions together.
  1433. Instruction *New = Cond->clone();
  1434. if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
  1435. PredBlock->getInstList().insert(PBI, New);
  1436. New->takeName(Cond);
  1437. Cond->setName(New->getName()+".old");
  1438. Instruction *NewCond =
  1439. cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
  1440. New, "or.cond"));
  1441. PBI->setCondition(NewCond);
  1442. if (PBI->getSuccessor(0) == BB) {
  1443. AddPredecessorToBlock(TrueDest, PredBlock, BB);
  1444. PBI->setSuccessor(0, TrueDest);
  1445. }
  1446. if (PBI->getSuccessor(1) == BB) {
  1447. AddPredecessorToBlock(FalseDest, PredBlock, BB);
  1448. PBI->setSuccessor(1, FalseDest);
  1449. }
  1450. // TODO: If BB is reachable from all paths through PredBlock, then we
  1451. // could replace PBI's branch probabilities with BI's.
  1452. // Merge probability data into PredBlock's branch.
  1453. APInt A, B, C, D;
  1454. if (ExtractBranchMetadata(PBI, C, D) && ExtractBranchMetadata(BI, A, B)) {
  1455. // Given IR which does:
  1456. // bbA:
  1457. // br i1 %x, label %bbB, label %bbC
  1458. // bbB:
  1459. // br i1 %y, label %bbD, label %bbC
  1460. // Let's call the probability that we take the edge from %bbA to %bbB
  1461. // 'a', from %bbA to %bbC, 'b', from %bbB to %bbD 'c' and from %bbB to
  1462. // %bbC probability 'd'.
  1463. //
  1464. // We transform the IR into:
  1465. // bbA:
  1466. // br i1 %z, label %bbD, label %bbC
  1467. // where the probability of going to %bbD is (a*c) and going to bbC is
  1468. // (b+a*d).
  1469. //
  1470. // Probabilities aren't stored as ratios directly. Using branch weights,
  1471. // we get:
  1472. // (a*c)% = A*C, (b+(a*d))% = A*D+B*C+B*D.
  1473. // In the event of overflow, we want to drop the LSB of the input
  1474. // probabilities.
  1475. unsigned BitsLost;
  1476. // Ignore overflow result on ProbTrue.
  1477. APInt ProbTrue = MultiplyAndLosePrecision(A, C, B, D, BitsLost);
  1478. APInt Tmp1 = MultiplyAndLosePrecision(B, D, A, C, BitsLost);
  1479. if (BitsLost) {
  1480. ProbTrue = ProbTrue.lshr(BitsLost*2);
  1481. }
  1482. APInt Tmp2 = MultiplyAndLosePrecision(A, D, C, B, BitsLost);
  1483. if (BitsLost) {
  1484. ProbTrue = ProbTrue.lshr(BitsLost*2);
  1485. Tmp1 = Tmp1.lshr(BitsLost*2);
  1486. }
  1487. APInt Tmp3 = MultiplyAndLosePrecision(B, C, A, D, BitsLost);
  1488. if (BitsLost) {
  1489. ProbTrue = ProbTrue.lshr(BitsLost*2);
  1490. Tmp1 = Tmp1.lshr(BitsLost*2);
  1491. Tmp2 = Tmp2.lshr(BitsLost*2);
  1492. }
  1493. bool Overflow1 = false, Overflow2 = false;
  1494. APInt Tmp4 = Tmp2.uadd_ov(Tmp3, Overflow1);
  1495. APInt ProbFalse = Tmp4.uadd_ov(Tmp1, Overflow2);
  1496. if (Overflow1 || Overflow2) {
  1497. ProbTrue = ProbTrue.lshr(1);
  1498. Tmp1 = Tmp1.lshr(1);
  1499. Tmp2 = Tmp2.lshr(1);
  1500. Tmp3 = Tmp3.lshr(1);
  1501. Tmp4 = Tmp2 + Tmp3;
  1502. ProbFalse = Tmp4 + Tmp1;
  1503. }
  1504. // The sum of branch weights must fit in 32-bits.
  1505. if (ProbTrue.isNegative() && ProbFalse.isNegative()) {
  1506. ProbTrue = ProbTrue.lshr(1);
  1507. ProbFalse = ProbFalse.lshr(1);
  1508. }
  1509. if (ProbTrue != ProbFalse) {
  1510. // Normalize the result.
  1511. APInt GCD = APIntOps::GreatestCommonDivisor(ProbTrue, ProbFalse);
  1512. ProbTrue = ProbTrue.udiv(GCD);
  1513. ProbFalse = ProbFalse.udiv(GCD);
  1514. LLVMContext &Context = BI->getContext();
  1515. Value *Ops[3];
  1516. Ops[0] = BI->getMetadata(LLVMContext::MD_prof)->getOperand(0);
  1517. Ops[1] = ConstantInt::get(Context, ProbTrue);
  1518. Ops[2] = ConstantInt::get(Context, ProbFalse);
  1519. PBI->setMetadata(LLVMContext::MD_prof, MDNode::get(Context, Ops));
  1520. } else {
  1521. PBI->setMetadata(LLVMContext::MD_prof, NULL);
  1522. }
  1523. } else {
  1524. PBI->setMetadata(LLVMContext::MD_prof, NULL);
  1525. }
  1526. // Copy any debug value intrinsics into the end of PredBlock.
  1527. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  1528. if (isa<DbgInfoIntrinsic>(*I))
  1529. I->clone()->insertBefore(PBI);
  1530. return true;
  1531. }
  1532. return false;
  1533. }
  1534. /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
  1535. /// predecessor of another block, this function tries to simplify it. We know
  1536. /// that PBI and BI are both conditional branches, and BI is in one of the
  1537. /// successor blocks of PBI - PBI branches to BI.
  1538. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
  1539. assert(PBI->isConditional() && BI->isConditional());
  1540. BasicBlock *BB = BI->getParent();
  1541. // If this block ends with a branch instruction, and if there is a
  1542. // predecessor that ends on a branch of the same condition, make
  1543. // this conditional branch redundant.
  1544. if (PBI->getCondition() == BI->getCondition() &&
  1545. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  1546. // Okay, the outcome of this conditional branch is statically
  1547. // knowable. If this block had a single pred, handle specially.
  1548. if (BB->getSinglePredecessor()) {
  1549. // Turn this into a branch on constant.
  1550. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  1551. BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  1552. CondIsTrue));
  1553. return true; // Nuke the branch on constant.
  1554. }
  1555. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  1556. // in the constant and simplify the block result. Subsequent passes of
  1557. // simplifycfg will thread the block.
  1558. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  1559. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  1560. PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
  1561. std::distance(PB, PE),
  1562. BI->getCondition()->getName() + ".pr",
  1563. BB->begin());
  1564. // Okay, we're going to insert the PHI node. Since PBI is not the only
  1565. // predecessor, compute the PHI'd conditional value for all of the preds.
  1566. // Any predecessor where the condition is not computable we keep symbolic.
  1567. for (pred_iterator PI = PB; PI != PE; ++PI) {
  1568. BasicBlock *P = *PI;
  1569. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
  1570. PBI != BI && PBI->isConditional() &&
  1571. PBI->getCondition() == BI->getCondition() &&
  1572. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  1573. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  1574. NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  1575. CondIsTrue), P);
  1576. } else {
  1577. NewPN->addIncoming(BI->getCondition(), P);
  1578. }
  1579. }
  1580. BI->setCondition(NewPN);
  1581. return true;
  1582. }
  1583. }
  1584. // If this is a conditional branch in an empty block, and if any
  1585. // predecessors is a conditional branch to one of our destinations,
  1586. // fold the conditions into logical ops and one cond br.
  1587. BasicBlock::iterator BBI = BB->begin();
  1588. // Ignore dbg intrinsics.
  1589. while (isa<DbgInfoIntrinsic>(BBI))
  1590. ++BBI;
  1591. if (&*BBI != BI)
  1592. return false;
  1593. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  1594. if (CE->canTrap())
  1595. return false;
  1596. int PBIOp, BIOp;
  1597. if (PBI->getSuccessor(0) == BI->getSuccessor(0))
  1598. PBIOp = BIOp = 0;
  1599. else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
  1600. PBIOp = 0, BIOp = 1;
  1601. else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
  1602. PBIOp = 1, BIOp = 0;
  1603. else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
  1604. PBIOp = BIOp = 1;
  1605. else
  1606. return false;
  1607. // Check to make sure that the other destination of this branch
  1608. // isn't BB itself. If so, this is an infinite loop that will
  1609. // keep getting unwound.
  1610. if (PBI->getSuccessor(PBIOp) == BB)
  1611. return false;
  1612. // Do not perform this transformation if it would require
  1613. // insertion of a large number of select instructions. For targets
  1614. // without predication/cmovs, this is a big pessimization.
  1615. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  1616. unsigned NumPhis = 0;
  1617. for (BasicBlock::iterator II = CommonDest->begin();
  1618. isa<PHINode>(II); ++II, ++NumPhis)
  1619. if (NumPhis > 2) // Disable this xform.
  1620. return false;
  1621. // Finally, if everything is ok, fold the branches to logical ops.
  1622. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  1623. DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  1624. << "AND: " << *BI->getParent());
  1625. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  1626. // branch in it, where one edge (OtherDest) goes back to itself but the other
  1627. // exits. We don't *know* that the program avoids the infinite loop
  1628. // (even though that seems likely). If we do this xform naively, we'll end up
  1629. // recursively unpeeling the loop. Since we know that (after the xform is
  1630. // done) that the block *is* infinite if reached, we just make it an obviously
  1631. // infinite loop with no cond branch.
  1632. if (OtherDest == BB) {
  1633. // Insert it at the end of the function, because it's either code,
  1634. // or it won't matter if it's hot. :)
  1635. BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
  1636. "infloop", BB->getParent());
  1637. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  1638. OtherDest = InfLoopBlock;
  1639. }
  1640. DEBUG(dbgs() << *PBI->getParent()->getParent());
  1641. // BI may have other predecessors. Because of this, we leave
  1642. // it alone, but modify PBI.
  1643. // Make sure we get to CommonDest on True&True directions.
  1644. Value *PBICond = PBI->getCondition();
  1645. IRBuilder<true, NoFolder> Builder(PBI);
  1646. if (PBIOp)
  1647. PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
  1648. Value *BICond = BI->getCondition();
  1649. if (BIOp)
  1650. BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
  1651. // Merge the conditions.
  1652. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  1653. // Modify PBI to branch on the new condition to the new dests.
  1654. PBI->setCondition(Cond);
  1655. PBI->setSuccessor(0, CommonDest);
  1656. PBI->setSuccessor(1, OtherDest);
  1657. // OtherDest may have phi nodes. If so, add an entry from PBI's
  1658. // block that are identical to the entries for BI's block.
  1659. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  1660. // We know that the CommonDest already had an edge from PBI to
  1661. // it. If it has PHIs though, the PHIs may have different
  1662. // entries for BB and PBI's BB. If so, insert a select to make
  1663. // them agree.
  1664. PHINode *PN;
  1665. for (BasicBlock::iterator II = CommonDest->begin();
  1666. (PN = dyn_cast<PHINode>(II)); ++II) {
  1667. Value *BIV = PN->getIncomingValueForBlock(BB);
  1668. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  1669. Value *PBIV = PN->getIncomingValue(PBBIdx);
  1670. if (BIV != PBIV) {
  1671. // Insert a select in PBI to pick the right value.
  1672. Value *NV = cast<SelectInst>
  1673. (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
  1674. PN->setIncomingValue(PBBIdx, NV);
  1675. }
  1676. }
  1677. DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  1678. DEBUG(dbgs() << *PBI->getParent()->getParent());
  1679. // This basic block is probably dead. We know it has at least
  1680. // one fewer predecessor.
  1681. return true;
  1682. }
  1683. // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
  1684. // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
  1685. // Takes care of updating the successors and removing the old terminator.
  1686. // Also makes sure not to introduce new successors by assuming that edges to
  1687. // non-successor TrueBBs and FalseBBs aren't reachable.
  1688. static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
  1689. BasicBlock *TrueBB, BasicBlock *FalseBB){
  1690. // Remove any superfluous successor edges from the CFG.
  1691. // First, figure out which successors to preserve.
  1692. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  1693. // successor.
  1694. BasicBlock *KeepEdge1 = TrueBB;
  1695. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
  1696. // Then remove the rest.
  1697. for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
  1698. BasicBlock *Succ = OldTerm->getSuccessor(I);
  1699. // Make sure only to keep exactly one copy of each edge.
  1700. if (Succ == KeepEdge1)
  1701. KeepEdge1 = 0;
  1702. else if (Succ == KeepEdge2)
  1703. KeepEdge2 = 0;
  1704. else
  1705. Succ->removePredecessor(OldTerm->getParent());
  1706. }
  1707. IRBuilder<> Builder(OldTerm);
  1708. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  1709. // Insert an appropriate new terminator.
  1710. if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
  1711. if (TrueBB == FalseBB)
  1712. // We were only looking for one successor, and it was present.
  1713. // Create an unconditional branch to it.
  1714. Builder.CreateBr(TrueBB);
  1715. else
  1716. // We found both of the successors we were looking for.
  1717. // Create a conditional branch sharing the condition of the select.
  1718. Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  1719. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  1720. // Neither of the selected blocks were successors, so this
  1721. // terminator must be unreachable.
  1722. new UnreachableInst(OldTerm->getContext(), OldTerm);
  1723. } else {
  1724. // One of the selected values was a successor, but the other wasn't.
  1725. // Insert an unconditional branch to the one that was found;
  1726. // the edge to the one that wasn't must be unreachable.
  1727. if (KeepEdge1 == 0)
  1728. // Only TrueBB was found.
  1729. Builder.CreateBr(TrueBB);
  1730. else
  1731. // Only FalseBB was found.
  1732. Builder.CreateBr(FalseBB);
  1733. }
  1734. EraseTerminatorInstAndDCECond(OldTerm);
  1735. return true;
  1736. }
  1737. // SimplifySwitchOnSelect - Replaces
  1738. // (switch (select cond, X, Y)) on constant X, Y
  1739. // with a branch - conditional if X and Y lead to distinct BBs,
  1740. // unconditional otherwise.
  1741. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  1742. // Check for constant integer values in the select.
  1743. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  1744. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  1745. if (!TrueVal || !FalseVal)
  1746. return false;
  1747. // Find the relevant condition and destinations.
  1748. Value *Condition = Select->getCondition();
  1749. unsigned TrueCase = SI->findCaseValue(TrueVal);
  1750. unsigned FalseCase = SI->findCaseValue(FalseVal);
  1751. BasicBlock *TrueBB = SI->getSuccessor(SI->resolveSuccessorIndex(TrueCase));
  1752. BasicBlock *FalseBB = SI->getSuccessor(SI->resolveSuccessorIndex(FalseCase));
  1753. // Perform the actual simplification.
  1754. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
  1755. }
  1756. // SimplifyIndirectBrOnSelect - Replaces
  1757. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  1758. // blockaddress(@fn, BlockB)))
  1759. // with
  1760. // (br cond, BlockA, BlockB).
  1761. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  1762. // Check that both operands of the select are block addresses.
  1763. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  1764. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  1765. if (!TBA || !FBA)
  1766. return false;
  1767. // Extract the actual blocks.
  1768. BasicBlock *TrueBB = TBA->getBasicBlock();
  1769. BasicBlock *FalseBB = FBA->getBasicBlock();
  1770. // Perform the actual simplification.
  1771. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
  1772. }
  1773. /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
  1774. /// instruction (a seteq/setne with a constant) as the only instruction in a
  1775. /// block that ends with an uncond branch. We are looking for a very specific
  1776. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  1777. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  1778. /// default value goes to an uncond block with a seteq in it, we get something
  1779. /// like:
  1780. ///
  1781. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  1782. /// DEFAULT:
  1783. /// %tmp = icmp eq i8 %A, 92
  1784. /// br label %end
  1785. /// end:
  1786. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  1787. ///
  1788. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  1789. /// the PHI, merging the third icmp into the switch.
  1790. static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
  1791. const TargetData *TD,
  1792. IRBuilder<> &Builder) {
  1793. BasicBlock *BB = ICI->getParent();
  1794. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  1795. // complex.
  1796. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
  1797. Value *V = ICI->getOperand(0);
  1798. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  1799. // The pattern we're looking for is where our only predecessor is a switch on
  1800. // 'V' and this block is the default case for the switch. In this case we can
  1801. // fold the compared value into the switch to simplify things.
  1802. BasicBlock *Pred = BB->getSinglePredecessor();
  1803. if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
  1804. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  1805. if (SI->getCondition() != V)
  1806. return false;
  1807. // If BB is reachable on a non-default case, then we simply know the value of
  1808. // V in this block. Substitute it and constant fold the icmp instruction
  1809. // away.
  1810. if (SI->getDefaultDest() != BB) {
  1811. ConstantInt *VVal = SI->findCaseDest(BB);
  1812. assert(VVal && "Should have a unique destination value");
  1813. ICI->setOperand(0, VVal);
  1814. if (Value *V = SimplifyInstruction(ICI, TD)) {
  1815. ICI->replaceAllUsesWith(V);
  1816. ICI->eraseFromParent();
  1817. }
  1818. // BB is now empty, so it is likely to simplify away.
  1819. return SimplifyCFG(BB) | true;
  1820. }
  1821. // Ok, the block is reachable from the default dest. If the constant we're
  1822. // comparing exists in one of the other edges, then we can constant fold ICI
  1823. // and zap it.
  1824. if (SI->findCaseValue(Cst) != SwitchInst::ErrorIndex) {
  1825. Value *V;
  1826. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  1827. V = ConstantInt::getFalse(BB->getContext());
  1828. else
  1829. V = ConstantInt::getTrue(BB->getContext());
  1830. ICI->replaceAllUsesWith(V);
  1831. ICI->eraseFromParent();
  1832. // BB is now empty, so it is likely to simplify away.
  1833. return SimplifyCFG(BB) | true;
  1834. }
  1835. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  1836. // the block.
  1837. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  1838. PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
  1839. if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
  1840. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  1841. return false;
  1842. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  1843. // true in the PHI.
  1844. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  1845. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  1846. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  1847. std::swap(DefaultCst, NewCst);
  1848. // Replace ICI (which is used by the PHI for the default value) with true or
  1849. // false depending on if it is EQ or NE.
  1850. ICI->replaceAllUsesWith(DefaultCst);
  1851. ICI->eraseFromParent();
  1852. // Okay, the switch goes to this block on a default value. Add an edge from
  1853. // the switch to the merge point on the compared value.
  1854. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
  1855. BB->getParent(), BB);
  1856. SI->addCase(Cst, NewBB);
  1857. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  1858. Builder.SetInsertPoint(NewBB);
  1859. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  1860. Builder.CreateBr(SuccBlock);
  1861. PHIUse->addIncoming(NewCst, NewBB);
  1862. return true;
  1863. }
  1864. /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
  1865. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  1866. /// fold it into a switch instruction if so.
  1867. static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD,
  1868. IRBuilder<> &Builder) {
  1869. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  1870. if (Cond == 0) return false;
  1871. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  1872. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  1873. // 'setne's and'ed together, collect them.
  1874. Value *CompVal = 0;
  1875. std::vector<ConstantInt*> Values;
  1876. bool TrueWhenEqual = true;
  1877. Value *ExtraCase = 0;
  1878. unsigned UsedICmps = 0;
  1879. if (Cond->getOpcode() == Instruction::Or) {
  1880. CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
  1881. UsedICmps);
  1882. } else if (Cond->getOpcode() == Instruction::And) {
  1883. CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
  1884. UsedICmps);
  1885. TrueWhenEqual = false;
  1886. }
  1887. // If we didn't have a multiply compared value, fail.
  1888. if (CompVal == 0) return false;
  1889. // Avoid turning single icmps into a switch.
  1890. if (UsedICmps <= 1)
  1891. return false;
  1892. // There might be duplicate constants in the list, which the switch
  1893. // instruction can't handle, remove them now.
  1894. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  1895. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  1896. // If Extra was used, we require at least two switch values to do the
  1897. // transformation. A switch with one value is just an cond branch.
  1898. if (ExtraCase && Values.size() < 2) return false;
  1899. // Figure out which block is which destination.
  1900. BasicBlock *DefaultBB = BI->getSuccessor(1);
  1901. BasicBlock *EdgeBB = BI->getSuccessor(0);
  1902. if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
  1903. BasicBlock *BB = BI->getParent();
  1904. DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  1905. << " cases into SWITCH. BB is:\n" << *BB);
  1906. // If there are any extra values that couldn't be folded into the switch
  1907. // then we evaluate them with an explicit branch first. Split the block
  1908. // right before the condbr to handle it.
  1909. if (ExtraCase) {
  1910. BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
  1911. // Remove the uncond branch added to the old block.
  1912. TerminatorInst *OldTI = BB->getTerminator();
  1913. Builder.SetInsertPoint(OldTI);
  1914. if (TrueWhenEqual)
  1915. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  1916. else
  1917. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  1918. OldTI->eraseFromParent();
  1919. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  1920. // for the edge we just added.
  1921. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  1922. DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  1923. << "\nEXTRABB = " << *BB);
  1924. BB = NewBB;
  1925. }
  1926. Builder.SetInsertPoint(BI);
  1927. // Convert pointer to int before we switch.
  1928. if (CompVal->getType()->isPointerTy()) {
  1929. assert(TD && "Cannot switch on pointer without TargetData");
  1930. CompVal = Builder.CreatePtrToInt(CompVal,
  1931. TD->getIntPtrType(CompVal->getContext()),
  1932. "magicptr");
  1933. }
  1934. // Create the new switch instruction now.
  1935. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  1936. // Add all of the 'cases' to the switch instruction.
  1937. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  1938. New->addCase(Values[i], EdgeBB);
  1939. // We added edges from PI to the EdgeBB. As such, if there were any
  1940. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  1941. // the number of edges added.
  1942. for (BasicBlock::iterator BBI = EdgeBB->begin();
  1943. isa<PHINode>(BBI); ++BBI) {
  1944. PHINode *PN = cast<PHINode>(BBI);
  1945. Value *InVal = PN->getIncomingValueForBlock(BB);
  1946. for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
  1947. PN->addIncoming(InVal, BB);
  1948. }
  1949. // Erase the old branch instruction.
  1950. EraseTerminatorInstAndDCECond(BI);
  1951. DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  1952. return true;
  1953. }
  1954. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  1955. // If this is a trivial landing pad that just continues unwinding the caught
  1956. // exception then zap the landing pad, turning its invokes into calls.
  1957. BasicBlock *BB = RI->getParent();
  1958. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  1959. if (RI->getValue() != LPInst)
  1960. // Not a landing pad, or the resume is not unwinding the exception that
  1961. // caused control to branch here.
  1962. return false;
  1963. // Check that there are no other instructions except for debug intrinsics.
  1964. BasicBlock::iterator I = LPInst, E = RI;
  1965. while (++I != E)
  1966. if (!isa<DbgInfoIntrinsic>(I))
  1967. return false;
  1968. // Turn all invokes that unwind here into calls and delete the basic block.
  1969. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  1970. InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
  1971. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  1972. // Insert a call instruction before the invoke.
  1973. CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
  1974. Call->takeName(II);
  1975. Call->setCallingConv(II->getCallingConv());
  1976. Call->setAttributes(II->getAttributes());
  1977. Call->setDebugLoc(II->getDebugLoc());
  1978. // Anything that used the value produced by the invoke instruction now uses
  1979. // the value produced by the call instruction. Note that we do this even
  1980. // for void functions and calls with no uses so that the callgraph edge is
  1981. // updated.
  1982. II->replaceAllUsesWith(Call);
  1983. BB->removePredecessor(II->getParent());
  1984. // Insert a branch to the normal destination right before the invoke.
  1985. BranchInst::Create(II->getNormalDest(), II);
  1986. // Finally, delete the invoke instruction!
  1987. II->eraseFromParent();
  1988. }
  1989. // The landingpad is now unreachable. Zap it.
  1990. BB->eraseFromParent();
  1991. return true;
  1992. }
  1993. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  1994. BasicBlock *BB = RI->getParent();
  1995. if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
  1996. // Find predecessors that end with branches.
  1997. SmallVector<BasicBlock*, 8> UncondBranchPreds;
  1998. SmallVector<BranchInst*, 8> CondBranchPreds;
  1999. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2000. BasicBlock *P = *PI;
  2001. TerminatorInst *PTI = P->getTerminator();
  2002. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  2003. if (BI->isUnconditional())
  2004. UncondBranchPreds.push_back(P);
  2005. else
  2006. CondBranchPreds.push_back(BI);
  2007. }
  2008. }
  2009. // If we found some, do the transformation!
  2010. if (!UncondBranchPreds.empty() && DupRet) {
  2011. while (!UncondBranchPreds.empty()) {
  2012. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  2013. DEBUG(dbgs() << "FOLDING: " << *BB
  2014. << "INTO UNCOND BRANCH PRED: " << *Pred);
  2015. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  2016. }
  2017. // If we eliminated all predecessors of the block, delete the block now.
  2018. if (pred_begin(BB) == pred_end(BB))
  2019. // We know there are no successors, so just nuke the block.
  2020. BB->eraseFromParent();
  2021. return true;
  2022. }
  2023. // Check out all of the conditional branches going to this return
  2024. // instruction. If any of them just select between returns, change the
  2025. // branch itself into a select/return pair.
  2026. while (!CondBranchPreds.empty()) {
  2027. BranchInst *BI = CondBranchPreds.pop_back_val();
  2028. // Check to see if the non-BB successor is also a return block.
  2029. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  2030. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  2031. SimplifyCondBranchToTwoReturns(BI, Builder))
  2032. return true;
  2033. }
  2034. return false;
  2035. }
  2036. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  2037. BasicBlock *BB = UI->getParent();
  2038. bool Changed = false;
  2039. // If there are any instructions immediately before the unreachable that can
  2040. // be removed, do so.
  2041. while (UI != BB->begin()) {
  2042. BasicBlock::iterator BBI = UI;
  2043. --BBI;
  2044. // Do not delete instructions that can have side effects which might cause
  2045. // the unreachable to not be reachable; specifically, calls and volatile
  2046. // operations may have this effect.
  2047. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
  2048. if (BBI->mayHaveSideEffects()) {
  2049. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  2050. if (SI->isVolatile())
  2051. break;
  2052. } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  2053. if (LI->isVolatile())
  2054. break;
  2055. } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  2056. if (RMWI->isVolatile())
  2057. break;
  2058. } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  2059. if (CXI->isVolatile())
  2060. break;
  2061. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  2062. !isa<LandingPadInst>(BBI)) {
  2063. break;
  2064. }
  2065. // Note that deleting LandingPad's here is in fact okay, although it
  2066. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  2067. // all the predecessors of this block will be the unwind edges of Invokes,
  2068. // and we can therefore guarantee this block will be erased.
  2069. }
  2070. // Delete this instruction (any uses are guaranteed to be dead)
  2071. if (!BBI->use_empty())
  2072. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  2073. BBI->eraseFromParent();
  2074. Changed = true;
  2075. }
  2076. // If the unreachable instruction is the first in the block, take a gander
  2077. // at all of the predecessors of this instruction, and simplify them.
  2078. if (&BB->front() != UI) return Changed;
  2079. SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
  2080. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  2081. TerminatorInst *TI = Preds[i]->getTerminator();
  2082. IRBuilder<> Builder(TI);
  2083. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2084. if (BI->isUnconditional()) {
  2085. if (BI->getSuccessor(0) == BB) {
  2086. new UnreachableInst(TI->getContext(), TI);
  2087. TI->eraseFromParent();
  2088. Changed = true;
  2089. }
  2090. } else {
  2091. if (BI->getSuccessor(0) == BB) {
  2092. Builder.CreateBr(BI->getSuccessor(1));
  2093. EraseTerminatorInstAndDCECond(BI);
  2094. } else if (BI->getSuccessor(1) == BB) {
  2095. Builder.CreateBr(BI->getSuccessor(0));
  2096. EraseTerminatorInstAndDCECond(BI);
  2097. Changed = true;
  2098. }
  2099. }
  2100. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2101. for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
  2102. if (SI->getCaseSuccessor(i) == BB) {
  2103. BB->removePredecessor(SI->getParent());
  2104. SI->removeCase(i);
  2105. --i; --e;
  2106. Changed = true;
  2107. }
  2108. // If the default value is unreachable, figure out the most popular
  2109. // destination and make it the default.
  2110. if (SI->getDefaultDest() == BB) {
  2111. std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
  2112. for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
  2113. std::pair<unsigned, unsigned> &entry =
  2114. Popularity[SI->getCaseSuccessor(i)];
  2115. if (entry.first == 0) {
  2116. entry.first = 1;
  2117. entry.second = i;
  2118. } else {
  2119. entry.first++;
  2120. }
  2121. }
  2122. // Find the most popular block.
  2123. unsigned MaxPop = 0;
  2124. unsigned MaxIndex = 0;
  2125. BasicBlock *MaxBlock = 0;
  2126. for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
  2127. I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
  2128. if (I->second.first > MaxPop ||
  2129. (I->second.first == MaxPop && MaxIndex > I->second.second)) {
  2130. MaxPop = I->second.first;
  2131. MaxIndex = I->second.second;
  2132. MaxBlock = I->first;
  2133. }
  2134. }
  2135. if (MaxBlock) {
  2136. // Make this the new default, allowing us to delete any explicit
  2137. // edges to it.
  2138. SI->setDefaultDest(MaxBlock);
  2139. Changed = true;
  2140. // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
  2141. // it.
  2142. if (isa<PHINode>(MaxBlock->begin()))
  2143. for (unsigned i = 0; i != MaxPop-1; ++i)
  2144. MaxBlock->removePredecessor(SI->getParent());
  2145. for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
  2146. if (SI->getCaseSuccessor(i) == MaxBlock) {
  2147. SI->removeCase(i);
  2148. --i; --e;
  2149. }
  2150. }
  2151. }
  2152. } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
  2153. if (II->getUnwindDest() == BB) {
  2154. // Convert the invoke to a call instruction. This would be a good
  2155. // place to note that the call does not throw though.
  2156. BranchInst *BI = Builder.CreateBr(II->getNormalDest());
  2157. II->removeFromParent(); // Take out of symbol table
  2158. // Insert the call now...
  2159. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
  2160. Builder.SetInsertPoint(BI);
  2161. CallInst *CI = Builder.CreateCall(II->getCalledValue(),
  2162. Args, II->getName());
  2163. CI->setCallingConv(II->getCallingConv());
  2164. CI->setAttributes(II->getAttributes());
  2165. // If the invoke produced a value, the call does now instead.
  2166. II->replaceAllUsesWith(CI);
  2167. delete II;
  2168. Changed = true;
  2169. }
  2170. }
  2171. }
  2172. // If this block is now dead, remove it.
  2173. if (pred_begin(BB) == pred_end(BB) &&
  2174. BB != &BB->getParent()->getEntryBlock()) {
  2175. // We know there are no successors, so just nuke the block.
  2176. BB->eraseFromParent();
  2177. return true;
  2178. }
  2179. return Changed;
  2180. }
  2181. /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
  2182. /// integer range comparison into a sub, an icmp and a branch.
  2183. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  2184. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  2185. // Make sure all cases point to the same destination and gather the values.
  2186. SmallVector<ConstantInt *, 16> Cases;
  2187. Cases.push_back(SI->getCaseValue(0));
  2188. for (unsigned I = 1, E = SI->getNumCases(); I != E; ++I) {
  2189. if (SI->getCaseSuccessor(I-1) != SI->getCaseSuccessor(I))
  2190. return false;
  2191. Cases.push_back(SI->getCaseValue(I));
  2192. }
  2193. assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
  2194. // Sort the case values, then check if they form a range we can transform.
  2195. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  2196. for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
  2197. if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
  2198. return false;
  2199. }
  2200. Constant *Offset = ConstantExpr::getNeg(Cases.back());
  2201. Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
  2202. Value *Sub = SI->getCondition();
  2203. if (!Offset->isNullValue())
  2204. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
  2205. Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  2206. Builder.CreateCondBr(Cmp, SI->getCaseSuccessor(0), SI->getDefaultDest());
  2207. // Prune obsolete incoming values off the successor's PHI nodes.
  2208. for (BasicBlock::iterator BBI = SI->getCaseSuccessor(0)->begin();
  2209. isa<PHINode>(BBI); ++BBI) {
  2210. for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
  2211. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2212. }
  2213. SI->eraseFromParent();
  2214. return true;
  2215. }
  2216. /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
  2217. /// and use it to remove dead cases.
  2218. static bool EliminateDeadSwitchCases(SwitchInst *SI) {
  2219. Value *Cond = SI->getCondition();
  2220. unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
  2221. APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
  2222. ComputeMaskedBits(Cond, APInt::getAllOnesValue(Bits), KnownZero, KnownOne);
  2223. // Gather dead cases.
  2224. SmallVector<ConstantInt*, 8> DeadCases;
  2225. for (unsigned I = 0, E = SI->getNumCases(); I != E; ++I) {
  2226. if ((SI->getCaseValue(I)->getValue() & KnownZero) != 0 ||
  2227. (SI->getCaseValue(I)->getValue() & KnownOne) != KnownOne) {
  2228. DeadCases.push_back(SI->getCaseValue(I));
  2229. DEBUG(dbgs() << "SimplifyCFG: switch case '"
  2230. << SI->getCaseValue(I)->getValue() << "' is dead.\n");
  2231. }
  2232. }
  2233. // Remove dead cases from the switch.
  2234. for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
  2235. unsigned Case = SI->findCaseValue(DeadCases[I]);
  2236. assert(Case != SwitchInst::ErrorIndex &&
  2237. "Case was not found. Probably mistake in DeadCases forming.");
  2238. // Prune unused values from PHI nodes.
  2239. SI->getCaseSuccessor(Case)->removePredecessor(SI->getParent());
  2240. SI->removeCase(Case);
  2241. }
  2242. return !DeadCases.empty();
  2243. }
  2244. /// FindPHIForConditionForwarding - If BB would be eligible for simplification
  2245. /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  2246. /// by an unconditional branch), look at the phi node for BB in the successor
  2247. /// block and see if the incoming value is equal to CaseValue. If so, return
  2248. /// the phi node, and set PhiIndex to BB's index in the phi node.
  2249. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  2250. BasicBlock *BB,
  2251. int *PhiIndex) {
  2252. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  2253. return NULL; // BB must be empty to be a candidate for simplification.
  2254. if (!BB->getSinglePredecessor())
  2255. return NULL; // BB must be dominated by the switch.
  2256. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  2257. if (!Branch || !Branch->isUnconditional())
  2258. return NULL; // Terminator must be unconditional branch.
  2259. BasicBlock *Succ = Branch->getSuccessor(0);
  2260. BasicBlock::iterator I = Succ->begin();
  2261. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  2262. int Idx = PHI->getBasicBlockIndex(BB);
  2263. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  2264. Value *InValue = PHI->getIncomingValue(Idx);
  2265. if (InValue != CaseValue) continue;
  2266. *PhiIndex = Idx;
  2267. return PHI;
  2268. }
  2269. return NULL;
  2270. }
  2271. /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
  2272. /// instruction to a phi node dominated by the switch, if that would mean that
  2273. /// some of the destination blocks of the switch can be folded away.
  2274. /// Returns true if a change is made.
  2275. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  2276. typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
  2277. ForwardingNodesMap ForwardingNodes;
  2278. for (unsigned I = 0; I < SI->getNumCases(); ++I) { // 0 is the default case.
  2279. ConstantInt *CaseValue = SI->getCaseValue(I);
  2280. BasicBlock *CaseDest = SI->getCaseSuccessor(I);
  2281. int PhiIndex;
  2282. PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
  2283. &PhiIndex);
  2284. if (!PHI) continue;
  2285. ForwardingNodes[PHI].push_back(PhiIndex);
  2286. }
  2287. bool Changed = false;
  2288. for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
  2289. E = ForwardingNodes.end(); I != E; ++I) {
  2290. PHINode *Phi = I->first;
  2291. SmallVector<int,4> &Indexes = I->second;
  2292. if (Indexes.size() < 2) continue;
  2293. for (size_t I = 0, E = Indexes.size(); I != E; ++I)
  2294. Phi->setIncomingValue(Indexes[I], SI->getCondition());
  2295. Changed = true;
  2296. }
  2297. return Changed;
  2298. }
  2299. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  2300. // If this switch is too complex to want to look at, ignore it.
  2301. if (!isValueEqualityComparison(SI))
  2302. return false;
  2303. BasicBlock *BB = SI->getParent();
  2304. // If we only have one predecessor, and if it is a branch on this value,
  2305. // see if that predecessor totally determines the outcome of this switch.
  2306. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  2307. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  2308. return SimplifyCFG(BB) | true;
  2309. Value *Cond = SI->getCondition();
  2310. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  2311. if (SimplifySwitchOnSelect(SI, Select))
  2312. return SimplifyCFG(BB) | true;
  2313. // If the block only contains the switch, see if we can fold the block
  2314. // away into any preds.
  2315. BasicBlock::iterator BBI = BB->begin();
  2316. // Ignore dbg intrinsics.
  2317. while (isa<DbgInfoIntrinsic>(BBI))
  2318. ++BBI;
  2319. if (SI == &*BBI)
  2320. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  2321. return SimplifyCFG(BB) | true;
  2322. // Try to transform the switch into an icmp and a branch.
  2323. if (TurnSwitchRangeIntoICmp(SI, Builder))
  2324. return SimplifyCFG(BB) | true;
  2325. // Remove unreachable cases.
  2326. if (EliminateDeadSwitchCases(SI))
  2327. return SimplifyCFG(BB) | true;
  2328. if (ForwardSwitchConditionToPHI(SI))
  2329. return SimplifyCFG(BB) | true;
  2330. return false;
  2331. }
  2332. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  2333. BasicBlock *BB = IBI->getParent();
  2334. bool Changed = false;
  2335. // Eliminate redundant destinations.
  2336. SmallPtrSet<Value *, 8> Succs;
  2337. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  2338. BasicBlock *Dest = IBI->getDestination(i);
  2339. if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
  2340. Dest->removePredecessor(BB);
  2341. IBI->removeDestination(i);
  2342. --i; --e;
  2343. Changed = true;
  2344. }
  2345. }
  2346. if (IBI->getNumDestinations() == 0) {
  2347. // If the indirectbr has no successors, change it to unreachable.
  2348. new UnreachableInst(IBI->getContext(), IBI);
  2349. EraseTerminatorInstAndDCECond(IBI);
  2350. return true;
  2351. }
  2352. if (IBI->getNumDestinations() == 1) {
  2353. // If the indirectbr has one successor, change it to a direct branch.
  2354. BranchInst::Create(IBI->getDestination(0), IBI);
  2355. EraseTerminatorInstAndDCECond(IBI);
  2356. return true;
  2357. }
  2358. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  2359. if (SimplifyIndirectBrOnSelect(IBI, SI))
  2360. return SimplifyCFG(BB) | true;
  2361. }
  2362. return Changed;
  2363. }
  2364. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
  2365. BasicBlock *BB = BI->getParent();
  2366. // If the Terminator is the only non-phi instruction, simplify the block.
  2367. BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
  2368. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  2369. TryToSimplifyUncondBranchFromEmptyBlock(BB))
  2370. return true;
  2371. // If the only instruction in the block is a seteq/setne comparison
  2372. // against a constant, try to simplify the block.
  2373. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  2374. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  2375. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  2376. ;
  2377. if (I->isTerminator() &&
  2378. TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
  2379. return true;
  2380. }
  2381. return false;
  2382. }
  2383. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  2384. BasicBlock *BB = BI->getParent();
  2385. // Conditional branch
  2386. if (isValueEqualityComparison(BI)) {
  2387. // If we only have one predecessor, and if it is a branch on this value,
  2388. // see if that predecessor totally determines the outcome of this
  2389. // switch.
  2390. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  2391. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  2392. return SimplifyCFG(BB) | true;
  2393. // This block must be empty, except for the setcond inst, if it exists.
  2394. // Ignore dbg intrinsics.
  2395. BasicBlock::iterator I = BB->begin();
  2396. // Ignore dbg intrinsics.
  2397. while (isa<DbgInfoIntrinsic>(I))
  2398. ++I;
  2399. if (&*I == BI) {
  2400. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  2401. return SimplifyCFG(BB) | true;
  2402. } else if (&*I == cast<Instruction>(BI->getCondition())){
  2403. ++I;
  2404. // Ignore dbg intrinsics.
  2405. while (isa<DbgInfoIntrinsic>(I))
  2406. ++I;
  2407. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  2408. return SimplifyCFG(BB) | true;
  2409. }
  2410. }
  2411. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  2412. if (SimplifyBranchOnICmpChain(BI, TD, Builder))
  2413. return true;
  2414. // If this basic block is ONLY a compare and a branch, and if a predecessor
  2415. // branches to us and one of our successors, fold the comparison into the
  2416. // predecessor and use logical operations to pick the right destination.
  2417. if (FoldBranchToCommonDest(BI))
  2418. return SimplifyCFG(BB) | true;
  2419. // We have a conditional branch to two blocks that are only reachable
  2420. // from BI. We know that the condbr dominates the two blocks, so see if
  2421. // there is any identical code in the "then" and "else" blocks. If so, we
  2422. // can hoist it up to the branching block.
  2423. if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
  2424. if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
  2425. if (HoistThenElseCodeToIf(BI))
  2426. return SimplifyCFG(BB) | true;
  2427. } else {
  2428. // If Successor #1 has multiple preds, we may be able to conditionally
  2429. // execute Successor #0 if it branches to successor #1.
  2430. TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
  2431. if (Succ0TI->getNumSuccessors() == 1 &&
  2432. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  2433. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
  2434. return SimplifyCFG(BB) | true;
  2435. }
  2436. } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
  2437. // If Successor #0 has multiple preds, we may be able to conditionally
  2438. // execute Successor #1 if it branches to successor #0.
  2439. TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
  2440. if (Succ1TI->getNumSuccessors() == 1 &&
  2441. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  2442. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
  2443. return SimplifyCFG(BB) | true;
  2444. }
  2445. // If this is a branch on a phi node in the current block, thread control
  2446. // through this block if any PHI node entries are constants.
  2447. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  2448. if (PN->getParent() == BI->getParent())
  2449. if (FoldCondBranchOnPHI(BI, TD))
  2450. return SimplifyCFG(BB) | true;
  2451. // Scan predecessor blocks for conditional branches.
  2452. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  2453. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  2454. if (PBI != BI && PBI->isConditional())
  2455. if (SimplifyCondBranchToCondBranch(PBI, BI))
  2456. return SimplifyCFG(BB) | true;
  2457. return false;
  2458. }
  2459. /// Check if passing a value to an instruction will cause undefined behavior.
  2460. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  2461. Constant *C = dyn_cast<Constant>(V);
  2462. if (!C)
  2463. return false;
  2464. if (!I->hasOneUse()) // Only look at single-use instructions, for compile time
  2465. return false;
  2466. if (C->isNullValue()) {
  2467. Instruction *Use = I->use_back();
  2468. // Now make sure that there are no instructions in between that can alter
  2469. // control flow (eg. calls)
  2470. for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
  2471. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  2472. return false;
  2473. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  2474. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  2475. if (GEP->getPointerOperand() == I)
  2476. return passingValueIsAlwaysUndefined(V, GEP);
  2477. // Look through bitcasts.
  2478. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  2479. return passingValueIsAlwaysUndefined(V, BC);
  2480. // Load from null is undefined.
  2481. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  2482. return LI->getPointerAddressSpace() == 0;
  2483. // Store to null is undefined.
  2484. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  2485. return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
  2486. }
  2487. return false;
  2488. }
  2489. /// If BB has an incoming value that will always trigger undefined behavior
  2490. /// (eg. null pointer dereference), remove the branch leading here.
  2491. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  2492. for (BasicBlock::iterator i = BB->begin();
  2493. PHINode *PHI = dyn_cast<PHINode>(i); ++i)
  2494. for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
  2495. if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
  2496. TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
  2497. IRBuilder<> Builder(T);
  2498. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  2499. BB->removePredecessor(PHI->getIncomingBlock(i));
  2500. // Turn uncoditional branches into unreachables and remove the dead
  2501. // destination from conditional branches.
  2502. if (BI->isUnconditional())
  2503. Builder.CreateUnreachable();
  2504. else
  2505. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
  2506. BI->getSuccessor(0));
  2507. BI->eraseFromParent();
  2508. return true;
  2509. }
  2510. // TODO: SwitchInst.
  2511. }
  2512. return false;
  2513. }
  2514. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  2515. bool Changed = false;
  2516. assert(BB && BB->getParent() && "Block not embedded in function!");
  2517. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  2518. // Remove basic blocks that have no predecessors (except the entry block)...
  2519. // or that just have themself as a predecessor. These are unreachable.
  2520. if ((pred_begin(BB) == pred_end(BB) &&
  2521. BB != &BB->getParent()->getEntryBlock()) ||
  2522. BB->getSinglePredecessor() == BB) {
  2523. DEBUG(dbgs() << "Removing BB: \n" << *BB);
  2524. DeleteDeadBlock(BB);
  2525. return true;
  2526. }
  2527. // Check to see if we can constant propagate this terminator instruction
  2528. // away...
  2529. Changed |= ConstantFoldTerminator(BB, true);
  2530. // Check for and eliminate duplicate PHI nodes in this block.
  2531. Changed |= EliminateDuplicatePHINodes(BB);
  2532. // Check for and remove branches that will always cause undefined behavior.
  2533. Changed |= removeUndefIntroducingPredecessor(BB);
  2534. // Merge basic blocks into their predecessor if there is only one distinct
  2535. // pred, and if there is only one distinct successor of the predecessor, and
  2536. // if there are no PHI nodes.
  2537. //
  2538. if (MergeBlockIntoPredecessor(BB))
  2539. return true;
  2540. IRBuilder<> Builder(BB);
  2541. // If there is a trivial two-entry PHI node in this basic block, and we can
  2542. // eliminate it, do so now.
  2543. if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
  2544. if (PN->getNumIncomingValues() == 2)
  2545. Changed |= FoldTwoEntryPHINode(PN, TD);
  2546. Builder.SetInsertPoint(BB->getTerminator());
  2547. if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  2548. if (BI->isUnconditional()) {
  2549. if (SimplifyUncondBranch(BI, Builder)) return true;
  2550. } else {
  2551. if (SimplifyCondBranch(BI, Builder)) return true;
  2552. }
  2553. } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  2554. if (SimplifyReturn(RI, Builder)) return true;
  2555. } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  2556. if (SimplifyResume(RI, Builder)) return true;
  2557. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  2558. if (SimplifySwitch(SI, Builder)) return true;
  2559. } else if (UnreachableInst *UI =
  2560. dyn_cast<UnreachableInst>(BB->getTerminator())) {
  2561. if (SimplifyUnreachable(UI)) return true;
  2562. } else if (IndirectBrInst *IBI =
  2563. dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  2564. if (SimplifyIndirectBr(IBI)) return true;
  2565. }
  2566. return Changed;
  2567. }
  2568. /// SimplifyCFG - This function is used to do simplification of a CFG. For
  2569. /// example, it adjusts branches to branches to eliminate the extra hop, it
  2570. /// eliminates unreachable basic blocks, and does other "peephole" optimization
  2571. /// of the CFG. It returns true if a modification was made.
  2572. ///
  2573. bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
  2574. return SimplifyCFGOpt(TD).run(BB);
  2575. }