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