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