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