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" |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 18 | #include "llvm/Type.h" |
Reid Spencer | c103057 | 2007-01-19 21:13:56 +0000 | [diff] [blame] | 19 | #include "llvm/DerivedTypes.h" |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 20 | #include "llvm/Support/CFG.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 21 | #include "llvm/Support/Debug.h" |
Chris Lattner | 79066fa | 2007-01-30 23:46:24 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 23 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Chris Lattner | 93e985f | 2007-02-13 02:10:56 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/SmallVector.h" |
Chris Lattner | c995123 | 2007-04-02 01:44:59 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/SmallPtrSet.h" |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 26 | #include <algorithm> |
| 27 | #include <functional> |
Chris Lattner | d52c261 | 2004-02-24 07:23:58 +0000 | [diff] [blame] | 28 | #include <set> |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 29 | #include <map> |
Chris Lattner | f7703df | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 30 | using namespace llvm; |
Brian Gaeke | d0fde30 | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 31 | |
Chris Lattner | 2bdcb56 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 32 | /// SafeToMergeTerminators - Return true if it is safe to merge these two |
| 33 | /// terminator instructions together. |
| 34 | /// |
| 35 | static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { |
| 36 | if (SI1 == SI2) return false; // Can't merge with self! |
| 37 | |
| 38 | // It is not safe to merge these two switch instructions if they have a common |
| 39 | // successor, and if that successor has a PHI node, and if *that* PHI node has |
| 40 | // conflicting incoming values from the two switch blocks. |
| 41 | BasicBlock *SI1BB = SI1->getParent(); |
| 42 | BasicBlock *SI2BB = SI2->getParent(); |
Chris Lattner | c995123 | 2007-04-02 01:44:59 +0000 | [diff] [blame] | 43 | SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Chris Lattner | 2bdcb56 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 44 | |
| 45 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 46 | if (SI1Succs.count(*I)) |
| 47 | for (BasicBlock::iterator BBI = (*I)->begin(); |
| 48 | isa<PHINode>(BBI); ++BBI) { |
| 49 | PHINode *PN = cast<PHINode>(BBI); |
| 50 | if (PN->getIncomingValueForBlock(SI1BB) != |
| 51 | PN->getIncomingValueForBlock(SI2BB)) |
| 52 | return false; |
| 53 | } |
| 54 | |
| 55 | return true; |
| 56 | } |
| 57 | |
| 58 | /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will |
| 59 | /// now be entries in it from the 'NewPred' block. The values that will be |
| 60 | /// flowing into the PHI nodes will be the same as those coming in from |
| 61 | /// ExistPred, an existing predecessor of Succ. |
| 62 | static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| 63 | BasicBlock *ExistPred) { |
| 64 | assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) != |
| 65 | succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!"); |
| 66 | if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do |
| 67 | |
| 68 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 69 | PHINode *PN = cast<PHINode>(I); |
| 70 | Value *V = PN->getIncomingValueForBlock(ExistPred); |
| 71 | PN->addIncoming(V, NewPred); |
| 72 | } |
| 73 | } |
| 74 | |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 75 | // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an |
| 76 | // almost-empty BB ending in an unconditional branch to Succ, into succ. |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 77 | // |
| 78 | // Assumption: Succ is the single successor for BB. |
| 79 | // |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 80 | static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 81 | assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); |
Chris Lattner | 3abb95d | 2002-09-24 00:09:26 +0000 | [diff] [blame] | 82 | |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 83 | DOUT << "Looking to fold " << BB->getNameStart() << " into " |
| 84 | << Succ->getNameStart() << "\n"; |
| 85 | // Shortcut, if there is only a single predecessor is must be BB and merging |
| 86 | // is always safe |
| 87 | if (Succ->getSinglePredecessor()) return true; |
| 88 | |
| 89 | typedef SmallPtrSet<Instruction*, 16> InstrSet; |
| 90 | InstrSet BBPHIs; |
| 91 | |
| 92 | // Make a list of all phi nodes in BB |
| 93 | BasicBlock::iterator BBI = BB->begin(); |
| 94 | while (isa<PHINode>(*BBI)) BBPHIs.insert(BBI++); |
| 95 | |
| 96 | // Make a list of the predecessors of BB |
| 97 | typedef SmallPtrSet<BasicBlock*, 16> BlockSet; |
| 98 | BlockSet BBPreds(pred_begin(BB), pred_end(BB)); |
| 99 | |
| 100 | // Use that list to make another list of common predecessors of BB and Succ |
| 101 | BlockSet CommonPreds; |
| 102 | for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); |
| 103 | PI != PE; ++PI) |
| 104 | if (BBPreds.count(*PI)) |
| 105 | CommonPreds.insert(*PI); |
| 106 | |
| 107 | // Shortcut, if there are no common predecessors, merging is always safe |
| 108 | if (CommonPreds.begin() == CommonPreds.end()) |
| 109 | return true; |
| 110 | |
| 111 | // Look at all the phi nodes in Succ, to see if they present a conflict when |
| 112 | // merging these blocks |
| 113 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 114 | PHINode *PN = cast<PHINode>(I); |
| 115 | |
| 116 | // If the incoming value from BB is again a PHINode in |
| 117 | // BB which has the same incoming value for *PI as PN does, we can |
| 118 | // merge the phi nodes and then the blocks can still be merged |
| 119 | PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB)); |
| 120 | if (BBPN && BBPN->getParent() == BB) { |
| 121 | for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end(); |
| 122 | PI != PE; PI++) { |
| 123 | if (BBPN->getIncomingValueForBlock(*PI) |
| 124 | != PN->getIncomingValueForBlock(*PI)) { |
| 125 | DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in " |
| 126 | << Succ->getNameStart() << " is conflicting with " |
| 127 | << BBPN->getNameStart() << " with regard to common predecessor " |
| 128 | << (*PI)->getNameStart() << "\n"; |
| 129 | return false; |
Chris Lattner | dc88dbe | 2005-08-03 00:38:27 +0000 | [diff] [blame] | 130 | } |
| 131 | } |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 132 | // Remove this phinode from the list of phis in BB, since it has been |
| 133 | // handled. |
| 134 | BBPHIs.erase(BBPN); |
| 135 | } else { |
| 136 | Value* Val = PN->getIncomingValueForBlock(BB); |
| 137 | for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end(); |
| 138 | PI != PE; PI++) { |
| 139 | // See if the incoming value for the common predecessor is equal to the |
| 140 | // one for BB, in which case this phi node will not prevent the merging |
| 141 | // of the block. |
| 142 | if (Val != PN->getIncomingValueForBlock(*PI)) { |
| 143 | DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in " |
| 144 | << Succ->getNameStart() << " is conflicting with regard to common " |
| 145 | << "predecessor " << (*PI)->getNameStart() << "\n"; |
| 146 | return false; |
| 147 | } |
| 148 | } |
Chris Lattner | 1aad921 | 2005-08-03 00:59:12 +0000 | [diff] [blame] | 149 | } |
Chris Lattner | 1aad921 | 2005-08-03 00:59:12 +0000 | [diff] [blame] | 150 | } |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 151 | |
| 152 | // If there are any other phi nodes in BB that don't have a phi node in Succ |
| 153 | // to merge with, they must be moved to Succ completely. However, for any |
| 154 | // predecessors of Succ, branches will be added to the phi node that just |
| 155 | // point to itself. So, for any common predecessors, this must not cause |
| 156 | // conflicts. |
| 157 | for (InstrSet::iterator I = BBPHIs.begin(), E = BBPHIs.end(); |
| 158 | I != E; I++) { |
| 159 | PHINode *PN = cast<PHINode>(*I); |
| 160 | for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end(); |
| 161 | PI != PE; PI++) |
| 162 | if (PN->getIncomingValueForBlock(*PI) != PN) { |
| 163 | DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in " |
| 164 | << BB->getNameStart() << " is conflicting with regard to common " |
| 165 | << "predecessor " << (*PI)->getNameStart() << "\n"; |
| 166 | return false; |
| 167 | } |
| 168 | } |
| 169 | |
Chris Lattner | 8e75ee2 | 2005-12-03 18:25:58 +0000 | [diff] [blame] | 170 | return true; |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 171 | } |
| 172 | |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 173 | /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional |
| 174 | /// branch to Succ, and contains no instructions other than PHI nodes and the |
| 175 | /// branch. If possible, eliminate BB. |
| 176 | static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, |
| 177 | BasicBlock *Succ) { |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 178 | // Check to see if merging these blocks would cause conflicts for any of the |
| 179 | // phi nodes in BB or Succ. If not, we can safely merge. |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 180 | if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 181 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 182 | DOUT << "Killing Trivial BB: \n" << *BB; |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 183 | |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 184 | if (isa<PHINode>(Succ->begin())) { |
| 185 | // If there is more than one pred of succ, and there are PHI nodes in |
| 186 | // the successor, then we need to add incoming edges for the PHI nodes |
| 187 | // |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 188 | const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 189 | |
| 190 | // Loop over all of the PHI nodes in the successor of BB. |
| 191 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 192 | PHINode *PN = cast<PHINode>(I); |
| 193 | Value *OldVal = PN->removeIncomingValue(BB, false); |
| 194 | assert(OldVal && "No entry in PHI for Pred BB!"); |
| 195 | |
Chris Lattner | dc88dbe | 2005-08-03 00:38:27 +0000 | [diff] [blame] | 196 | // If this incoming value is one of the PHI nodes in BB, the new entries |
| 197 | // in the PHI node are the entries from the old PHI. |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 198 | if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { |
| 199 | PHINode *OldValPN = cast<PHINode>(OldVal); |
| 200 | for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 201 | // Note that, since we are merging phi nodes and BB and Succ might |
| 202 | // have common predecessors, we could end up with a phi node with |
| 203 | // identical incoming branches. This will be cleaned up later (and |
| 204 | // will trigger asserts if we try to clean it up now, without also |
| 205 | // simplifying the corresponding conditional branch). |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 206 | PN->addIncoming(OldValPN->getIncomingValue(i), |
| 207 | OldValPN->getIncomingBlock(i)); |
| 208 | } else { |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 209 | // Add an incoming value for each of the new incoming values. |
| 210 | for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) |
| 211 | PN->addIncoming(OldVal, BBPreds[i]); |
Chris Lattner | 3b3efc7 | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 216 | if (isa<PHINode>(&BB->front())) { |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 217 | SmallVector<BasicBlock*, 16> |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 218 | OldSuccPreds(pred_begin(Succ), pred_end(Succ)); |
| 219 | |
| 220 | // Move all PHI nodes in BB to Succ if they are alive, otherwise |
| 221 | // delete them. |
| 222 | while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) |
Chris Lattner | dc88dbe | 2005-08-03 00:38:27 +0000 | [diff] [blame] | 223 | if (PN->use_empty()) { |
| 224 | // Just remove the dead phi. This happens if Succ's PHIs were the only |
| 225 | // users of the PHI nodes. |
| 226 | PN->eraseFromParent(); |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 227 | } else { |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 228 | // The instruction is alive, so this means that BB must dominate all |
| 229 | // predecessors of Succ (Since all uses of the PN are after its |
| 230 | // definition, so in Succ or a block dominated by Succ. If a predecessor |
| 231 | // of Succ would not be dominated by BB, PN would violate the def before |
| 232 | // use SSA demand). Therefore, we can simply move the phi node to the |
| 233 | // next block. |
Chris Lattner | d423b8b | 2005-08-03 00:23:42 +0000 | [diff] [blame] | 234 | Succ->getInstList().splice(Succ->begin(), |
| 235 | BB->getInstList(), BB->begin()); |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 236 | |
| 237 | // We need to add new entries for the PHI node to account for |
| 238 | // predecessors of Succ that the PHI node does not take into |
Matthijs Kooijman | 5e179a2 | 2008-05-23 09:09:41 +0000 | [diff] [blame] | 239 | // account. At this point, since we know that BB dominated succ and all |
| 240 | // of its predecessors, this means that we should any newly added |
| 241 | // incoming edges should use the PHI node itself as the value for these |
| 242 | // edges, because they are loop back edges. |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 243 | for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i) |
| 244 | if (OldSuccPreds[i] != BB) |
| 245 | PN->addIncoming(PN, OldSuccPreds[i]); |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // Everything that jumped to BB now goes to Succ. |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 250 | BB->replaceAllUsesWith(Succ); |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 251 | if (!Succ->hasName()) Succ->takeName(BB); |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 252 | BB->eraseFromParent(); // Delete the old basic block. |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 253 | return true; |
| 254 | } |
| 255 | |
Chris Lattner | 723c66d | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 256 | /// GetIfCondition - Given a basic block (BB) with two predecessors (and |
| 257 | /// presumably PHI nodes in it), check to see if the merge at this block is due |
| 258 | /// to an "if condition". If so, return the boolean condition that determines |
| 259 | /// which entry into BB will be taken. Also, return by references the block |
| 260 | /// that will be entered from if the condition is true, and the block that will |
| 261 | /// be entered if the condition is false. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 262 | /// |
Chris Lattner | 723c66d | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 263 | /// |
| 264 | static Value *GetIfCondition(BasicBlock *BB, |
| 265 | BasicBlock *&IfTrue, BasicBlock *&IfFalse) { |
| 266 | assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 && |
| 267 | "Function can only handle blocks with 2 predecessors!"); |
| 268 | BasicBlock *Pred1 = *pred_begin(BB); |
| 269 | BasicBlock *Pred2 = *++pred_begin(BB); |
| 270 | |
| 271 | // We can only handle branches. Other control flow will be lowered to |
| 272 | // branches if possible anyway. |
| 273 | if (!isa<BranchInst>(Pred1->getTerminator()) || |
| 274 | !isa<BranchInst>(Pred2->getTerminator())) |
| 275 | return 0; |
| 276 | BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator()); |
| 277 | BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator()); |
| 278 | |
| 279 | // Eliminate code duplication by ensuring that Pred1Br is conditional if |
| 280 | // either are. |
| 281 | if (Pred2Br->isConditional()) { |
| 282 | // If both branches are conditional, we don't have an "if statement". In |
| 283 | // reality, we could transform this case, but since the condition will be |
| 284 | // required anyway, we stand no chance of eliminating it, so the xform is |
| 285 | // probably not profitable. |
| 286 | if (Pred1Br->isConditional()) |
| 287 | return 0; |
| 288 | |
| 289 | std::swap(Pred1, Pred2); |
| 290 | std::swap(Pred1Br, Pred2Br); |
| 291 | } |
| 292 | |
| 293 | if (Pred1Br->isConditional()) { |
| 294 | // If we found a conditional branch predecessor, make sure that it branches |
| 295 | // to BB and Pred2Br. If it doesn't, this isn't an "if statement". |
| 296 | if (Pred1Br->getSuccessor(0) == BB && |
| 297 | Pred1Br->getSuccessor(1) == Pred2) { |
| 298 | IfTrue = Pred1; |
| 299 | IfFalse = Pred2; |
| 300 | } else if (Pred1Br->getSuccessor(0) == Pred2 && |
| 301 | Pred1Br->getSuccessor(1) == BB) { |
| 302 | IfTrue = Pred2; |
| 303 | IfFalse = Pred1; |
| 304 | } else { |
| 305 | // We know that one arm of the conditional goes to BB, so the other must |
| 306 | // go somewhere unrelated, and this must not be an "if statement". |
| 307 | return 0; |
| 308 | } |
| 309 | |
| 310 | // The only thing we have to watch out for here is to make sure that Pred2 |
| 311 | // doesn't have incoming edges from other blocks. If it does, the condition |
| 312 | // doesn't dominate BB. |
| 313 | if (++pred_begin(Pred2) != pred_end(Pred2)) |
| 314 | return 0; |
| 315 | |
| 316 | return Pred1Br->getCondition(); |
| 317 | } |
| 318 | |
| 319 | // Ok, if we got here, both predecessors end with an unconditional branch to |
| 320 | // BB. Don't panic! If both blocks only have a single (identical) |
| 321 | // predecessor, and THAT is a conditional branch, then we're all ok! |
| 322 | if (pred_begin(Pred1) == pred_end(Pred1) || |
| 323 | ++pred_begin(Pred1) != pred_end(Pred1) || |
| 324 | pred_begin(Pred2) == pred_end(Pred2) || |
| 325 | ++pred_begin(Pred2) != pred_end(Pred2) || |
| 326 | *pred_begin(Pred1) != *pred_begin(Pred2)) |
| 327 | return 0; |
| 328 | |
| 329 | // Otherwise, if this is a conditional branch, then we can use it! |
| 330 | BasicBlock *CommonPred = *pred_begin(Pred1); |
| 331 | if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) { |
| 332 | assert(BI->isConditional() && "Two successors but not conditional?"); |
| 333 | if (BI->getSuccessor(0) == Pred1) { |
| 334 | IfTrue = Pred1; |
| 335 | IfFalse = Pred2; |
| 336 | } else { |
| 337 | IfTrue = Pred2; |
| 338 | IfFalse = Pred1; |
| 339 | } |
| 340 | return BI->getCondition(); |
| 341 | } |
| 342 | return 0; |
| 343 | } |
| 344 | |
| 345 | |
| 346 | // If we have a merge point of an "if condition" as accepted above, return true |
| 347 | // if the specified value dominates the block. We don't handle the true |
| 348 | // generality of domination here, just a special case which works well enough |
| 349 | // for us. |
Chris Lattner | 9c07866 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 350 | // |
| 351 | // If AggressiveInsts is non-null, and if V does not dominate BB, we check to |
| 352 | // see if V (which must be an instruction) is cheap to compute and is |
| 353 | // non-trapping. If both are true, the instruction is inserted into the set and |
| 354 | // true is returned. |
| 355 | static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
| 356 | std::set<Instruction*> *AggressiveInsts) { |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 357 | Instruction *I = dyn_cast<Instruction>(V); |
Chris Lattner | b74b181 | 2006-10-20 00:42:07 +0000 | [diff] [blame] | 358 | if (!I) { |
| 359 | // Non-instructions all dominate instructions, but not all constantexprs |
| 360 | // can be executed unconditionally. |
| 361 | if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) |
| 362 | if (C->canTrap()) |
| 363 | return false; |
| 364 | return true; |
| 365 | } |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 366 | BasicBlock *PBB = I->getParent(); |
Chris Lattner | 723c66d | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 367 | |
Chris Lattner | da895d6 | 2005-02-27 06:18:25 +0000 | [diff] [blame] | 368 | // 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] | 369 | // the bottom of this block. |
| 370 | if (PBB == BB) return false; |
Chris Lattner | 723c66d | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 371 | |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 372 | // If this instruction is defined in a block that contains an unconditional |
| 373 | // branch to BB, then it must be in the 'conditional' part of the "if |
| 374 | // statement". |
| 375 | if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator())) |
| 376 | if (BI->isUnconditional() && BI->getSuccessor(0) == BB) { |
Chris Lattner | 9c07866 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 377 | if (!AggressiveInsts) return false; |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 378 | // Okay, it looks like the instruction IS in the "condition". Check to |
| 379 | // see if its a cheap instruction to unconditionally compute, and if it |
| 380 | // only uses stuff defined outside of the condition. If so, hoist it out. |
| 381 | switch (I->getOpcode()) { |
| 382 | default: return false; // Cannot hoist this out safely. |
| 383 | case Instruction::Load: |
| 384 | // We can hoist loads that are non-volatile and obviously cannot trap. |
| 385 | if (cast<LoadInst>(I)->isVolatile()) |
| 386 | return false; |
| 387 | if (!isa<AllocaInst>(I->getOperand(0)) && |
Reid Spencer | 460f16c | 2004-07-18 00:32:14 +0000 | [diff] [blame] | 388 | !isa<Constant>(I->getOperand(0))) |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 389 | return false; |
| 390 | |
| 391 | // Finally, we have to check to make sure there are no instructions |
| 392 | // before the load in its basic block, as we are going to hoist the loop |
| 393 | // out to its predecessor. |
| 394 | if (PBB->begin() != BasicBlock::iterator(I)) |
| 395 | return false; |
| 396 | break; |
| 397 | case Instruction::Add: |
| 398 | case Instruction::Sub: |
| 399 | case Instruction::And: |
| 400 | case Instruction::Or: |
| 401 | case Instruction::Xor: |
| 402 | case Instruction::Shl: |
Reid Spencer | 3822ff5 | 2006-11-08 06:47:33 +0000 | [diff] [blame] | 403 | case Instruction::LShr: |
| 404 | case Instruction::AShr: |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 405 | case Instruction::ICmp: |
| 406 | case Instruction::FCmp: |
Chris Lattner | 3d73bce | 2008-01-03 07:25:26 +0000 | [diff] [blame] | 407 | if (I->getOperand(0)->getType()->isFPOrFPVector()) |
| 408 | return false; // FP arithmetic might trap. |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 409 | break; // These are all cheap and non-trapping instructions. |
| 410 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 411 | |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 412 | // Okay, we can only really hoist these out if their operands are not |
| 413 | // defined in the conditional region. |
| 414 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
Chris Lattner | 9c07866 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 415 | if (!DominatesMergePoint(I->getOperand(i), BB, 0)) |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 416 | return false; |
Chris Lattner | 9c07866 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 417 | // Okay, it's safe to do this! Remember this instruction. |
| 418 | AggressiveInsts->insert(I); |
Chris Lattner | 570751c | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 419 | } |
| 420 | |
Chris Lattner | 723c66d | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 421 | return true; |
| 422 | } |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 423 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 424 | // GatherConstantSetEQs - Given a potentially 'or'd together collection of |
| 425 | // icmp_eq instructions that compare a value against a constant, return the |
| 426 | // value being compared, and stick the constant into the Values vector. |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 427 | static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){ |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 428 | if (Instruction *Inst = dyn_cast<Instruction>(V)) { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 429 | if (Inst->getOpcode() == Instruction::ICmp && |
| 430 | cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) { |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 431 | if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) { |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 432 | Values.push_back(C); |
| 433 | return Inst->getOperand(0); |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 434 | } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) { |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 435 | Values.push_back(C); |
| 436 | return Inst->getOperand(1); |
| 437 | } |
| 438 | } else if (Inst->getOpcode() == Instruction::Or) { |
| 439 | if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values)) |
| 440 | if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values)) |
| 441 | if (LHS == RHS) |
| 442 | return LHS; |
| 443 | } |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 444 | } |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 445 | return 0; |
| 446 | } |
| 447 | |
| 448 | // GatherConstantSetNEs - Given a potentially 'and'd together collection of |
| 449 | // setne instructions that compare a value against a constant, return the value |
| 450 | // being compared, and stick the constant into the Values vector. |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 451 | static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){ |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 452 | if (Instruction *Inst = dyn_cast<Instruction>(V)) { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 453 | if (Inst->getOpcode() == Instruction::ICmp && |
| 454 | cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) { |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 455 | if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) { |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 456 | Values.push_back(C); |
| 457 | return Inst->getOperand(0); |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 458 | } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) { |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 459 | Values.push_back(C); |
| 460 | return Inst->getOperand(1); |
| 461 | } |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 462 | } else if (Inst->getOpcode() == Instruction::And) { |
| 463 | if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values)) |
| 464 | if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values)) |
| 465 | if (LHS == RHS) |
| 466 | return LHS; |
| 467 | } |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 468 | } |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 469 | return 0; |
| 470 | } |
| 471 | |
| 472 | |
| 473 | |
| 474 | /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a |
| 475 | /// bunch of comparisons of one value against constants, return the value and |
| 476 | /// the constants being compared. |
| 477 | static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal, |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 478 | std::vector<ConstantInt*> &Values) { |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 479 | if (Cond->getOpcode() == Instruction::Or) { |
| 480 | CompVal = GatherConstantSetEQs(Cond, Values); |
| 481 | |
| 482 | // Return true to indicate that the condition is true if the CompVal is |
| 483 | // equal to one of the constants. |
| 484 | return true; |
| 485 | } else if (Cond->getOpcode() == Instruction::And) { |
| 486 | CompVal = GatherConstantSetNEs(Cond, Values); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 487 | |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 488 | // Return false to indicate that the condition is false if the CompVal is |
| 489 | // equal to one of the constants. |
| 490 | return false; |
| 491 | } |
| 492 | return false; |
| 493 | } |
| 494 | |
| 495 | /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and |
| 496 | /// has no side effects, nuke it. If it uses any instructions that become dead |
| 497 | /// because the instruction is now gone, nuke them too. |
| 498 | static void ErasePossiblyDeadInstructionTree(Instruction *I) { |
Chris Lattner | 8cfe633 | 2006-08-03 21:40:24 +0000 | [diff] [blame] | 499 | if (!isInstructionTriviallyDead(I)) return; |
| 500 | |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 501 | SmallVector<Instruction*, 16> InstrsToInspect; |
Chris Lattner | 8cfe633 | 2006-08-03 21:40:24 +0000 | [diff] [blame] | 502 | InstrsToInspect.push_back(I); |
| 503 | |
| 504 | while (!InstrsToInspect.empty()) { |
| 505 | I = InstrsToInspect.back(); |
| 506 | InstrsToInspect.pop_back(); |
| 507 | |
| 508 | if (!isInstructionTriviallyDead(I)) continue; |
| 509 | |
| 510 | // If I is in the work list multiple times, remove previous instances. |
| 511 | for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i) |
| 512 | if (InstrsToInspect[i] == I) { |
| 513 | InstrsToInspect.erase(InstrsToInspect.begin()+i); |
| 514 | --i, --e; |
| 515 | } |
| 516 | |
| 517 | // Add operands of dead instruction to worklist. |
| 518 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
| 519 | if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i))) |
| 520 | InstrsToInspect.push_back(OpI); |
| 521 | |
| 522 | // Remove dead instruction. |
| 523 | I->eraseFromParent(); |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 524 | } |
| 525 | } |
| 526 | |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 527 | // isValueEqualityComparison - Return true if the specified terminator checks to |
| 528 | // see if a value is equal to constant integer value. |
| 529 | static Value *isValueEqualityComparison(TerminatorInst *TI) { |
Chris Lattner | 4bebf08 | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 530 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 531 | // Do not permit merging of large switch instructions into their |
| 532 | // predecessors unless there is only one predecessor. |
| 533 | if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()), |
| 534 | pred_end(SI->getParent())) > 128) |
| 535 | return 0; |
| 536 | |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 537 | return SI->getCondition(); |
Chris Lattner | 4bebf08 | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 538 | } |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 539 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
| 540 | if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 541 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) |
| 542 | if ((ICI->getPredicate() == ICmpInst::ICMP_EQ || |
| 543 | ICI->getPredicate() == ICmpInst::ICMP_NE) && |
| 544 | isa<ConstantInt>(ICI->getOperand(1))) |
| 545 | return ICI->getOperand(0); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 546 | return 0; |
| 547 | } |
| 548 | |
| 549 | // Given a value comparison instruction, decode all of the 'cases' that it |
| 550 | // represents and return the 'default' block. |
| 551 | static BasicBlock * |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 552 | GetValueEqualityComparisonCases(TerminatorInst *TI, |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 553 | std::vector<std::pair<ConstantInt*, |
| 554 | BasicBlock*> > &Cases) { |
| 555 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 556 | Cases.reserve(SI->getNumCases()); |
| 557 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
Chris Lattner | be54dcc | 2005-02-26 18:33:28 +0000 | [diff] [blame] | 558 | Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i))); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 559 | return SI->getDefaultDest(); |
| 560 | } |
| 561 | |
| 562 | BranchInst *BI = cast<BranchInst>(TI); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 563 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| 564 | Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)), |
| 565 | BI->getSuccessor(ICI->getPredicate() == |
| 566 | ICmpInst::ICMP_NE))); |
| 567 | return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 568 | } |
| 569 | |
| 570 | |
Dan Gohman | fa73ea2 | 2007-05-24 14:36:04 +0000 | [diff] [blame] | 571 | // EliminateBlockCases - Given a vector of bb/value pairs, remove any entries |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 572 | // in the list that match the specified block. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 573 | static void EliminateBlockCases(BasicBlock *BB, |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 574 | std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) { |
| 575 | for (unsigned i = 0, e = Cases.size(); i != e; ++i) |
| 576 | if (Cases[i].second == BB) { |
| 577 | Cases.erase(Cases.begin()+i); |
| 578 | --i; --e; |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as |
| 583 | // well. |
| 584 | static bool |
| 585 | ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1, |
| 586 | std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) { |
| 587 | std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2; |
| 588 | |
| 589 | // Make V1 be smaller than V2. |
| 590 | if (V1->size() > V2->size()) |
| 591 | std::swap(V1, V2); |
| 592 | |
| 593 | if (V1->size() == 0) return false; |
| 594 | if (V1->size() == 1) { |
| 595 | // Just scan V2. |
| 596 | ConstantInt *TheVal = (*V1)[0].first; |
| 597 | for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| 598 | if (TheVal == (*V2)[i].first) |
| 599 | return true; |
| 600 | } |
| 601 | |
| 602 | // Otherwise, just sort both lists and compare element by element. |
| 603 | std::sort(V1->begin(), V1->end()); |
| 604 | std::sort(V2->begin(), V2->end()); |
| 605 | unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| 606 | while (i1 != e1 && i2 != e2) { |
| 607 | if ((*V1)[i1].first == (*V2)[i2].first) |
| 608 | return true; |
| 609 | if ((*V1)[i1].first < (*V2)[i2].first) |
| 610 | ++i1; |
| 611 | else |
| 612 | ++i2; |
| 613 | } |
| 614 | return false; |
| 615 | } |
| 616 | |
| 617 | // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a |
| 618 | // terminator instruction and its block is known to only have a single |
| 619 | // predecessor block, check to see if that predecessor is also a value |
| 620 | // comparison with the same value, and if that comparison determines the outcome |
| 621 | // of this comparison. If so, simplify TI. This does a very limited form of |
| 622 | // jump threading. |
| 623 | static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
| 624 | BasicBlock *Pred) { |
| 625 | Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
| 626 | if (!PredVal) return false; // Not a value comparison in predecessor. |
| 627 | |
| 628 | Value *ThisVal = isValueEqualityComparison(TI); |
| 629 | assert(ThisVal && "This isn't a value comparison!!"); |
| 630 | if (ThisVal != PredVal) return false; // Different predicates. |
| 631 | |
| 632 | // Find out information about when control will move from Pred to TI's block. |
| 633 | std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases; |
| 634 | BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), |
| 635 | PredCases); |
| 636 | EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 637 | |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 638 | // Find information about how control leaves this block. |
| 639 | std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases; |
| 640 | BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
| 641 | EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
| 642 | |
| 643 | // If TI's block is the default block from Pred's comparison, potentially |
| 644 | // simplify TI based on this knowledge. |
| 645 | if (PredDef == TI->getParent()) { |
| 646 | // If we are here, we know that the value is none of those cases listed in |
| 647 | // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| 648 | // can simplify TI. |
| 649 | if (ValuesOverlap(PredCases, ThisCases)) { |
| 650 | if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) { |
| 651 | // Okay, one of the successors of this condbr is dead. Convert it to a |
| 652 | // uncond br. |
| 653 | assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| 654 | Value *Cond = BTI->getCondition(); |
| 655 | // Insert the new branch. |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 656 | Instruction *NI = BranchInst::Create(ThisDef, TI); |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 657 | |
| 658 | // Remove PHI node entries for the dead edge. |
| 659 | ThisCases[0].second->removePredecessor(TI->getParent()); |
| 660 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 661 | DOUT << "Threading pred instr: " << *Pred->getTerminator() |
| 662 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"; |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 663 | |
| 664 | TI->eraseFromParent(); // Nuke the old one. |
| 665 | // If condition is now dead, nuke it. |
| 666 | if (Instruction *CondI = dyn_cast<Instruction>(Cond)) |
| 667 | ErasePossiblyDeadInstructionTree(CondI); |
| 668 | return true; |
| 669 | |
| 670 | } else { |
| 671 | SwitchInst *SI = cast<SwitchInst>(TI); |
| 672 | // Okay, TI has cases that are statically dead, prune them away. |
Chris Lattner | c995123 | 2007-04-02 01:44:59 +0000 | [diff] [blame] | 673 | SmallPtrSet<Constant*, 16> DeadCases; |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 674 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 675 | DeadCases.insert(PredCases[i].first); |
| 676 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 677 | DOUT << "Threading pred instr: " << *Pred->getTerminator() |
| 678 | << "Through successor TI: " << *TI; |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 679 | |
| 680 | for (unsigned i = SI->getNumCases()-1; i != 0; --i) |
| 681 | if (DeadCases.count(SI->getCaseValue(i))) { |
| 682 | SI->getSuccessor(i)->removePredecessor(TI->getParent()); |
| 683 | SI->removeCase(i); |
| 684 | } |
| 685 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 686 | DOUT << "Leaving: " << *TI << "\n"; |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 687 | return true; |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | } else { |
| 692 | // Otherwise, TI's block must correspond to some matched value. Find out |
| 693 | // which value (or set of values) this is. |
| 694 | ConstantInt *TIV = 0; |
| 695 | BasicBlock *TIBB = TI->getParent(); |
| 696 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 697 | if (PredCases[i].second == TIBB) { |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 698 | if (TIV == 0) |
| 699 | TIV = PredCases[i].first; |
| 700 | else |
| 701 | return false; // Cannot handle multiple values coming to this block. |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 702 | } |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 703 | assert(TIV && "No edge from pred to succ?"); |
| 704 | |
| 705 | // Okay, we found the one constant that our value can be if we get into TI's |
| 706 | // BB. Find out which successor will unconditionally be branched to. |
| 707 | BasicBlock *TheRealDest = 0; |
| 708 | for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| 709 | if (ThisCases[i].first == TIV) { |
| 710 | TheRealDest = ThisCases[i].second; |
| 711 | break; |
| 712 | } |
| 713 | |
| 714 | // If not handled by any explicit cases, it is handled by the default case. |
| 715 | if (TheRealDest == 0) TheRealDest = ThisDef; |
| 716 | |
| 717 | // Remove PHI node entries for dead edges. |
| 718 | BasicBlock *CheckEdge = TheRealDest; |
| 719 | for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) |
| 720 | if (*SI != CheckEdge) |
| 721 | (*SI)->removePredecessor(TIBB); |
| 722 | else |
| 723 | CheckEdge = 0; |
| 724 | |
| 725 | // Insert the new branch. |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 726 | Instruction *NI = BranchInst::Create(TheRealDest, TI); |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 727 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 728 | DOUT << "Threading pred instr: " << *Pred->getTerminator() |
| 729 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"; |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 730 | Instruction *Cond = 0; |
| 731 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
| 732 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
| 733 | TI->eraseFromParent(); // Nuke the old one. |
| 734 | |
| 735 | if (Cond) ErasePossiblyDeadInstructionTree(Cond); |
| 736 | return true; |
| 737 | } |
| 738 | return false; |
| 739 | } |
| 740 | |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 741 | // FoldValueComparisonIntoPredecessors - The specified terminator is a value |
| 742 | // equality comparison instruction (either a switch or a branch on "X == c"). |
| 743 | // See if any of the predecessors of the terminator block are value comparisons |
| 744 | // on the same value. If so, and if safe to do so, fold them together. |
| 745 | static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) { |
| 746 | BasicBlock *BB = TI->getParent(); |
| 747 | Value *CV = isValueEqualityComparison(TI); // CondVal |
| 748 | assert(CV && "Not a comparison?"); |
| 749 | bool Changed = false; |
| 750 | |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 751 | SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 752 | while (!Preds.empty()) { |
| 753 | BasicBlock *Pred = Preds.back(); |
| 754 | Preds.pop_back(); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 755 | |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 756 | // See if the predecessor is a comparison with the same value. |
| 757 | TerminatorInst *PTI = Pred->getTerminator(); |
| 758 | Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
| 759 | |
| 760 | if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { |
| 761 | // Figure out which 'cases' to copy from SI to PSI. |
| 762 | std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases; |
| 763 | BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| 764 | |
| 765 | std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases; |
| 766 | BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| 767 | |
| 768 | // Based on whether the default edge from PTI goes to BB or not, fill in |
| 769 | // PredCases and PredDefault with the new switch cases we would like to |
| 770 | // build. |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 771 | SmallVector<BasicBlock*, 8> NewSuccessors; |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 772 | |
| 773 | if (PredDefault == BB) { |
| 774 | // If this is the default destination from PTI, only the edges in TI |
| 775 | // that don't occur in PTI, or that branch to BB will be activated. |
| 776 | std::set<ConstantInt*> PTIHandled; |
| 777 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 778 | if (PredCases[i].second != BB) |
| 779 | PTIHandled.insert(PredCases[i].first); |
| 780 | else { |
| 781 | // The default destination is BB, we don't need explicit targets. |
| 782 | std::swap(PredCases[i], PredCases.back()); |
| 783 | PredCases.pop_back(); |
| 784 | --i; --e; |
| 785 | } |
| 786 | |
| 787 | // Reconstruct the new switch statement we will be building. |
| 788 | if (PredDefault != BBDefault) { |
| 789 | PredDefault->removePredecessor(Pred); |
| 790 | PredDefault = BBDefault; |
| 791 | NewSuccessors.push_back(BBDefault); |
| 792 | } |
| 793 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 794 | if (!PTIHandled.count(BBCases[i].first) && |
| 795 | BBCases[i].second != BBDefault) { |
| 796 | PredCases.push_back(BBCases[i]); |
| 797 | NewSuccessors.push_back(BBCases[i].second); |
| 798 | } |
| 799 | |
| 800 | } else { |
| 801 | // If this is not the default destination from PSI, only the edges |
| 802 | // in SI that occur in PSI with a destination of BB will be |
| 803 | // activated. |
| 804 | std::set<ConstantInt*> PTIHandled; |
| 805 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 806 | if (PredCases[i].second == BB) { |
| 807 | PTIHandled.insert(PredCases[i].first); |
| 808 | std::swap(PredCases[i], PredCases.back()); |
| 809 | PredCases.pop_back(); |
| 810 | --i; --e; |
| 811 | } |
| 812 | |
| 813 | // Okay, now we know which constants were sent to BB from the |
| 814 | // predecessor. Figure out where they will all go now. |
| 815 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 816 | if (PTIHandled.count(BBCases[i].first)) { |
| 817 | // If this is one we are capable of getting... |
| 818 | PredCases.push_back(BBCases[i]); |
| 819 | NewSuccessors.push_back(BBCases[i].second); |
| 820 | PTIHandled.erase(BBCases[i].first);// This constant is taken care of |
| 821 | } |
| 822 | |
| 823 | // If there are any constants vectored to BB that TI doesn't handle, |
| 824 | // they must go to the default destination of TI. |
| 825 | for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(), |
| 826 | E = PTIHandled.end(); I != E; ++I) { |
| 827 | PredCases.push_back(std::make_pair(*I, BBDefault)); |
| 828 | NewSuccessors.push_back(BBDefault); |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | // Okay, at this point, we know which new successor Pred will get. Make |
| 833 | // sure we update the number of entries in the PHI nodes for these |
| 834 | // successors. |
| 835 | for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) |
| 836 | AddPredecessorToBlock(NewSuccessors[i], Pred, BB); |
| 837 | |
| 838 | // Now that the successors are updated, create the new Switch instruction. |
Gabor Greif | b1dbcd8 | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 839 | SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault, |
| 840 | PredCases.size(), PTI); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 841 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 842 | NewSI->addCase(PredCases[i].first, PredCases[i].second); |
Chris Lattner | 13b2f76 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 843 | |
| 844 | Instruction *DeadCond = 0; |
| 845 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) |
| 846 | // If PTI is a branch, remember the condition. |
| 847 | DeadCond = dyn_cast<Instruction>(BI->getCondition()); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 848 | Pred->getInstList().erase(PTI); |
| 849 | |
Chris Lattner | 13b2f76 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 850 | // If the condition is dead now, remove the instruction tree. |
| 851 | if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond); |
| 852 | |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 853 | // Okay, last check. If BB is still a successor of PSI, then we must |
| 854 | // have an infinite loop case. If so, add an infinitely looping block |
| 855 | // to handle the case to preserve the behavior of the code. |
| 856 | BasicBlock *InfLoopBlock = 0; |
| 857 | for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| 858 | if (NewSI->getSuccessor(i) == BB) { |
| 859 | if (InfLoopBlock == 0) { |
| 860 | // Insert it at the end of the loop, because it's either code, |
| 861 | // or it won't matter if it's hot. :) |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 862 | InfLoopBlock = BasicBlock::Create("infloop", BB->getParent()); |
| 863 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 864 | } |
| 865 | NewSI->setSuccessor(i, InfLoopBlock); |
| 866 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 867 | |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 868 | Changed = true; |
| 869 | } |
| 870 | } |
| 871 | return Changed; |
| 872 | } |
| 873 | |
Chris Lattner | 6306d07 | 2005-08-03 17:59:45 +0000 | [diff] [blame] | 874 | /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 875 | /// BB2, hoist any common code in the two blocks up into the branch block. The |
| 876 | /// caller of this function guarantees that BI's block dominates BB1 and BB2. |
| 877 | static bool HoistThenElseCodeToIf(BranchInst *BI) { |
| 878 | // This does very trivial matching, with limited scanning, to find identical |
| 879 | // instructions in the two blocks. In particular, we don't want to get into |
| 880 | // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| 881 | // such, we currently just scan for obviously identical instructions in an |
| 882 | // identical order. |
| 883 | BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| 884 | BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
| 885 | |
| 886 | Instruction *I1 = BB1->begin(), *I2 = BB2->begin(); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 887 | if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) || |
| 888 | isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2)) |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 889 | return false; |
| 890 | |
| 891 | // If we get here, we can hoist at least one instruction. |
| 892 | BasicBlock *BIParent = BI->getParent(); |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 893 | |
| 894 | do { |
| 895 | // If we are hoisting the terminator instruction, don't move one (making a |
| 896 | // broken BB), instead clone it, and remove BI. |
| 897 | if (isa<TerminatorInst>(I1)) |
| 898 | goto HoistTerminator; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 899 | |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 900 | // For a normal instruction, we just move one to right before the branch, |
| 901 | // then replace all uses of the other with the first. Finally, we remove |
| 902 | // the now redundant second instruction. |
| 903 | BIParent->getInstList().splice(BI, BB1->getInstList(), I1); |
| 904 | if (!I2->use_empty()) |
| 905 | I2->replaceAllUsesWith(I1); |
| 906 | BB2->getInstList().erase(I2); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 907 | |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 908 | I1 = BB1->begin(); |
| 909 | I2 = BB2->begin(); |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 910 | } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2)); |
| 911 | |
| 912 | return true; |
| 913 | |
| 914 | HoistTerminator: |
| 915 | // Okay, it is safe to hoist the terminator. |
| 916 | Instruction *NT = I1->clone(); |
| 917 | BIParent->getInstList().insert(BI, NT); |
| 918 | if (NT->getType() != Type::VoidTy) { |
| 919 | I1->replaceAllUsesWith(NT); |
| 920 | I2->replaceAllUsesWith(NT); |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 921 | NT->takeName(I1); |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 922 | } |
| 923 | |
| 924 | // Hoisting one of the terminators from our successor is a great thing. |
| 925 | // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| 926 | // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| 927 | // nodes, so we insert select instruction to compute the final result. |
| 928 | std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; |
| 929 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
| 930 | PHINode *PN; |
| 931 | for (BasicBlock::iterator BBI = SI->begin(); |
Chris Lattner | 0f535c6 | 2004-11-30 07:47:34 +0000 | [diff] [blame] | 932 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 933 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 934 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 935 | if (BB1V != BB2V) { |
| 936 | // These values do not agree. Insert a select instruction before NT |
| 937 | // that determines the right value. |
| 938 | SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
| 939 | if (SI == 0) |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 940 | SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V, |
| 941 | BB1V->getName()+"."+BB2V->getName(), NT); |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 942 | // Make the PHI node use the select for all incoming values for BB1/BB2 |
| 943 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 944 | if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) |
| 945 | PN->setIncomingValue(i, SI); |
| 946 | } |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | // Update any PHI nodes in our new successors. |
| 951 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) |
| 952 | AddPredecessorToBlock(*SI, BIParent, BB1); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 953 | |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 954 | BI->eraseFromParent(); |
| 955 | return true; |
| 956 | } |
| 957 | |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 958 | /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch |
| 959 | /// across this block. |
| 960 | static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { |
| 961 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 962 | unsigned Size = 0; |
| 963 | |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 964 | // If this basic block contains anything other than a PHI (which controls the |
| 965 | // branch) and branch itself, bail out. FIXME: improve this in the future. |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 966 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) { |
| 967 | if (Size > 10) return false; // Don't clone large BB's. |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 968 | |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 969 | // We can only support instructions that are do not define values that are |
| 970 | // live outside of the current basic block. |
| 971 | for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end(); |
| 972 | UI != E; ++UI) { |
| 973 | Instruction *U = cast<Instruction>(*UI); |
| 974 | if (U->getParent() != BB || isa<PHINode>(U)) return false; |
| 975 | } |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 976 | |
| 977 | // Looks ok, continue checking. |
| 978 | } |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 979 | |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 980 | return true; |
| 981 | } |
| 982 | |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 983 | /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value |
| 984 | /// that is defined in the same block as the branch and if any PHI entries are |
| 985 | /// constants, thread edges corresponding to that entry to be branches to their |
| 986 | /// ultimate destination. |
| 987 | static bool FoldCondBranchOnPHI(BranchInst *BI) { |
| 988 | BasicBlock *BB = BI->getParent(); |
| 989 | PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
Chris Lattner | 9c88d98 | 2005-09-19 23:57:04 +0000 | [diff] [blame] | 990 | // NOTE: we currently cannot transform this case if the PHI node is used |
| 991 | // outside of the block. |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 992 | if (!PN || PN->getParent() != BB || !PN->hasOneUse()) |
| 993 | return false; |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 994 | |
| 995 | // Degenerate case of a single entry PHI. |
| 996 | if (PN->getNumIncomingValues() == 1) { |
| 997 | if (PN->getIncomingValue(0) != PN) |
| 998 | PN->replaceAllUsesWith(PN->getIncomingValue(0)); |
| 999 | else |
| 1000 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
| 1001 | PN->eraseFromParent(); |
| 1002 | return true; |
| 1003 | } |
| 1004 | |
| 1005 | // Now we know that this block has multiple preds and two succs. |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1006 | if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1007 | |
| 1008 | // Okay, this is a simple enough basic block. See if any phi values are |
| 1009 | // constants. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1010 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1011 | ConstantInt *CB; |
| 1012 | if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) && |
Reid Spencer | 4fe16d6 | 2007-01-11 18:21:29 +0000 | [diff] [blame] | 1013 | CB->getType() == Type::Int1Ty) { |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1014 | // Okay, we now know that all edges from PredBB should be revectored to |
| 1015 | // branch to RealDest. |
| 1016 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1017 | BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1018 | |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1019 | if (RealDest == BB) continue; // Skip self loops. |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1020 | |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1021 | // The dest block might have PHI nodes, other predecessors and other |
| 1022 | // difficult cases. Instead of being smart about this, just insert a new |
| 1023 | // block that jumps to the destination block, effectively splitting |
| 1024 | // the edge we are about to create. |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1025 | BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge", |
| 1026 | RealDest->getParent(), RealDest); |
| 1027 | BranchInst::Create(RealDest, EdgeBB); |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1028 | PHINode *PN; |
| 1029 | for (BasicBlock::iterator BBI = RealDest->begin(); |
| 1030 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1031 | Value *V = PN->getIncomingValueForBlock(BB); |
| 1032 | PN->addIncoming(V, EdgeBB); |
| 1033 | } |
| 1034 | |
| 1035 | // BB may have instructions that are being threaded over. Clone these |
| 1036 | // instructions into EdgeBB. We know that there will be no uses of the |
| 1037 | // cloned instructions outside of EdgeBB. |
| 1038 | BasicBlock::iterator InsertPt = EdgeBB->begin(); |
| 1039 | std::map<Value*, Value*> TranslateMap; // Track translated values. |
| 1040 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
| 1041 | if (PHINode *PN = dyn_cast<PHINode>(BBI)) { |
| 1042 | TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); |
| 1043 | } else { |
| 1044 | // Clone the instruction. |
| 1045 | Instruction *N = BBI->clone(); |
| 1046 | if (BBI->hasName()) N->setName(BBI->getName()+".c"); |
| 1047 | |
| 1048 | // Update operands due to translation. |
| 1049 | for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { |
| 1050 | std::map<Value*, Value*>::iterator PI = |
| 1051 | TranslateMap.find(N->getOperand(i)); |
| 1052 | if (PI != TranslateMap.end()) |
| 1053 | N->setOperand(i, PI->second); |
| 1054 | } |
| 1055 | |
| 1056 | // Check for trivial simplification. |
| 1057 | if (Constant *C = ConstantFoldInstruction(N)) { |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1058 | TranslateMap[BBI] = C; |
| 1059 | delete N; // Constant folded away, don't need actual inst |
| 1060 | } else { |
| 1061 | // Insert the new instruction into its new home. |
| 1062 | EdgeBB->getInstList().insert(InsertPt, N); |
| 1063 | if (!BBI->use_empty()) |
| 1064 | TranslateMap[BBI] = N; |
| 1065 | } |
| 1066 | } |
| 1067 | } |
| 1068 | |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1069 | // Loop over all of the edges from PredBB to BB, changing them to branch |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1070 | // to EdgeBB instead. |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1071 | TerminatorInst *PredBBTI = PredBB->getTerminator(); |
| 1072 | for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| 1073 | if (PredBBTI->getSuccessor(i) == BB) { |
| 1074 | BB->removePredecessor(PredBB); |
Chris Lattner | e9487f0 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1075 | PredBBTI->setSuccessor(i, EdgeBB); |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1076 | } |
| 1077 | |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1078 | // Recurse, simplifying any other constants. |
| 1079 | return FoldCondBranchOnPHI(BI) | true; |
| 1080 | } |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1081 | } |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1082 | |
| 1083 | return false; |
| 1084 | } |
| 1085 | |
Chris Lattner | f58c1a5 | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1086 | /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry |
| 1087 | /// PHI node, see if we can eliminate it. |
| 1088 | static bool FoldTwoEntryPHINode(PHINode *PN) { |
| 1089 | // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| 1090 | // statement", which has a very simple dominance structure. Basically, we |
| 1091 | // are trying to find the condition that is being branched on, which |
| 1092 | // subsequently causes this merge to happen. We really want control |
| 1093 | // dependence information for this check, but simplifycfg can't keep it up |
| 1094 | // to date, and this catches most of the cases we care about anyway. |
| 1095 | // |
| 1096 | BasicBlock *BB = PN->getParent(); |
| 1097 | BasicBlock *IfTrue, *IfFalse; |
| 1098 | Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); |
| 1099 | if (!IfCond) return false; |
| 1100 | |
Chris Lattner | 822a879 | 2006-11-18 19:19:36 +0000 | [diff] [blame] | 1101 | // Okay, we found that we can merge this two-entry phi node into a select. |
| 1102 | // Doing so would require us to fold *all* two entry phi nodes in this block. |
| 1103 | // At some point this becomes non-profitable (particularly if the target |
| 1104 | // doesn't support cmov's). Only do this transformation if there are two or |
| 1105 | // fewer PHI nodes in this block. |
| 1106 | unsigned NumPhis = 0; |
| 1107 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) |
| 1108 | if (NumPhis > 2) |
| 1109 | return false; |
| 1110 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 1111 | DOUT << "FOUND IF CONDITION! " << *IfCond << " T: " |
| 1112 | << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"; |
Chris Lattner | f58c1a5 | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1113 | |
| 1114 | // Loop over the PHI's seeing if we can promote them all to select |
| 1115 | // instructions. While we are at it, keep track of the instructions |
| 1116 | // that need to be moved to the dominating block. |
| 1117 | std::set<Instruction*> AggressiveInsts; |
| 1118 | |
Chris Lattner | f58c1a5 | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1119 | BasicBlock::iterator AfterPHIIt = BB->begin(); |
| 1120 | while (isa<PHINode>(AfterPHIIt)) { |
| 1121 | PHINode *PN = cast<PHINode>(AfterPHIIt++); |
| 1122 | if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) { |
| 1123 | if (PN->getIncomingValue(0) != PN) |
| 1124 | PN->replaceAllUsesWith(PN->getIncomingValue(0)); |
| 1125 | else |
| 1126 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
| 1127 | } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB, |
| 1128 | &AggressiveInsts) || |
| 1129 | !DominatesMergePoint(PN->getIncomingValue(1), BB, |
| 1130 | &AggressiveInsts)) { |
Chris Lattner | 055dc10 | 2005-09-23 07:23:18 +0000 | [diff] [blame] | 1131 | return false; |
Chris Lattner | f58c1a5 | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1132 | } |
| 1133 | } |
| 1134 | |
Chris Lattner | f58c1a5 | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1135 | // If we all PHI nodes are promotable, check to make sure that all |
| 1136 | // instructions in the predecessor blocks can be promoted as well. If |
| 1137 | // not, we won't be able to get rid of the control flow, so it's not |
| 1138 | // worth promoting to select instructions. |
| 1139 | BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0; |
| 1140 | PN = cast<PHINode>(BB->begin()); |
| 1141 | BasicBlock *Pred = PN->getIncomingBlock(0); |
| 1142 | if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) { |
| 1143 | IfBlock1 = Pred; |
| 1144 | DomBlock = *pred_begin(Pred); |
| 1145 | for (BasicBlock::iterator I = Pred->begin(); |
| 1146 | !isa<TerminatorInst>(I); ++I) |
| 1147 | if (!AggressiveInsts.count(I)) { |
| 1148 | // This is not an aggressive instruction that we can promote. |
| 1149 | // Because of this, we won't be able to get rid of the control |
| 1150 | // flow, so the xform is not worth it. |
| 1151 | return false; |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | Pred = PN->getIncomingBlock(1); |
| 1156 | if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) { |
| 1157 | IfBlock2 = Pred; |
| 1158 | DomBlock = *pred_begin(Pred); |
| 1159 | for (BasicBlock::iterator I = Pred->begin(); |
| 1160 | !isa<TerminatorInst>(I); ++I) |
| 1161 | if (!AggressiveInsts.count(I)) { |
| 1162 | // This is not an aggressive instruction that we can promote. |
| 1163 | // Because of this, we won't be able to get rid of the control |
| 1164 | // flow, so the xform is not worth it. |
| 1165 | return false; |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | // If we can still promote the PHI nodes after this gauntlet of tests, |
| 1170 | // do all of the PHI's now. |
| 1171 | |
| 1172 | // Move all 'aggressive' instructions, which are defined in the |
| 1173 | // conditional parts of the if's up to the dominating block. |
| 1174 | if (IfBlock1) { |
| 1175 | DomBlock->getInstList().splice(DomBlock->getTerminator(), |
| 1176 | IfBlock1->getInstList(), |
| 1177 | IfBlock1->begin(), |
| 1178 | IfBlock1->getTerminator()); |
| 1179 | } |
| 1180 | if (IfBlock2) { |
| 1181 | DomBlock->getInstList().splice(DomBlock->getTerminator(), |
| 1182 | IfBlock2->getInstList(), |
| 1183 | IfBlock2->begin(), |
| 1184 | IfBlock2->getTerminator()); |
| 1185 | } |
| 1186 | |
| 1187 | while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| 1188 | // Change the PHI node into a select instruction. |
| 1189 | Value *TrueVal = |
| 1190 | PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
| 1191 | Value *FalseVal = |
| 1192 | PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
| 1193 | |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1194 | Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt); |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1195 | PN->replaceAllUsesWith(NV); |
| 1196 | NV->takeName(PN); |
| 1197 | |
Chris Lattner | f58c1a5 | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1198 | BB->getInstList().erase(PN); |
| 1199 | } |
| 1200 | return true; |
| 1201 | } |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1202 | |
Chris Lattner | c9e495c | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1203 | /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes |
| 1204 | /// to two returning blocks, try to merge them together into one return, |
| 1205 | /// introducing a select if the return values disagree. |
| 1206 | static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) { |
| 1207 | assert(BI->isConditional() && "Must be a conditional branch"); |
| 1208 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 1209 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 1210 | ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); |
| 1211 | ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); |
| 1212 | |
| 1213 | // Check to ensure both blocks are empty (just a return) or optionally empty |
| 1214 | // with PHI nodes. If there are other instructions, merging would cause extra |
| 1215 | // computation on one path or the other. |
| 1216 | BasicBlock::iterator BBI = TrueRet; |
| 1217 | if (BBI != TrueSucc->begin() && !isa<PHINode>(--BBI)) |
| 1218 | return false; // Not empty with optional phi nodes. |
| 1219 | BBI = FalseRet; |
| 1220 | if (BBI != FalseSucc->begin() && !isa<PHINode>(--BBI)) |
| 1221 | return false; // Not empty with optional phi nodes. |
| 1222 | |
| 1223 | // Okay, we found a branch that is going to two return nodes. If |
| 1224 | // there is no return value for this function, just change the |
| 1225 | // branch into a return. |
| 1226 | if (FalseRet->getNumOperands() == 0) { |
| 1227 | TrueSucc->removePredecessor(BI->getParent()); |
| 1228 | FalseSucc->removePredecessor(BI->getParent()); |
| 1229 | ReturnInst::Create(0, BI); |
| 1230 | BI->eraseFromParent(); |
| 1231 | return true; |
| 1232 | } |
| 1233 | |
| 1234 | // Otherwise, build up the result values for the new return. |
| 1235 | SmallVector<Value*, 4> TrueResult; |
| 1236 | SmallVector<Value*, 4> FalseResult; |
| 1237 | |
| 1238 | for (unsigned i = 0, e = TrueRet->getNumOperands(); i != e; ++i) { |
| 1239 | // Otherwise, figure out what the true and false return values are |
| 1240 | // so we can insert a new select instruction. |
| 1241 | Value *TrueValue = TrueRet->getOperand(i); |
| 1242 | Value *FalseValue = FalseRet->getOperand(i); |
| 1243 | |
| 1244 | // Unwrap any PHI nodes in the return blocks. |
| 1245 | if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue)) |
| 1246 | if (TVPN->getParent() == TrueSucc) |
| 1247 | TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| 1248 | if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue)) |
| 1249 | if (FVPN->getParent() == FalseSucc) |
| 1250 | FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
| 1251 | |
| 1252 | // In order for this transformation to be safe, we must be able to |
| 1253 | // unconditionally execute both operands to the return. This is |
| 1254 | // normally the case, but we could have a potentially-trapping |
| 1255 | // constant expression that prevents this transformation from being |
| 1256 | // safe. |
| 1257 | if (ConstantExpr *TCV = dyn_cast<ConstantExpr>(TrueValue)) |
| 1258 | if (TCV->canTrap()) |
| 1259 | return false; |
| 1260 | if (ConstantExpr *FCV = dyn_cast<ConstantExpr>(FalseValue)) |
| 1261 | if (FCV->canTrap()) |
| 1262 | return false; |
| 1263 | |
| 1264 | TrueResult.push_back(TrueValue); |
| 1265 | FalseResult.push_back(FalseValue); |
| 1266 | } |
| 1267 | |
| 1268 | // Okay, we collected all the mapped values and checked them for sanity, and |
| 1269 | // defined to really do this transformation. First, update the CFG. |
| 1270 | TrueSucc->removePredecessor(BI->getParent()); |
| 1271 | FalseSucc->removePredecessor(BI->getParent()); |
| 1272 | |
| 1273 | // Insert select instructions where needed. |
| 1274 | Value *BrCond = BI->getCondition(); |
| 1275 | for (unsigned i = 0, e = TrueRet->getNumOperands(); i != e; ++i) { |
| 1276 | // Insert a select if the results differ. |
| 1277 | if (TrueResult[i] == FalseResult[i] || isa<UndefValue>(FalseResult[i])) |
| 1278 | continue; |
| 1279 | if (isa<UndefValue>(TrueResult[i])) { |
| 1280 | TrueResult[i] = FalseResult[i]; |
| 1281 | continue; |
| 1282 | } |
| 1283 | |
| 1284 | TrueResult[i] = SelectInst::Create(BrCond, TrueResult[i], |
| 1285 | FalseResult[i], "retval", BI); |
| 1286 | } |
| 1287 | |
| 1288 | Value *RI = ReturnInst::Create(&TrueResult[0], TrueResult.size(), BI); |
| 1289 | |
| 1290 | DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" |
| 1291 | << "\n " << *BI << "NewRet = " << *RI |
| 1292 | << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc; |
| 1293 | |
| 1294 | BI->eraseFromParent(); |
| 1295 | |
| 1296 | if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond)) |
| 1297 | ErasePossiblyDeadInstructionTree(BrCondI); |
| 1298 | return true; |
| 1299 | } |
| 1300 | |
| 1301 | |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 1302 | namespace { |
| 1303 | /// ConstantIntOrdering - This class implements a stable ordering of constant |
| 1304 | /// integers that does not depend on their address. This is important for |
| 1305 | /// applications that sort ConstantInt's to ensure uniqueness. |
| 1306 | struct ConstantIntOrdering { |
| 1307 | bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
Reid Spencer | e1c99d4 | 2007-03-02 23:01:14 +0000 | [diff] [blame] | 1308 | return LHS->getValue().ult(RHS->getValue()); |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 1309 | } |
| 1310 | }; |
| 1311 | } |
| 1312 | |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1313 | // SimplifyCFG - This function is used to do simplification of a CFG. For |
| 1314 | // example, it adjusts branches to branches to eliminate the extra hop, it |
| 1315 | // eliminates unreachable basic blocks, and does other "peephole" optimization |
Chris Lattner | e2ca540 | 2003-03-05 21:01:52 +0000 | [diff] [blame] | 1316 | // of the CFG. It returns true if a modification was made. |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1317 | // |
| 1318 | // WARNING: The entry node of a function may not be simplified. |
| 1319 | // |
Chris Lattner | f7703df | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 1320 | bool llvm::SimplifyCFG(BasicBlock *BB) { |
Chris Lattner | dc3602b | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 1321 | bool Changed = false; |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1322 | Function *M = BB->getParent(); |
| 1323 | |
| 1324 | assert(BB && BB->getParent() && "Block not embedded in function!"); |
| 1325 | assert(BB->getTerminator() && "Degenerate basic block encountered!"); |
Dan Gohman | ecb7a77 | 2007-03-22 16:38:57 +0000 | [diff] [blame] | 1326 | assert(&BB->getParent()->getEntryBlock() != BB && |
| 1327 | "Can't Simplify entry block!"); |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1328 | |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1329 | // Remove basic blocks that have no predecessors... which are unreachable. |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 1330 | if ((pred_begin(BB) == pred_end(BB)) || |
| 1331 | (*pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB))) { |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 1332 | DOUT << "Removing BB: \n" << *BB; |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1333 | |
| 1334 | // Loop through all of our successors and make sure they know that one |
| 1335 | // of their predecessors is going away. |
Chris Lattner | 151c80b | 2005-04-12 18:51:33 +0000 | [diff] [blame] | 1336 | for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) |
| 1337 | SI->removePredecessor(BB); |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1338 | |
| 1339 | while (!BB->empty()) { |
Chris Lattner | 1896150 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1340 | Instruction &I = BB->back(); |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1341 | // If this instruction is used, replace uses with an arbitrary |
Chris Lattner | f5e982d | 2005-08-02 23:29:23 +0000 | [diff] [blame] | 1342 | // value. Because control flow can't get here, we don't care |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1343 | // what we replace the value with. Note that since this block is |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1344 | // unreachable, and all values contained within it must dominate their |
| 1345 | // uses, that all uses will eventually be removed. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1346 | if (!I.use_empty()) |
Chris Lattner | f5e982d | 2005-08-02 23:29:23 +0000 | [diff] [blame] | 1347 | // Make all users of this instruction use undef instead |
| 1348 | I.replaceAllUsesWith(UndefValue::get(I.getType())); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1349 | |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1350 | // Remove the instruction from the basic block |
Chris Lattner | 1896150 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1351 | BB->getInstList().pop_back(); |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1352 | } |
Chris Lattner | 1896150 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1353 | M->getBasicBlockList().erase(BB); |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1354 | return true; |
| 1355 | } |
| 1356 | |
Chris Lattner | 694e37f | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 1357 | // Check to see if we can constant propagate this terminator instruction |
| 1358 | // away... |
Chris Lattner | dc3602b | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 1359 | Changed |= ConstantFoldTerminator(BB); |
Chris Lattner | 694e37f | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 1360 | |
Dan Gohman | 882d87d | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 1361 | // If there is a trivial two-entry PHI node in this basic block, and we can |
| 1362 | // eliminate it, do so now. |
| 1363 | if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) |
| 1364 | if (PN->getNumIncomingValues() == 2) |
| 1365 | Changed |= FoldTwoEntryPHINode(PN); |
| 1366 | |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1367 | // If this is a returning block with only PHI nodes in it, fold the return |
| 1368 | // instruction into any unconditional branch predecessors. |
Chris Lattner | 147af6b | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1369 | // |
| 1370 | // If any predecessor is a conditional branch that just selects among |
| 1371 | // different return values, fold the replace the branch/return with a select |
| 1372 | // and return. |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1373 | if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { |
| 1374 | BasicBlock::iterator BBI = BB->getTerminator(); |
| 1375 | if (BBI == BB->begin() || isa<PHINode>(--BBI)) { |
Chris Lattner | 147af6b | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1376 | // Find predecessors that end with branches. |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 1377 | SmallVector<BasicBlock*, 8> UncondBranchPreds; |
| 1378 | SmallVector<BranchInst*, 8> CondBranchPreds; |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1379 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 1380 | TerminatorInst *PTI = (*PI)->getTerminator(); |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 1381 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1382 | if (BI->isUnconditional()) |
| 1383 | UncondBranchPreds.push_back(*PI); |
Chris Lattner | 147af6b | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1384 | else |
| 1385 | CondBranchPreds.push_back(BI); |
Anton Korobeynikov | 07e6e56 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 1386 | } |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1387 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1388 | |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1389 | // If we found some, do the transformation! |
| 1390 | if (!UncondBranchPreds.empty()) { |
| 1391 | while (!UncondBranchPreds.empty()) { |
| 1392 | BasicBlock *Pred = UncondBranchPreds.back(); |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 1393 | DOUT << "FOLDING: " << *BB |
| 1394 | << "INTO UNCOND BRANCH PRED: " << *Pred; |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1395 | UncondBranchPreds.pop_back(); |
| 1396 | Instruction *UncondBranch = Pred->getTerminator(); |
| 1397 | // Clone the return and add it to the end of the predecessor. |
| 1398 | Instruction *NewRet = RI->clone(); |
| 1399 | Pred->getInstList().push_back(NewRet); |
| 1400 | |
| 1401 | // If the return instruction returns a value, and if the value was a |
| 1402 | // PHI node in "BB", propagate the right value into the return. |
Chris Lattner | ffba582 | 2008-04-28 00:19:07 +0000 | [diff] [blame] | 1403 | for (unsigned i = 0, e = NewRet->getNumOperands(); i != e; ++i) |
| 1404 | if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(i))) |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1405 | if (PN->getParent() == BB) |
Chris Lattner | ffba582 | 2008-04-28 00:19:07 +0000 | [diff] [blame] | 1406 | NewRet->setOperand(i, PN->getIncomingValueForBlock(Pred)); |
| 1407 | |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1408 | // Update any PHI nodes in the returning block to realize that we no |
| 1409 | // longer branch to them. |
| 1410 | BB->removePredecessor(Pred); |
| 1411 | Pred->getInstList().erase(UncondBranch); |
| 1412 | } |
| 1413 | |
| 1414 | // If we eliminated all predecessors of the block, delete the block now. |
| 1415 | if (pred_begin(BB) == pred_end(BB)) |
| 1416 | // We know there are no successors, so just nuke the block. |
| 1417 | M->getBasicBlockList().erase(BB); |
| 1418 | |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1419 | return true; |
| 1420 | } |
Chris Lattner | 147af6b | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1421 | |
| 1422 | // Check out all of the conditional branches going to this return |
| 1423 | // instruction. If any of them just select between returns, change the |
| 1424 | // branch itself into a select/return pair. |
| 1425 | while (!CondBranchPreds.empty()) { |
| 1426 | BranchInst *BI = CondBranchPreds.back(); |
| 1427 | CondBranchPreds.pop_back(); |
Chris Lattner | 147af6b | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1428 | |
| 1429 | // Check to see if the non-BB successor is also a return block. |
Chris Lattner | c9e495c | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1430 | if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && |
| 1431 | isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && |
| 1432 | SimplifyCondBranchToTwoReturns(BI)) |
| 1433 | return true; |
Chris Lattner | 147af6b | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1434 | } |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1435 | } |
Reid Spencer | 3ed469c | 2006-11-02 20:25:50 +0000 | [diff] [blame] | 1436 | } else if (isa<UnwindInst>(BB->begin())) { |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1437 | // Check to see if the first instruction in this block is just an unwind. |
| 1438 | // If so, replace any invoke instructions which use this as an exception |
Chris Lattner | af17b1d | 2004-07-20 01:17:38 +0000 | [diff] [blame] | 1439 | // destination with call instructions, and any unconditional branch |
| 1440 | // predecessor with an unwind. |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1441 | // |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 1442 | SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1443 | while (!Preds.empty()) { |
| 1444 | BasicBlock *Pred = Preds.back(); |
Chris Lattner | af17b1d | 2004-07-20 01:17:38 +0000 | [diff] [blame] | 1445 | if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) { |
Nick Lewycky | 280a6e6 | 2008-04-25 16:53:59 +0000 | [diff] [blame] | 1446 | if (BI->isUnconditional()) { |
Chris Lattner | af17b1d | 2004-07-20 01:17:38 +0000 | [diff] [blame] | 1447 | Pred->getInstList().pop_back(); // nuke uncond branch |
| 1448 | new UnwindInst(Pred); // Use unwind. |
| 1449 | Changed = true; |
| 1450 | } |
Nick Lewycky | 3f4cc31 | 2008-03-09 07:50:37 +0000 | [diff] [blame] | 1451 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator())) |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1452 | if (II->getUnwindDest() == BB) { |
| 1453 | // Insert a new branch instruction before the invoke, because this |
| 1454 | // is now a fall through... |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1455 | BranchInst *BI = BranchInst::Create(II->getNormalDest(), II); |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1456 | Pred->getInstList().remove(II); // Take out of symbol table |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1457 | |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1458 | // Insert the call now... |
Chris Lattner | 93e985f | 2007-02-13 02:10:56 +0000 | [diff] [blame] | 1459 | SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end()); |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1460 | CallInst *CI = CallInst::Create(II->getCalledValue(), |
| 1461 | Args.begin(), Args.end(), II->getName(), BI); |
Chris Lattner | 16d0db2 | 2005-05-14 12:21:56 +0000 | [diff] [blame] | 1462 | CI->setCallingConv(II->getCallingConv()); |
Duncan Sands | dc02467 | 2007-11-27 13:23:08 +0000 | [diff] [blame] | 1463 | CI->setParamAttrs(II->getParamAttrs()); |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1464 | // If the invoke produced a value, the Call now does instead |
| 1465 | II->replaceAllUsesWith(CI); |
| 1466 | delete II; |
| 1467 | Changed = true; |
| 1468 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1469 | |
Chris Lattner | e14ea08 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1470 | Preds.pop_back(); |
| 1471 | } |
Chris Lattner | 8e509dd | 2004-02-24 16:09:21 +0000 | [diff] [blame] | 1472 | |
| 1473 | // If this block is now dead, remove it. |
| 1474 | if (pred_begin(BB) == pred_end(BB)) { |
| 1475 | // We know there are no successors, so just nuke the block. |
| 1476 | M->getBasicBlockList().erase(BB); |
| 1477 | return true; |
| 1478 | } |
| 1479 | |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 1480 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
| 1481 | if (isValueEqualityComparison(SI)) { |
| 1482 | // If we only have one predecessor, and if it is a branch on this value, |
| 1483 | // see if that predecessor totally determines the outcome of this switch. |
| 1484 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 1485 | if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred)) |
| 1486 | return SimplifyCFG(BB) || 1; |
| 1487 | |
| 1488 | // If the block only contains the switch, see if we can fold the block |
| 1489 | // away into any preds. |
| 1490 | if (SI == &BB->front()) |
| 1491 | if (FoldValueComparisonIntoPredecessors(SI)) |
| 1492 | return SimplifyCFG(BB) || 1; |
| 1493 | } |
Chris Lattner | 542f149 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1494 | } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 1495 | if (BI->isUnconditional()) { |
Dan Gohman | 02dea8b | 2008-05-23 21:05:58 +0000 | [diff] [blame^] | 1496 | BasicBlock::iterator BBI = BB->getFirstNonPHI(); |
Chris Lattner | 7e66348 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 1497 | |
| 1498 | BasicBlock *Succ = BI->getSuccessor(0); |
| 1499 | if (BBI->isTerminator() && // Terminator is the only non-phi instruction! |
| 1500 | Succ != BB) // Don't hurt infinite loops! |
| 1501 | if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ)) |
| 1502 | return 1; |
| 1503 | |
| 1504 | } else { // Conditional branch |
Reid Spencer | 3ed469c | 2006-11-02 20:25:50 +0000 | [diff] [blame] | 1505 | if (isValueEqualityComparison(BI)) { |
Chris Lattner | 623369a | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 1506 | // If we only have one predecessor, and if it is a branch on this value, |
| 1507 | // see if that predecessor totally determines the outcome of this |
| 1508 | // switch. |
| 1509 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 1510 | if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred)) |
| 1511 | return SimplifyCFG(BB) || 1; |
| 1512 | |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1513 | // This block must be empty, except for the setcond inst, if it exists. |
| 1514 | BasicBlock::iterator I = BB->begin(); |
| 1515 | if (&*I == BI || |
| 1516 | (&*I == cast<Instruction>(BI->getCondition()) && |
| 1517 | &*++I == BI)) |
| 1518 | if (FoldValueComparisonIntoPredecessors(BI)) |
| 1519 | return SimplifyCFG(BB) | true; |
| 1520 | } |
Chris Lattner | eaba3a1 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1521 | |
| 1522 | // If this is a branch on a phi node in the current block, thread control |
| 1523 | // through this block if any PHI node entries are constants. |
| 1524 | if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) |
| 1525 | if (PN->getParent() == BI->getParent()) |
| 1526 | if (FoldCondBranchOnPHI(BI)) |
| 1527 | return SimplifyCFG(BB) | true; |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1528 | |
| 1529 | // If this basic block is ONLY a setcc and a branch, and if a predecessor |
| 1530 | // branches to us and one of our successors, fold the setcc into the |
| 1531 | // predecessor and use logical operations to pick the right destination. |
Chris Lattner | 12fe2b1 | 2004-05-02 05:02:03 +0000 | [diff] [blame] | 1532 | BasicBlock *TrueDest = BI->getSuccessor(0); |
| 1533 | BasicBlock *FalseDest = BI->getSuccessor(1); |
Chris Lattner | decb0ca | 2007-04-17 17:47:54 +0000 | [diff] [blame] | 1534 | if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition())) { |
| 1535 | BasicBlock::iterator CondIt = Cond; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1536 | if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) && |
| 1537 | Cond->getParent() == BB && &BB->front() == Cond && |
Chris Lattner | decb0ca | 2007-04-17 17:47:54 +0000 | [diff] [blame] | 1538 | &*++CondIt == BI && Cond->hasOneUse() && |
Chris Lattner | 12fe2b1 | 2004-05-02 05:02:03 +0000 | [diff] [blame] | 1539 | TrueDest != BB && FalseDest != BB) |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1540 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI) |
| 1541 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | a1f79fb | 2004-05-02 01:00:44 +0000 | [diff] [blame] | 1542 | if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) { |
Chris Lattner | 2636c1b | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1543 | BasicBlock *PredBlock = *PI; |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1544 | if (PBI->getSuccessor(0) == FalseDest || |
| 1545 | PBI->getSuccessor(1) == TrueDest) { |
| 1546 | // Invert the predecessors condition test (xor it with true), |
| 1547 | // which allows us to write this code once. |
| 1548 | Value *NewCond = |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1549 | BinaryOperator::CreateNot(PBI->getCondition(), |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1550 | PBI->getCondition()->getName()+".not", PBI); |
| 1551 | PBI->setCondition(NewCond); |
| 1552 | BasicBlock *OldTrue = PBI->getSuccessor(0); |
| 1553 | BasicBlock *OldFalse = PBI->getSuccessor(1); |
| 1554 | PBI->setSuccessor(0, OldFalse); |
| 1555 | PBI->setSuccessor(1, OldTrue); |
| 1556 | } |
| 1557 | |
Chris Lattner | 299520d | 2006-02-18 00:33:17 +0000 | [diff] [blame] | 1558 | if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) || |
| 1559 | (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) { |
Chris Lattner | 2636c1b | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1560 | // Clone Cond into the predecessor basic block, and or/and the |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1561 | // two conditions together. |
| 1562 | Instruction *New = Cond->clone(); |
Chris Lattner | 2636c1b | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1563 | PredBlock->getInstList().insert(PBI, New); |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1564 | New->takeName(Cond); |
| 1565 | Cond->setName(New->getName()+".old"); |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1566 | Instruction::BinaryOps Opcode = |
| 1567 | PBI->getSuccessor(0) == TrueDest ? |
| 1568 | Instruction::Or : Instruction::And; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1569 | Value *NewCond = |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1570 | BinaryOperator::Create(Opcode, PBI->getCondition(), |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1571 | New, "bothcond", PBI); |
| 1572 | PBI->setCondition(NewCond); |
| 1573 | if (PBI->getSuccessor(0) == BB) { |
Chris Lattner | 2636c1b | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1574 | AddPredecessorToBlock(TrueDest, PredBlock, BB); |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1575 | PBI->setSuccessor(0, TrueDest); |
| 1576 | } |
| 1577 | if (PBI->getSuccessor(1) == BB) { |
Chris Lattner | 2636c1b | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1578 | AddPredecessorToBlock(FalseDest, PredBlock, BB); |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1579 | PBI->setSuccessor(1, FalseDest); |
| 1580 | } |
| 1581 | return SimplifyCFG(BB) | 1; |
| 1582 | } |
| 1583 | } |
Chris Lattner | decb0ca | 2007-04-17 17:47:54 +0000 | [diff] [blame] | 1584 | } |
Chris Lattner | e67fa05 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1585 | |
Chris Lattner | decb0ca | 2007-04-17 17:47:54 +0000 | [diff] [blame] | 1586 | // Scan predessor blocks for conditional branches. |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1587 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 1588 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1589 | if (PBI != BI && PBI->isConditional()) { |
| 1590 | |
| 1591 | // If this block ends with a branch instruction, and if there is a |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1592 | // predecessor that ends on a branch of the same condition, make |
| 1593 | // this conditional branch redundant. |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1594 | if (PBI->getCondition() == BI->getCondition() && |
| 1595 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 1596 | // Okay, the outcome of this conditional branch is statically |
| 1597 | // knowable. If this block had a single pred, handle specially. |
| 1598 | if (BB->getSinglePredecessor()) { |
| 1599 | // Turn this into a branch on constant. |
| 1600 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1601 | BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue)); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1602 | return SimplifyCFG(BB); // Nuke the branch on constant. |
| 1603 | } |
| 1604 | |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1605 | // Otherwise, if there are multiple predecessors, insert a PHI |
| 1606 | // that merges in the constant and simplify the block result. |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1607 | if (BlockIsSimpleEnoughToThreadThrough(BB)) { |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1608 | PHINode *NewPN = PHINode::Create(Type::Int1Ty, |
| 1609 | BI->getCondition()->getName()+".pr", |
| 1610 | BB->begin()); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1611 | for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 1612 | if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) && |
| 1613 | PBI != BI && PBI->isConditional() && |
| 1614 | PBI->getCondition() == BI->getCondition() && |
| 1615 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 1616 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1617 | NewPN->addIncoming(ConstantInt::get(Type::Int1Ty, |
| 1618 | CondIsTrue), *PI); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1619 | } else { |
| 1620 | NewPN->addIncoming(BI->getCondition(), *PI); |
| 1621 | } |
| 1622 | |
| 1623 | BI->setCondition(NewPN); |
| 1624 | // This will thread the branch. |
| 1625 | return SimplifyCFG(BB) | true; |
| 1626 | } |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1627 | } |
| 1628 | |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1629 | // If this is a conditional branch in an empty block, and if any |
| 1630 | // predecessors is a conditional branch to one of our destinations, |
| 1631 | // fold the conditions into logical ops and one cond br. |
| 1632 | if (&BB->front() == BI) { |
| 1633 | int PBIOp, BIOp; |
| 1634 | if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { |
| 1635 | PBIOp = BIOp = 0; |
| 1636 | } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { |
| 1637 | PBIOp = 0; BIOp = 1; |
| 1638 | } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { |
| 1639 | PBIOp = 1; BIOp = 0; |
| 1640 | } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { |
| 1641 | PBIOp = BIOp = 1; |
| 1642 | } else { |
| 1643 | PBIOp = BIOp = -1; |
| 1644 | } |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1645 | |
Chris Lattner | 299520d | 2006-02-18 00:33:17 +0000 | [diff] [blame] | 1646 | // Check to make sure that the other destination of this branch |
| 1647 | // isn't BB itself. If so, this is an infinite loop that will |
| 1648 | // keep getting unwound. |
| 1649 | if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB) |
| 1650 | PBIOp = BIOp = -1; |
Chris Lattner | 822a879 | 2006-11-18 19:19:36 +0000 | [diff] [blame] | 1651 | |
| 1652 | // Do not perform this transformation if it would require |
| 1653 | // insertion of a large number of select instructions. For targets |
| 1654 | // without predication/cmovs, this is a big pessimization. |
| 1655 | if (PBIOp != -1) { |
| 1656 | BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); |
| 1657 | |
| 1658 | unsigned NumPhis = 0; |
| 1659 | for (BasicBlock::iterator II = CommonDest->begin(); |
| 1660 | isa<PHINode>(II); ++II, ++NumPhis) { |
| 1661 | if (NumPhis > 2) { |
| 1662 | // Disable this xform. |
| 1663 | PBIOp = -1; |
| 1664 | break; |
| 1665 | } |
| 1666 | } |
| 1667 | } |
Chris Lattner | 7f2e1dd | 2006-06-12 20:18:01 +0000 | [diff] [blame] | 1668 | |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1669 | // Finally, if everything is ok, fold the branches to logical ops. |
| 1670 | if (PBIOp != -1) { |
| 1671 | BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); |
| 1672 | BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); |
| 1673 | |
Chris Lattner | 7f2e1dd | 2006-06-12 20:18:01 +0000 | [diff] [blame] | 1674 | // If OtherDest *is* BB, then this is a basic block with just |
| 1675 | // a conditional branch in it, where one edge (OtherDesg) goes |
| 1676 | // back to the block. We know that the program doesn't get |
| 1677 | // stuck in the infinite loop, so the condition must be such |
| 1678 | // that OtherDest isn't branched through. Forward to CommonDest, |
| 1679 | // and avoid an infinite loop at optimizer time. |
| 1680 | if (OtherDest == BB) |
| 1681 | OtherDest = CommonDest; |
| 1682 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 1683 | DOUT << "FOLDING BRs:" << *PBI->getParent() |
| 1684 | << "AND: " << *BI->getParent(); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1685 | |
| 1686 | // BI may have other predecessors. Because of this, we leave |
| 1687 | // it alone, but modify PBI. |
| 1688 | |
| 1689 | // Make sure we get to CommonDest on True&True directions. |
| 1690 | Value *PBICond = PBI->getCondition(); |
| 1691 | if (PBIOp) |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1692 | PBICond = BinaryOperator::CreateNot(PBICond, |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1693 | PBICond->getName()+".not", |
| 1694 | PBI); |
| 1695 | Value *BICond = BI->getCondition(); |
| 1696 | if (BIOp) |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1697 | BICond = BinaryOperator::CreateNot(BICond, |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1698 | BICond->getName()+".not", |
| 1699 | PBI); |
| 1700 | // Merge the conditions. |
| 1701 | Value *Cond = |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1702 | BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1703 | |
| 1704 | // Modify PBI to branch on the new condition to the new dests. |
| 1705 | PBI->setCondition(Cond); |
| 1706 | PBI->setSuccessor(0, CommonDest); |
| 1707 | PBI->setSuccessor(1, OtherDest); |
| 1708 | |
| 1709 | // OtherDest may have phi nodes. If so, add an entry from PBI's |
| 1710 | // block that are identical to the entries for BI's block. |
| 1711 | PHINode *PN; |
| 1712 | for (BasicBlock::iterator II = OtherDest->begin(); |
| 1713 | (PN = dyn_cast<PHINode>(II)); ++II) { |
| 1714 | Value *V = PN->getIncomingValueForBlock(BB); |
| 1715 | PN->addIncoming(V, PBI->getParent()); |
| 1716 | } |
| 1717 | |
| 1718 | // We know that the CommonDest already had an edge from PBI to |
| 1719 | // it. If it has PHIs though, the PHIs may have different |
| 1720 | // entries for BB and PBI's BB. If so, insert a select to make |
| 1721 | // them agree. |
| 1722 | for (BasicBlock::iterator II = CommonDest->begin(); |
| 1723 | (PN = dyn_cast<PHINode>(II)); ++II) { |
| 1724 | Value * BIV = PN->getIncomingValueForBlock(BB); |
| 1725 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 1726 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 1727 | if (BIV != PBIV) { |
| 1728 | // Insert a select in PBI to pick the right value. |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1729 | Value *NV = SelectInst::Create(PBICond, PBIV, BIV, |
| 1730 | PBIV->getName()+".mux", PBI); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1731 | PN->setIncomingValue(PBBIdx, NV); |
| 1732 | } |
| 1733 | } |
| 1734 | |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 1735 | DOUT << "INTO: " << *PBI->getParent(); |
Chris Lattner | 263d1e4 | 2005-09-23 18:47:20 +0000 | [diff] [blame] | 1736 | |
| 1737 | // This basic block is probably dead. We know it has at least |
| 1738 | // one fewer predecessor. |
| 1739 | return SimplifyCFG(BB) | true; |
| 1740 | } |
Chris Lattner | 2e42e36 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1741 | } |
Chris Lattner | 92da2c2 | 2004-05-01 22:36:37 +0000 | [diff] [blame] | 1742 | } |
Chris Lattner | d52c261 | 2004-02-24 07:23:58 +0000 | [diff] [blame] | 1743 | } |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1744 | } else if (isa<UnreachableInst>(BB->getTerminator())) { |
| 1745 | // If there are any instructions immediately before the unreachable that can |
| 1746 | // be removed, do so. |
| 1747 | Instruction *Unreachable = BB->getTerminator(); |
| 1748 | while (Unreachable != BB->begin()) { |
| 1749 | BasicBlock::iterator BBI = Unreachable; |
| 1750 | --BBI; |
| 1751 | if (isa<CallInst>(BBI)) break; |
| 1752 | // Delete this instruction |
| 1753 | BB->getInstList().erase(BBI); |
| 1754 | Changed = true; |
| 1755 | } |
| 1756 | |
| 1757 | // If the unreachable instruction is the first in the block, take a gander |
| 1758 | // at all of the predecessors of this instruction, and simplify them. |
| 1759 | if (&BB->front() == Unreachable) { |
Chris Lattner | 8244243 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 1760 | SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1761 | for (unsigned i = 0, e = Preds.size(); i != e; ++i) { |
| 1762 | TerminatorInst *TI = Preds[i]->getTerminator(); |
| 1763 | |
| 1764 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 1765 | if (BI->isUnconditional()) { |
| 1766 | if (BI->getSuccessor(0) == BB) { |
| 1767 | new UnreachableInst(TI); |
| 1768 | TI->eraseFromParent(); |
| 1769 | Changed = true; |
| 1770 | } |
| 1771 | } else { |
| 1772 | if (BI->getSuccessor(0) == BB) { |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1773 | BranchInst::Create(BI->getSuccessor(1), BI); |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1774 | BI->eraseFromParent(); |
| 1775 | } else if (BI->getSuccessor(1) == BB) { |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1776 | BranchInst::Create(BI->getSuccessor(0), BI); |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1777 | BI->eraseFromParent(); |
| 1778 | Changed = true; |
| 1779 | } |
| 1780 | } |
| 1781 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 1782 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
| 1783 | if (SI->getSuccessor(i) == BB) { |
Chris Lattner | 42eb752 | 2005-05-20 22:19:54 +0000 | [diff] [blame] | 1784 | BB->removePredecessor(SI->getParent()); |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1785 | SI->removeCase(i); |
| 1786 | --i; --e; |
| 1787 | Changed = true; |
| 1788 | } |
| 1789 | // If the default value is unreachable, figure out the most popular |
| 1790 | // destination and make it the default. |
| 1791 | if (SI->getSuccessor(0) == BB) { |
| 1792 | std::map<BasicBlock*, unsigned> Popularity; |
| 1793 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
| 1794 | Popularity[SI->getSuccessor(i)]++; |
| 1795 | |
| 1796 | // Find the most popular block. |
| 1797 | unsigned MaxPop = 0; |
| 1798 | BasicBlock *MaxBlock = 0; |
| 1799 | for (std::map<BasicBlock*, unsigned>::iterator |
| 1800 | I = Popularity.begin(), E = Popularity.end(); I != E; ++I) { |
| 1801 | if (I->second > MaxPop) { |
| 1802 | MaxPop = I->second; |
| 1803 | MaxBlock = I->first; |
| 1804 | } |
| 1805 | } |
| 1806 | if (MaxBlock) { |
| 1807 | // Make this the new default, allowing us to delete any explicit |
| 1808 | // edges to it. |
| 1809 | SI->setSuccessor(0, MaxBlock); |
| 1810 | Changed = true; |
| 1811 | |
Chris Lattner | 42eb752 | 2005-05-20 22:19:54 +0000 | [diff] [blame] | 1812 | // If MaxBlock has phinodes in it, remove MaxPop-1 entries from |
| 1813 | // it. |
| 1814 | if (isa<PHINode>(MaxBlock->begin())) |
| 1815 | for (unsigned i = 0; i != MaxPop-1; ++i) |
| 1816 | MaxBlock->removePredecessor(SI->getParent()); |
| 1817 | |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1818 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
| 1819 | if (SI->getSuccessor(i) == MaxBlock) { |
| 1820 | SI->removeCase(i); |
| 1821 | --i; --e; |
| 1822 | } |
| 1823 | } |
| 1824 | } |
| 1825 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { |
| 1826 | if (II->getUnwindDest() == BB) { |
| 1827 | // Convert the invoke to a call instruction. This would be a good |
| 1828 | // place to note that the call does not throw though. |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1829 | BranchInst *BI = BranchInst::Create(II->getNormalDest(), II); |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1830 | II->removeFromParent(); // Take out of symbol table |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1831 | |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1832 | // Insert the call now... |
Chris Lattner | 93e985f | 2007-02-13 02:10:56 +0000 | [diff] [blame] | 1833 | SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end()); |
Gabor Greif | 051a950 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1834 | CallInst *CI = CallInst::Create(II->getCalledValue(), |
| 1835 | Args.begin(), Args.end(), |
| 1836 | II->getName(), BI); |
Chris Lattner | 16d0db2 | 2005-05-14 12:21:56 +0000 | [diff] [blame] | 1837 | CI->setCallingConv(II->getCallingConv()); |
Duncan Sands | dc02467 | 2007-11-27 13:23:08 +0000 | [diff] [blame] | 1838 | CI->setParamAttrs(II->getParamAttrs()); |
Chris Lattner | 698f96f | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1839 | // If the invoke produced a value, the Call does now instead. |
| 1840 | II->replaceAllUsesWith(CI); |
| 1841 | delete II; |
| 1842 | Changed = true; |
| 1843 | } |
| 1844 | } |
| 1845 | } |
| 1846 | |
| 1847 | // If this block is now dead, remove it. |
| 1848 | if (pred_begin(BB) == pred_end(BB)) { |
| 1849 | // We know there are no successors, so just nuke the block. |
| 1850 | M->getBasicBlockList().erase(BB); |
| 1851 | return true; |
| 1852 | } |
| 1853 | } |
Chris Lattner | 19831ec | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1854 | } |
| 1855 | |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1856 | // Merge basic blocks into their predecessor if there is only one distinct |
| 1857 | // pred, and if there is only one distinct successor of the predecessor, and |
| 1858 | // if there are no PHI nodes. |
| 1859 | // |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1860 | pred_iterator PI(pred_begin(BB)), PE(pred_end(BB)); |
| 1861 | BasicBlock *OnlyPred = *PI++; |
| 1862 | for (; PI != PE; ++PI) // Search all predecessors, see if they are all same |
| 1863 | if (*PI != OnlyPred) { |
| 1864 | OnlyPred = 0; // There are multiple different predecessors... |
| 1865 | break; |
| 1866 | } |
Chris Lattner | 92da2c2 | 2004-05-01 22:36:37 +0000 | [diff] [blame] | 1867 | |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1868 | BasicBlock *OnlySucc = 0; |
| 1869 | if (OnlyPred && OnlyPred != BB && // Don't break self loops |
| 1870 | OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) { |
| 1871 | // Check to see if there is only one distinct successor... |
| 1872 | succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred)); |
| 1873 | OnlySucc = BB; |
| 1874 | for (; SI != SE; ++SI) |
| 1875 | if (*SI != OnlySucc) { |
| 1876 | OnlySucc = 0; // There are multiple distinct successors! |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1877 | break; |
| 1878 | } |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1879 | } |
| 1880 | |
Nick Lewycky | 280a6e6 | 2008-04-25 16:53:59 +0000 | [diff] [blame] | 1881 | if (OnlySucc) { |
Bill Wendling | 0d45a09 | 2006-11-26 10:17:54 +0000 | [diff] [blame] | 1882 | DOUT << "Merging: " << *BB << "into: " << *OnlyPred; |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1883 | |
| 1884 | // Resolve any PHI nodes at the start of the block. They are all |
| 1885 | // guaranteed to have exactly one entry if they exist, unless there are |
| 1886 | // multiple duplicate (but guaranteed to be equal) entries for the |
| 1887 | // incoming edges. This occurs when there are multiple edges from |
| 1888 | // OnlyPred to OnlySucc. |
| 1889 | // |
| 1890 | while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { |
| 1891 | PN->replaceAllUsesWith(PN->getIncomingValue(0)); |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1892 | BB->getInstList().pop_front(); // Delete the phi node. |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1893 | } |
| 1894 | |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1895 | // Delete the unconditional branch from the predecessor. |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1896 | OnlyPred->getInstList().pop_back(); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1897 | |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1898 | // Move all definitions in the successor to the predecessor. |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1899 | OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList()); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1900 | |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1901 | // Make all PHI nodes that referred to BB now refer to Pred as their |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1902 | // source. |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1903 | BB->replaceAllUsesWith(OnlyPred); |
Chris Lattner | 1896150 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1904 | |
Chris Lattner | 86cc423 | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1905 | // Inherit predecessors name if it exists. |
| 1906 | if (!OnlyPred->hasName()) |
| 1907 | OnlyPred->takeName(BB); |
| 1908 | |
| 1909 | // Erase basic block from the function. |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1910 | M->getBasicBlockList().erase(BB); |
Chris Lattner | 1896150 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1911 | |
Chris Lattner | 2355f94 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1912 | return true; |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1913 | } |
Chris Lattner | 723c66d | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1914 | |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1915 | // Otherwise, if this block only has a single predecessor, and if that block |
| 1916 | // is a conditional branch, see if we can hoist any code from this block up |
| 1917 | // into our predecessor. |
| 1918 | if (OnlyPred) |
Chris Lattner | 7613437 | 2004-12-10 17:42:31 +0000 | [diff] [blame] | 1919 | if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator())) |
| 1920 | if (BI->isConditional()) { |
| 1921 | // Get the other block. |
| 1922 | BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB); |
| 1923 | PI = pred_begin(OtherBB); |
| 1924 | ++PI; |
| 1925 | if (PI == pred_end(OtherBB)) { |
| 1926 | // We have a conditional branch to two blocks that are only reachable |
| 1927 | // from the condbr. We know that the condbr dominates the two blocks, |
| 1928 | // so see if there is any identical code in the "then" and "else" |
| 1929 | // blocks. If so, we can hoist it up to the branching block. |
| 1930 | Changed |= HoistThenElseCodeToIf(BI); |
| 1931 | } |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1932 | } |
Chris Lattner | 37dc938 | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1933 | |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1934 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 1935 | if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
| 1936 | // Change br (X == 0 | X == 1), T, F into a switch instruction. |
| 1937 | if (BI->isConditional() && isa<Instruction>(BI->getCondition())) { |
| 1938 | Instruction *Cond = cast<Instruction>(BI->getCondition()); |
| 1939 | // If this is a bunch of seteq's or'd together, or if it's a bunch of |
| 1940 | // 'setne's and'ed together, collect them. |
| 1941 | Value *CompVal = 0; |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 1942 | std::vector<ConstantInt*> Values; |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1943 | bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values); |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 1944 | if (CompVal && CompVal->getType()->isInteger()) { |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1945 | // There might be duplicate constants in the list, which the switch |
| 1946 | // instruction can't handle, remove them now. |
Chris Lattner | 1654cff | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 1947 | std::sort(Values.begin(), Values.end(), ConstantIntOrdering()); |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1948 | Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1949 | |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1950 | // Figure out which block is which destination. |
| 1951 | BasicBlock *DefaultBB = BI->getSuccessor(1); |
| 1952 | BasicBlock *EdgeBB = BI->getSuccessor(0); |
| 1953 | if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1954 | |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1955 | // Create the new switch instruction now. |
Gabor Greif | b1dbcd8 | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 1956 | SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB, |
| 1957 | Values.size(), BI); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1958 | |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1959 | // Add all of the 'cases' to the switch instruction. |
| 1960 | for (unsigned i = 0, e = Values.size(); i != e; ++i) |
| 1961 | New->addCase(Values[i], EdgeBB); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1962 | |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1963 | // We added edges from PI to the EdgeBB. As such, if there were any |
| 1964 | // PHI nodes in EdgeBB, they need entries to be added corresponding to |
| 1965 | // the number of edges added. |
| 1966 | for (BasicBlock::iterator BBI = EdgeBB->begin(); |
Reid Spencer | 2da5c3d | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1967 | isa<PHINode>(BBI); ++BBI) { |
| 1968 | PHINode *PN = cast<PHINode>(BBI); |
Chris Lattner | 0d56008 | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1969 | Value *InVal = PN->getIncomingValueForBlock(*PI); |
| 1970 | for (unsigned i = 0, e = Values.size()-1; i != e; ++i) |
| 1971 | PN->addIncoming(InVal, *PI); |
| 1972 | } |
| 1973 | |
| 1974 | // Erase the old branch instruction. |
| 1975 | (*PI)->getInstList().erase(BI); |
| 1976 | |
| 1977 | // Erase the potentially condition tree that was used to computed the |
| 1978 | // branch condition. |
| 1979 | ErasePossiblyDeadInstructionTree(Cond); |
| 1980 | return true; |
| 1981 | } |
| 1982 | } |
| 1983 | |
Chris Lattner | 694e37f | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 1984 | return Changed; |
Chris Lattner | 01d1ee3 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1985 | } |