Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1 | //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by the LLVM research group and is distributed under |
| 6 | // the University of Illinois Open Source License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 9 | // |
Chris Lattner | a704ac8 | 2002-10-08 21:36:33 +0000 | [diff] [blame] | 10 | // Peephole optimize the CFG. |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Chris Lattner | 9734fd0 | 2004-06-20 01:13:18 +0000 | [diff] [blame] | 14 | #define DEBUG_TYPE "simplifycfg" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 15 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 16 | #include "llvm/Constants.h" |
| 17 | #include "llvm/Instructions.h" |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 18 | #include "llvm/Type.h" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 19 | #include "llvm/Support/CFG.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 20 | #include "llvm/Support/Debug.h" |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame^] | 21 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 22 | #include <algorithm> |
| 23 | #include <functional> |
Chris Lattner | a2ab489 | 2004-02-24 07:23:58 +0000 | [diff] [blame] | 24 | #include <set> |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 25 | #include <map> |
Chris Lattner | df3c342 | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 26 | using namespace llvm; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 27 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 28 | /// SafeToMergeTerminators - Return true if it is safe to merge these two |
| 29 | /// terminator instructions together. |
| 30 | /// |
| 31 | static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { |
| 32 | if (SI1 == SI2) return false; // Can't merge with self! |
| 33 | |
| 34 | // It is not safe to merge these two switch instructions if they have a common |
| 35 | // successor, and if that successor has a PHI node, and if *that* PHI node has |
| 36 | // conflicting incoming values from the two switch blocks. |
| 37 | BasicBlock *SI1BB = SI1->getParent(); |
| 38 | BasicBlock *SI2BB = SI2->getParent(); |
| 39 | std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
| 40 | |
| 41 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 42 | if (SI1Succs.count(*I)) |
| 43 | for (BasicBlock::iterator BBI = (*I)->begin(); |
| 44 | isa<PHINode>(BBI); ++BBI) { |
| 45 | PHINode *PN = cast<PHINode>(BBI); |
| 46 | if (PN->getIncomingValueForBlock(SI1BB) != |
| 47 | PN->getIncomingValueForBlock(SI2BB)) |
| 48 | return false; |
| 49 | } |
| 50 | |
| 51 | return true; |
| 52 | } |
| 53 | |
| 54 | /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will |
| 55 | /// now be entries in it from the 'NewPred' block. The values that will be |
| 56 | /// flowing into the PHI nodes will be the same as those coming in from |
| 57 | /// ExistPred, an existing predecessor of Succ. |
| 58 | static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| 59 | BasicBlock *ExistPred) { |
| 60 | assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) != |
| 61 | succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!"); |
| 62 | if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do |
| 63 | |
| 64 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 65 | PHINode *PN = cast<PHINode>(I); |
| 66 | Value *V = PN->getIncomingValueForBlock(ExistPred); |
| 67 | PN->addIncoming(V, NewPred); |
| 68 | } |
| 69 | } |
| 70 | |
Chris Lattner | 982b75c | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 71 | // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an |
| 72 | // almost-empty BB ending in an unconditional branch to Succ, into succ. |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 73 | // |
| 74 | // Assumption: Succ is the single successor for BB. |
| 75 | // |
Chris Lattner | 982b75c | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 76 | static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 77 | assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); |
Chris Lattner | 5325c5f | 2002-09-24 00:09:26 +0000 | [diff] [blame] | 78 | |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 79 | // Check to see if one of the predecessors of BB is already a predecessor of |
Chris Lattner | 31116ba | 2003-03-05 21:01:52 +0000 | [diff] [blame] | 80 | // Succ. If so, we cannot do the transformation if there are any PHI nodes |
| 81 | // with incompatible values coming in from the two edges! |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 82 | // |
Chris Lattner | 9080369 | 2005-08-03 00:38:27 +0000 | [diff] [blame] | 83 | if (isa<PHINode>(Succ->front())) { |
| 84 | std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); |
| 85 | for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);\ |
| 86 | PI != PE; ++PI) |
| 87 | if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) { |
| 88 | // Loop over all of the PHI nodes checking to see if there are |
| 89 | // incompatible values coming in. |
| 90 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 91 | PHINode *PN = cast<PHINode>(I); |
| 92 | // Loop up the entries in the PHI node for BB and for *PI if the |
| 93 | // values coming in are non-equal, we cannot merge these two blocks |
| 94 | // (instead we should insert a conditional move or something, then |
| 95 | // merge the blocks). |
| 96 | if (PN->getIncomingValueForBlock(BB) != |
| 97 | PN->getIncomingValueForBlock(*PI)) |
| 98 | return false; // Values are not equal... |
| 99 | } |
| 100 | } |
| 101 | } |
Chris Lattner | 2dbf196 | 2005-08-03 00:59:12 +0000 | [diff] [blame] | 102 | |
| 103 | // Finally, if BB has PHI nodes that are used by things other than the PHIs in |
| 104 | // Succ and Succ has predecessors that are not Succ and not Pred, we cannot |
| 105 | // fold these blocks, as we don't know whether BB dominates Succ or not to |
| 106 | // update the PHI nodes correctly. |
| 107 | if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 108 | |
Chris Lattner | 2dbf196 | 2005-08-03 00:59:12 +0000 | [diff] [blame] | 109 | // If the predecessors of Succ are only BB and Succ itself, we can handle this. |
| 110 | bool IsSafe = true; |
| 111 | for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI) |
| 112 | if (*PI != Succ && *PI != BB) { |
| 113 | IsSafe = false; |
| 114 | break; |
| 115 | } |
| 116 | if (IsSafe) return true; |
| 117 | |
| 118 | // If the PHI nodes in BB are only used by instructions in Succ, we are ok. |
| 119 | IsSafe = true; |
| 120 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I) && IsSafe; ++I) { |
| 121 | PHINode *PN = cast<PHINode>(I); |
| 122 | for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; |
| 123 | ++UI) |
| 124 | if (cast<Instruction>(*UI)->getParent() != Succ) { |
| 125 | IsSafe = false; |
| 126 | break; |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | return IsSafe; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 131 | } |
| 132 | |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 133 | /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional |
| 134 | /// branch to Succ, and contains no instructions other than PHI nodes and the |
| 135 | /// branch. If possible, eliminate BB. |
| 136 | static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, |
| 137 | BasicBlock *Succ) { |
| 138 | // If our successor has PHI nodes, then we need to update them to include |
| 139 | // entries for BB's predecessors, not for BB itself. Be careful though, |
| 140 | // if this transformation fails (returns true) then we cannot do this |
| 141 | // transformation! |
| 142 | // |
Chris Lattner | 982b75c | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 143 | if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 144 | |
| 145 | DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB); |
| 146 | |
Chris Lattner | 982b75c | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 147 | if (isa<PHINode>(Succ->begin())) { |
| 148 | // If there is more than one pred of succ, and there are PHI nodes in |
| 149 | // the successor, then we need to add incoming edges for the PHI nodes |
| 150 | // |
| 151 | const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); |
| 152 | |
| 153 | // Loop over all of the PHI nodes in the successor of BB. |
| 154 | for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { |
| 155 | PHINode *PN = cast<PHINode>(I); |
| 156 | Value *OldVal = PN->removeIncomingValue(BB, false); |
| 157 | assert(OldVal && "No entry in PHI for Pred BB!"); |
| 158 | |
Chris Lattner | 9080369 | 2005-08-03 00:38:27 +0000 | [diff] [blame] | 159 | // If this incoming value is one of the PHI nodes in BB, the new entries |
| 160 | // in the PHI node are the entries from the old PHI. |
Chris Lattner | 982b75c | 2005-08-03 00:29:26 +0000 | [diff] [blame] | 161 | if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { |
| 162 | PHINode *OldValPN = cast<PHINode>(OldVal); |
| 163 | for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) |
| 164 | PN->addIncoming(OldValPN->getIncomingValue(i), |
| 165 | OldValPN->getIncomingBlock(i)); |
| 166 | } else { |
| 167 | for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), |
| 168 | End = BBPreds.end(); PredI != End; ++PredI) { |
| 169 | // Add an incoming value for each of the new incoming values... |
| 170 | PN->addIncoming(OldVal, *PredI); |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 176 | if (isa<PHINode>(&BB->front())) { |
| 177 | std::vector<BasicBlock*> |
| 178 | OldSuccPreds(pred_begin(Succ), pred_end(Succ)); |
| 179 | |
| 180 | // Move all PHI nodes in BB to Succ if they are alive, otherwise |
| 181 | // delete them. |
| 182 | while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) |
Chris Lattner | 9080369 | 2005-08-03 00:38:27 +0000 | [diff] [blame] | 183 | if (PN->use_empty()) { |
| 184 | // Just remove the dead phi. This happens if Succ's PHIs were the only |
| 185 | // users of the PHI nodes. |
| 186 | PN->eraseFromParent(); |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 187 | } else { |
| 188 | // The instruction is alive, so this means that Succ must have |
| 189 | // *ONLY* had BB as a predecessor, and the PHI node is still valid |
| 190 | // now. Simply move it into Succ, because we know that BB |
| 191 | // strictly dominated Succ. |
Chris Lattner | 1f047fd | 2005-08-03 00:23:42 +0000 | [diff] [blame] | 192 | Succ->getInstList().splice(Succ->begin(), |
| 193 | BB->getInstList(), BB->begin()); |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 194 | |
| 195 | // We need to add new entries for the PHI node to account for |
| 196 | // predecessors of Succ that the PHI node does not take into |
| 197 | // account. At this point, since we know that BB dominated succ, |
| 198 | // this means that we should any newly added incoming edges should |
| 199 | // use the PHI node as the value for these edges, because they are |
| 200 | // loop back edges. |
| 201 | for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i) |
| 202 | if (OldSuccPreds[i] != BB) |
| 203 | PN->addIncoming(PN, OldSuccPreds[i]); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // Everything that jumped to BB now goes to Succ. |
| 208 | std::string OldName = BB->getName(); |
| 209 | BB->replaceAllUsesWith(Succ); |
| 210 | BB->eraseFromParent(); // Delete the old basic block. |
| 211 | |
| 212 | if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can |
| 213 | Succ->setName(OldName); |
| 214 | return true; |
| 215 | } |
| 216 | |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 217 | /// GetIfCondition - Given a basic block (BB) with two predecessors (and |
| 218 | /// presumably PHI nodes in it), check to see if the merge at this block is due |
| 219 | /// to an "if condition". If so, return the boolean condition that determines |
| 220 | /// which entry into BB will be taken. Also, return by references the block |
| 221 | /// that will be entered from if the condition is true, and the block that will |
| 222 | /// be entered if the condition is false. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 223 | /// |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 224 | /// |
| 225 | static Value *GetIfCondition(BasicBlock *BB, |
| 226 | BasicBlock *&IfTrue, BasicBlock *&IfFalse) { |
| 227 | assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 && |
| 228 | "Function can only handle blocks with 2 predecessors!"); |
| 229 | BasicBlock *Pred1 = *pred_begin(BB); |
| 230 | BasicBlock *Pred2 = *++pred_begin(BB); |
| 231 | |
| 232 | // We can only handle branches. Other control flow will be lowered to |
| 233 | // branches if possible anyway. |
| 234 | if (!isa<BranchInst>(Pred1->getTerminator()) || |
| 235 | !isa<BranchInst>(Pred2->getTerminator())) |
| 236 | return 0; |
| 237 | BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator()); |
| 238 | BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator()); |
| 239 | |
| 240 | // Eliminate code duplication by ensuring that Pred1Br is conditional if |
| 241 | // either are. |
| 242 | if (Pred2Br->isConditional()) { |
| 243 | // If both branches are conditional, we don't have an "if statement". In |
| 244 | // reality, we could transform this case, but since the condition will be |
| 245 | // required anyway, we stand no chance of eliminating it, so the xform is |
| 246 | // probably not profitable. |
| 247 | if (Pred1Br->isConditional()) |
| 248 | return 0; |
| 249 | |
| 250 | std::swap(Pred1, Pred2); |
| 251 | std::swap(Pred1Br, Pred2Br); |
| 252 | } |
| 253 | |
| 254 | if (Pred1Br->isConditional()) { |
| 255 | // If we found a conditional branch predecessor, make sure that it branches |
| 256 | // to BB and Pred2Br. If it doesn't, this isn't an "if statement". |
| 257 | if (Pred1Br->getSuccessor(0) == BB && |
| 258 | Pred1Br->getSuccessor(1) == Pred2) { |
| 259 | IfTrue = Pred1; |
| 260 | IfFalse = Pred2; |
| 261 | } else if (Pred1Br->getSuccessor(0) == Pred2 && |
| 262 | Pred1Br->getSuccessor(1) == BB) { |
| 263 | IfTrue = Pred2; |
| 264 | IfFalse = Pred1; |
| 265 | } else { |
| 266 | // We know that one arm of the conditional goes to BB, so the other must |
| 267 | // go somewhere unrelated, and this must not be an "if statement". |
| 268 | return 0; |
| 269 | } |
| 270 | |
| 271 | // The only thing we have to watch out for here is to make sure that Pred2 |
| 272 | // doesn't have incoming edges from other blocks. If it does, the condition |
| 273 | // doesn't dominate BB. |
| 274 | if (++pred_begin(Pred2) != pred_end(Pred2)) |
| 275 | return 0; |
| 276 | |
| 277 | return Pred1Br->getCondition(); |
| 278 | } |
| 279 | |
| 280 | // Ok, if we got here, both predecessors end with an unconditional branch to |
| 281 | // BB. Don't panic! If both blocks only have a single (identical) |
| 282 | // predecessor, and THAT is a conditional branch, then we're all ok! |
| 283 | if (pred_begin(Pred1) == pred_end(Pred1) || |
| 284 | ++pred_begin(Pred1) != pred_end(Pred1) || |
| 285 | pred_begin(Pred2) == pred_end(Pred2) || |
| 286 | ++pred_begin(Pred2) != pred_end(Pred2) || |
| 287 | *pred_begin(Pred1) != *pred_begin(Pred2)) |
| 288 | return 0; |
| 289 | |
| 290 | // Otherwise, if this is a conditional branch, then we can use it! |
| 291 | BasicBlock *CommonPred = *pred_begin(Pred1); |
| 292 | if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) { |
| 293 | assert(BI->isConditional() && "Two successors but not conditional?"); |
| 294 | if (BI->getSuccessor(0) == Pred1) { |
| 295 | IfTrue = Pred1; |
| 296 | IfFalse = Pred2; |
| 297 | } else { |
| 298 | IfTrue = Pred2; |
| 299 | IfFalse = Pred1; |
| 300 | } |
| 301 | return BI->getCondition(); |
| 302 | } |
| 303 | return 0; |
| 304 | } |
| 305 | |
| 306 | |
| 307 | // If we have a merge point of an "if condition" as accepted above, return true |
| 308 | // if the specified value dominates the block. We don't handle the true |
| 309 | // generality of domination here, just a special case which works well enough |
| 310 | // for us. |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 311 | // |
| 312 | // If AggressiveInsts is non-null, and if V does not dominate BB, we check to |
| 313 | // see if V (which must be an instruction) is cheap to compute and is |
| 314 | // non-trapping. If both are true, the instruction is inserted into the set and |
| 315 | // true is returned. |
| 316 | static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
| 317 | std::set<Instruction*> *AggressiveInsts) { |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 318 | Instruction *I = dyn_cast<Instruction>(V); |
| 319 | if (!I) return true; // Non-instructions all dominate instructions. |
| 320 | BasicBlock *PBB = I->getParent(); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 321 | |
Chris Lattner | 0ce80cd | 2005-02-27 06:18:25 +0000 | [diff] [blame] | 322 | // We don't want to allow weird loops that might have the "if condition" in |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 323 | // the bottom of this block. |
| 324 | if (PBB == BB) return false; |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 325 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 326 | // If this instruction is defined in a block that contains an unconditional |
| 327 | // branch to BB, then it must be in the 'conditional' part of the "if |
| 328 | // statement". |
| 329 | if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator())) |
| 330 | if (BI->isUnconditional() && BI->getSuccessor(0) == BB) { |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 331 | if (!AggressiveInsts) return false; |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 332 | // Okay, it looks like the instruction IS in the "condition". Check to |
| 333 | // see if its a cheap instruction to unconditionally compute, and if it |
| 334 | // only uses stuff defined outside of the condition. If so, hoist it out. |
| 335 | switch (I->getOpcode()) { |
| 336 | default: return false; // Cannot hoist this out safely. |
| 337 | case Instruction::Load: |
| 338 | // We can hoist loads that are non-volatile and obviously cannot trap. |
| 339 | if (cast<LoadInst>(I)->isVolatile()) |
| 340 | return false; |
| 341 | if (!isa<AllocaInst>(I->getOperand(0)) && |
Reid Spencer | ef784f0 | 2004-07-18 00:32:14 +0000 | [diff] [blame] | 342 | !isa<Constant>(I->getOperand(0))) |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 343 | return false; |
| 344 | |
| 345 | // Finally, we have to check to make sure there are no instructions |
| 346 | // before the load in its basic block, as we are going to hoist the loop |
| 347 | // out to its predecessor. |
| 348 | if (PBB->begin() != BasicBlock::iterator(I)) |
| 349 | return false; |
| 350 | break; |
| 351 | case Instruction::Add: |
| 352 | case Instruction::Sub: |
| 353 | case Instruction::And: |
| 354 | case Instruction::Or: |
| 355 | case Instruction::Xor: |
| 356 | case Instruction::Shl: |
| 357 | case Instruction::Shr: |
Chris Lattner | b38b443 | 2005-04-21 05:31:13 +0000 | [diff] [blame] | 358 | case Instruction::SetEQ: |
| 359 | case Instruction::SetNE: |
| 360 | case Instruction::SetLT: |
| 361 | case Instruction::SetGT: |
| 362 | case Instruction::SetLE: |
| 363 | case Instruction::SetGE: |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 364 | break; // These are all cheap and non-trapping instructions. |
| 365 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 366 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 367 | // Okay, we can only really hoist these out if their operands are not |
| 368 | // defined in the conditional region. |
| 369 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 370 | if (!DominatesMergePoint(I->getOperand(i), BB, 0)) |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 371 | return false; |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 372 | // Okay, it's safe to do this! Remember this instruction. |
| 373 | AggressiveInsts->insert(I); |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 374 | } |
| 375 | |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 376 | return true; |
| 377 | } |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 378 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 379 | // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq |
| 380 | // instructions that compare a value against a constant, return the value being |
| 381 | // compared, and stick the constant into the Values vector. |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 382 | static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){ |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 383 | if (Instruction *Inst = dyn_cast<Instruction>(V)) |
| 384 | if (Inst->getOpcode() == Instruction::SetEQ) { |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 385 | if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) { |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 386 | Values.push_back(C); |
| 387 | return Inst->getOperand(0); |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 388 | } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) { |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 389 | Values.push_back(C); |
| 390 | return Inst->getOperand(1); |
| 391 | } |
| 392 | } else if (Inst->getOpcode() == Instruction::Or) { |
| 393 | if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values)) |
| 394 | if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values)) |
| 395 | if (LHS == RHS) |
| 396 | return LHS; |
| 397 | } |
| 398 | return 0; |
| 399 | } |
| 400 | |
| 401 | // GatherConstantSetNEs - Given a potentially 'and'd together collection of |
| 402 | // setne instructions that compare a value against a constant, return the value |
| 403 | // being compared, and stick the constant into the Values vector. |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 404 | static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){ |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 405 | if (Instruction *Inst = dyn_cast<Instruction>(V)) |
| 406 | if (Inst->getOpcode() == Instruction::SetNE) { |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 407 | if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) { |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 408 | Values.push_back(C); |
| 409 | return Inst->getOperand(0); |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 410 | } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) { |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 411 | Values.push_back(C); |
| 412 | return Inst->getOperand(1); |
| 413 | } |
| 414 | } else if (Inst->getOpcode() == Instruction::Cast) { |
| 415 | // Cast of X to bool is really a comparison against zero. |
| 416 | assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!"); |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 417 | Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0)); |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 418 | return Inst->getOperand(0); |
| 419 | } else if (Inst->getOpcode() == Instruction::And) { |
| 420 | if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values)) |
| 421 | if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values)) |
| 422 | if (LHS == RHS) |
| 423 | return LHS; |
| 424 | } |
| 425 | return 0; |
| 426 | } |
| 427 | |
| 428 | |
| 429 | |
| 430 | /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a |
| 431 | /// bunch of comparisons of one value against constants, return the value and |
| 432 | /// the constants being compared. |
| 433 | static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal, |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 434 | std::vector<ConstantInt*> &Values) { |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 435 | if (Cond->getOpcode() == Instruction::Or) { |
| 436 | CompVal = GatherConstantSetEQs(Cond, Values); |
| 437 | |
| 438 | // Return true to indicate that the condition is true if the CompVal is |
| 439 | // equal to one of the constants. |
| 440 | return true; |
| 441 | } else if (Cond->getOpcode() == Instruction::And) { |
| 442 | CompVal = GatherConstantSetNEs(Cond, Values); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 443 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 444 | // Return false to indicate that the condition is false if the CompVal is |
| 445 | // equal to one of the constants. |
| 446 | return false; |
| 447 | } |
| 448 | return false; |
| 449 | } |
| 450 | |
| 451 | /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and |
| 452 | /// has no side effects, nuke it. If it uses any instructions that become dead |
| 453 | /// because the instruction is now gone, nuke them too. |
| 454 | static void ErasePossiblyDeadInstructionTree(Instruction *I) { |
| 455 | if (isInstructionTriviallyDead(I)) { |
| 456 | std::vector<Value*> Operands(I->op_begin(), I->op_end()); |
| 457 | I->getParent()->getInstList().erase(I); |
| 458 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 459 | if (Instruction *OpI = dyn_cast<Instruction>(Operands[i])) |
| 460 | ErasePossiblyDeadInstructionTree(OpI); |
| 461 | } |
| 462 | } |
| 463 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 464 | // isValueEqualityComparison - Return true if the specified terminator checks to |
| 465 | // see if a value is equal to constant integer value. |
| 466 | static Value *isValueEqualityComparison(TerminatorInst *TI) { |
Chris Lattner | a64923a | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 467 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 468 | // Do not permit merging of large switch instructions into their |
| 469 | // predecessors unless there is only one predecessor. |
| 470 | if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()), |
| 471 | pred_end(SI->getParent())) > 128) |
| 472 | return 0; |
| 473 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 474 | return SI->getCondition(); |
Chris Lattner | a64923a | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 475 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 476 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
| 477 | if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
| 478 | if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition())) |
| 479 | if ((SCI->getOpcode() == Instruction::SetEQ || |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 480 | SCI->getOpcode() == Instruction::SetNE) && |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 481 | isa<ConstantInt>(SCI->getOperand(1))) |
| 482 | return SCI->getOperand(0); |
| 483 | return 0; |
| 484 | } |
| 485 | |
| 486 | // Given a value comparison instruction, decode all of the 'cases' that it |
| 487 | // represents and return the 'default' block. |
| 488 | static BasicBlock * |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 489 | GetValueEqualityComparisonCases(TerminatorInst *TI, |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 490 | std::vector<std::pair<ConstantInt*, |
| 491 | BasicBlock*> > &Cases) { |
| 492 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 493 | Cases.reserve(SI->getNumCases()); |
| 494 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
Chris Lattner | cc6d75f | 2005-02-26 18:33:28 +0000 | [diff] [blame] | 495 | Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i))); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 496 | return SI->getDefaultDest(); |
| 497 | } |
| 498 | |
| 499 | BranchInst *BI = cast<BranchInst>(TI); |
| 500 | SetCondInst *SCI = cast<SetCondInst>(BI->getCondition()); |
| 501 | Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)), |
| 502 | BI->getSuccessor(SCI->getOpcode() == |
| 503 | Instruction::SetNE))); |
| 504 | return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ); |
| 505 | } |
| 506 | |
| 507 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 508 | // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries |
| 509 | // in the list that match the specified block. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 510 | static void EliminateBlockCases(BasicBlock *BB, |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 511 | std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) { |
| 512 | for (unsigned i = 0, e = Cases.size(); i != e; ++i) |
| 513 | if (Cases[i].second == BB) { |
| 514 | Cases.erase(Cases.begin()+i); |
| 515 | --i; --e; |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as |
| 520 | // well. |
| 521 | static bool |
| 522 | ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1, |
| 523 | std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) { |
| 524 | std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2; |
| 525 | |
| 526 | // Make V1 be smaller than V2. |
| 527 | if (V1->size() > V2->size()) |
| 528 | std::swap(V1, V2); |
| 529 | |
| 530 | if (V1->size() == 0) return false; |
| 531 | if (V1->size() == 1) { |
| 532 | // Just scan V2. |
| 533 | ConstantInt *TheVal = (*V1)[0].first; |
| 534 | for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| 535 | if (TheVal == (*V2)[i].first) |
| 536 | return true; |
| 537 | } |
| 538 | |
| 539 | // Otherwise, just sort both lists and compare element by element. |
| 540 | std::sort(V1->begin(), V1->end()); |
| 541 | std::sort(V2->begin(), V2->end()); |
| 542 | unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| 543 | while (i1 != e1 && i2 != e2) { |
| 544 | if ((*V1)[i1].first == (*V2)[i2].first) |
| 545 | return true; |
| 546 | if ((*V1)[i1].first < (*V2)[i2].first) |
| 547 | ++i1; |
| 548 | else |
| 549 | ++i2; |
| 550 | } |
| 551 | return false; |
| 552 | } |
| 553 | |
| 554 | // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a |
| 555 | // terminator instruction and its block is known to only have a single |
| 556 | // predecessor block, check to see if that predecessor is also a value |
| 557 | // comparison with the same value, and if that comparison determines the outcome |
| 558 | // of this comparison. If so, simplify TI. This does a very limited form of |
| 559 | // jump threading. |
| 560 | static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
| 561 | BasicBlock *Pred) { |
| 562 | Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
| 563 | if (!PredVal) return false; // Not a value comparison in predecessor. |
| 564 | |
| 565 | Value *ThisVal = isValueEqualityComparison(TI); |
| 566 | assert(ThisVal && "This isn't a value comparison!!"); |
| 567 | if (ThisVal != PredVal) return false; // Different predicates. |
| 568 | |
| 569 | // Find out information about when control will move from Pred to TI's block. |
| 570 | std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases; |
| 571 | BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), |
| 572 | PredCases); |
| 573 | EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 574 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 575 | // Find information about how control leaves this block. |
| 576 | std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases; |
| 577 | BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
| 578 | EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
| 579 | |
| 580 | // If TI's block is the default block from Pred's comparison, potentially |
| 581 | // simplify TI based on this knowledge. |
| 582 | if (PredDef == TI->getParent()) { |
| 583 | // If we are here, we know that the value is none of those cases listed in |
| 584 | // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| 585 | // can simplify TI. |
| 586 | if (ValuesOverlap(PredCases, ThisCases)) { |
| 587 | if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) { |
| 588 | // Okay, one of the successors of this condbr is dead. Convert it to a |
| 589 | // uncond br. |
| 590 | assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| 591 | Value *Cond = BTI->getCondition(); |
| 592 | // Insert the new branch. |
| 593 | Instruction *NI = new BranchInst(ThisDef, TI); |
| 594 | |
| 595 | // Remove PHI node entries for the dead edge. |
| 596 | ThisCases[0].second->removePredecessor(TI->getParent()); |
| 597 | |
| 598 | DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator() |
| 599 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
| 600 | |
| 601 | TI->eraseFromParent(); // Nuke the old one. |
| 602 | // If condition is now dead, nuke it. |
| 603 | if (Instruction *CondI = dyn_cast<Instruction>(Cond)) |
| 604 | ErasePossiblyDeadInstructionTree(CondI); |
| 605 | return true; |
| 606 | |
| 607 | } else { |
| 608 | SwitchInst *SI = cast<SwitchInst>(TI); |
| 609 | // Okay, TI has cases that are statically dead, prune them away. |
| 610 | std::set<Constant*> DeadCases; |
| 611 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 612 | DeadCases.insert(PredCases[i].first); |
| 613 | |
| 614 | DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator() |
| 615 | << "Through successor TI: " << *TI); |
| 616 | |
| 617 | for (unsigned i = SI->getNumCases()-1; i != 0; --i) |
| 618 | if (DeadCases.count(SI->getCaseValue(i))) { |
| 619 | SI->getSuccessor(i)->removePredecessor(TI->getParent()); |
| 620 | SI->removeCase(i); |
| 621 | } |
| 622 | |
| 623 | DEBUG(std::cerr << "Leaving: " << *TI << "\n"); |
| 624 | return true; |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | } else { |
| 629 | // Otherwise, TI's block must correspond to some matched value. Find out |
| 630 | // which value (or set of values) this is. |
| 631 | ConstantInt *TIV = 0; |
| 632 | BasicBlock *TIBB = TI->getParent(); |
| 633 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 634 | if (PredCases[i].second == TIBB) |
| 635 | if (TIV == 0) |
| 636 | TIV = PredCases[i].first; |
| 637 | else |
| 638 | return false; // Cannot handle multiple values coming to this block. |
| 639 | assert(TIV && "No edge from pred to succ?"); |
| 640 | |
| 641 | // Okay, we found the one constant that our value can be if we get into TI's |
| 642 | // BB. Find out which successor will unconditionally be branched to. |
| 643 | BasicBlock *TheRealDest = 0; |
| 644 | for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| 645 | if (ThisCases[i].first == TIV) { |
| 646 | TheRealDest = ThisCases[i].second; |
| 647 | break; |
| 648 | } |
| 649 | |
| 650 | // If not handled by any explicit cases, it is handled by the default case. |
| 651 | if (TheRealDest == 0) TheRealDest = ThisDef; |
| 652 | |
| 653 | // Remove PHI node entries for dead edges. |
| 654 | BasicBlock *CheckEdge = TheRealDest; |
| 655 | for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) |
| 656 | if (*SI != CheckEdge) |
| 657 | (*SI)->removePredecessor(TIBB); |
| 658 | else |
| 659 | CheckEdge = 0; |
| 660 | |
| 661 | // Insert the new branch. |
| 662 | Instruction *NI = new BranchInst(TheRealDest, TI); |
| 663 | |
| 664 | DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator() |
| 665 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
| 666 | Instruction *Cond = 0; |
| 667 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
| 668 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
| 669 | TI->eraseFromParent(); // Nuke the old one. |
| 670 | |
| 671 | if (Cond) ErasePossiblyDeadInstructionTree(Cond); |
| 672 | return true; |
| 673 | } |
| 674 | return false; |
| 675 | } |
| 676 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 677 | // FoldValueComparisonIntoPredecessors - The specified terminator is a value |
| 678 | // equality comparison instruction (either a switch or a branch on "X == c"). |
| 679 | // See if any of the predecessors of the terminator block are value comparisons |
| 680 | // on the same value. If so, and if safe to do so, fold them together. |
| 681 | static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) { |
| 682 | BasicBlock *BB = TI->getParent(); |
| 683 | Value *CV = isValueEqualityComparison(TI); // CondVal |
| 684 | assert(CV && "Not a comparison?"); |
| 685 | bool Changed = false; |
| 686 | |
| 687 | std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); |
| 688 | while (!Preds.empty()) { |
| 689 | BasicBlock *Pred = Preds.back(); |
| 690 | Preds.pop_back(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 691 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 692 | // See if the predecessor is a comparison with the same value. |
| 693 | TerminatorInst *PTI = Pred->getTerminator(); |
| 694 | Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
| 695 | |
| 696 | if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { |
| 697 | // Figure out which 'cases' to copy from SI to PSI. |
| 698 | std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases; |
| 699 | BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| 700 | |
| 701 | std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases; |
| 702 | BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| 703 | |
| 704 | // Based on whether the default edge from PTI goes to BB or not, fill in |
| 705 | // PredCases and PredDefault with the new switch cases we would like to |
| 706 | // build. |
| 707 | std::vector<BasicBlock*> NewSuccessors; |
| 708 | |
| 709 | if (PredDefault == BB) { |
| 710 | // If this is the default destination from PTI, only the edges in TI |
| 711 | // that don't occur in PTI, or that branch to BB will be activated. |
| 712 | std::set<ConstantInt*> PTIHandled; |
| 713 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 714 | if (PredCases[i].second != BB) |
| 715 | PTIHandled.insert(PredCases[i].first); |
| 716 | else { |
| 717 | // The default destination is BB, we don't need explicit targets. |
| 718 | std::swap(PredCases[i], PredCases.back()); |
| 719 | PredCases.pop_back(); |
| 720 | --i; --e; |
| 721 | } |
| 722 | |
| 723 | // Reconstruct the new switch statement we will be building. |
| 724 | if (PredDefault != BBDefault) { |
| 725 | PredDefault->removePredecessor(Pred); |
| 726 | PredDefault = BBDefault; |
| 727 | NewSuccessors.push_back(BBDefault); |
| 728 | } |
| 729 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 730 | if (!PTIHandled.count(BBCases[i].first) && |
| 731 | BBCases[i].second != BBDefault) { |
| 732 | PredCases.push_back(BBCases[i]); |
| 733 | NewSuccessors.push_back(BBCases[i].second); |
| 734 | } |
| 735 | |
| 736 | } else { |
| 737 | // If this is not the default destination from PSI, only the edges |
| 738 | // in SI that occur in PSI with a destination of BB will be |
| 739 | // activated. |
| 740 | std::set<ConstantInt*> PTIHandled; |
| 741 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 742 | if (PredCases[i].second == BB) { |
| 743 | PTIHandled.insert(PredCases[i].first); |
| 744 | std::swap(PredCases[i], PredCases.back()); |
| 745 | PredCases.pop_back(); |
| 746 | --i; --e; |
| 747 | } |
| 748 | |
| 749 | // Okay, now we know which constants were sent to BB from the |
| 750 | // predecessor. Figure out where they will all go now. |
| 751 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 752 | if (PTIHandled.count(BBCases[i].first)) { |
| 753 | // If this is one we are capable of getting... |
| 754 | PredCases.push_back(BBCases[i]); |
| 755 | NewSuccessors.push_back(BBCases[i].second); |
| 756 | PTIHandled.erase(BBCases[i].first);// This constant is taken care of |
| 757 | } |
| 758 | |
| 759 | // If there are any constants vectored to BB that TI doesn't handle, |
| 760 | // they must go to the default destination of TI. |
| 761 | for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(), |
| 762 | E = PTIHandled.end(); I != E; ++I) { |
| 763 | PredCases.push_back(std::make_pair(*I, BBDefault)); |
| 764 | NewSuccessors.push_back(BBDefault); |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | // Okay, at this point, we know which new successor Pred will get. Make |
| 769 | // sure we update the number of entries in the PHI nodes for these |
| 770 | // successors. |
| 771 | for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) |
| 772 | AddPredecessorToBlock(NewSuccessors[i], Pred, BB); |
| 773 | |
| 774 | // Now that the successors are updated, create the new Switch instruction. |
Chris Lattner | a35dfce | 2005-01-29 00:38:26 +0000 | [diff] [blame] | 775 | SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 776 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 777 | NewSI->addCase(PredCases[i].first, PredCases[i].second); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 778 | |
| 779 | Instruction *DeadCond = 0; |
| 780 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) |
| 781 | // If PTI is a branch, remember the condition. |
| 782 | DeadCond = dyn_cast<Instruction>(BI->getCondition()); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 783 | Pred->getInstList().erase(PTI); |
| 784 | |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 785 | // If the condition is dead now, remove the instruction tree. |
| 786 | if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond); |
| 787 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 788 | // Okay, last check. If BB is still a successor of PSI, then we must |
| 789 | // have an infinite loop case. If so, add an infinitely looping block |
| 790 | // to handle the case to preserve the behavior of the code. |
| 791 | BasicBlock *InfLoopBlock = 0; |
| 792 | for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| 793 | if (NewSI->getSuccessor(i) == BB) { |
| 794 | if (InfLoopBlock == 0) { |
| 795 | // Insert it at the end of the loop, because it's either code, |
| 796 | // or it won't matter if it's hot. :) |
| 797 | InfLoopBlock = new BasicBlock("infloop", BB->getParent()); |
| 798 | new BranchInst(InfLoopBlock, InfLoopBlock); |
| 799 | } |
| 800 | NewSI->setSuccessor(i, InfLoopBlock); |
| 801 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 802 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 803 | Changed = true; |
| 804 | } |
| 805 | } |
| 806 | return Changed; |
| 807 | } |
| 808 | |
Chris Lattner | d683bdd | 2005-08-03 17:59:45 +0000 | [diff] [blame] | 809 | /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 810 | /// BB2, hoist any common code in the two blocks up into the branch block. The |
| 811 | /// caller of this function guarantees that BI's block dominates BB1 and BB2. |
| 812 | static bool HoistThenElseCodeToIf(BranchInst *BI) { |
| 813 | // This does very trivial matching, with limited scanning, to find identical |
| 814 | // instructions in the two blocks. In particular, we don't want to get into |
| 815 | // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| 816 | // such, we currently just scan for obviously identical instructions in an |
| 817 | // identical order. |
| 818 | BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| 819 | BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
| 820 | |
| 821 | Instruction *I1 = BB1->begin(), *I2 = BB2->begin(); |
Chris Lattner | d683bdd | 2005-08-03 17:59:45 +0000 | [diff] [blame] | 822 | if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2) || |
| 823 | isa<PHINode>(I1)) |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 824 | return false; |
| 825 | |
| 826 | // If we get here, we can hoist at least one instruction. |
| 827 | BasicBlock *BIParent = BI->getParent(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 828 | |
| 829 | do { |
| 830 | // If we are hoisting the terminator instruction, don't move one (making a |
| 831 | // broken BB), instead clone it, and remove BI. |
| 832 | if (isa<TerminatorInst>(I1)) |
| 833 | goto HoistTerminator; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 834 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 835 | // For a normal instruction, we just move one to right before the branch, |
| 836 | // then replace all uses of the other with the first. Finally, we remove |
| 837 | // the now redundant second instruction. |
| 838 | BIParent->getInstList().splice(BI, BB1->getInstList(), I1); |
| 839 | if (!I2->use_empty()) |
| 840 | I2->replaceAllUsesWith(I1); |
| 841 | BB2->getInstList().erase(I2); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 842 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 843 | I1 = BB1->begin(); |
| 844 | I2 = BB2->begin(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 845 | } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2)); |
| 846 | |
| 847 | return true; |
| 848 | |
| 849 | HoistTerminator: |
| 850 | // Okay, it is safe to hoist the terminator. |
| 851 | Instruction *NT = I1->clone(); |
| 852 | BIParent->getInstList().insert(BI, NT); |
| 853 | if (NT->getType() != Type::VoidTy) { |
| 854 | I1->replaceAllUsesWith(NT); |
| 855 | I2->replaceAllUsesWith(NT); |
| 856 | NT->setName(I1->getName()); |
| 857 | } |
| 858 | |
| 859 | // Hoisting one of the terminators from our successor is a great thing. |
| 860 | // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| 861 | // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| 862 | // nodes, so we insert select instruction to compute the final result. |
| 863 | std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; |
| 864 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
| 865 | PHINode *PN; |
| 866 | for (BasicBlock::iterator BBI = SI->begin(); |
Chris Lattner | 0194457 | 2004-11-30 07:47:34 +0000 | [diff] [blame] | 867 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 868 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 869 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 870 | if (BB1V != BB2V) { |
| 871 | // These values do not agree. Insert a select instruction before NT |
| 872 | // that determines the right value. |
| 873 | SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
| 874 | if (SI == 0) |
| 875 | SI = new SelectInst(BI->getCondition(), BB1V, BB2V, |
| 876 | BB1V->getName()+"."+BB2V->getName(), NT); |
| 877 | // Make the PHI node use the select for all incoming values for BB1/BB2 |
| 878 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 879 | if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) |
| 880 | PN->setIncomingValue(i, SI); |
| 881 | } |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | // Update any PHI nodes in our new successors. |
| 886 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) |
| 887 | AddPredecessorToBlock(*SI, BIParent, BB1); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 888 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 889 | BI->eraseFromParent(); |
| 890 | return true; |
| 891 | } |
| 892 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame^] | 893 | /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value |
| 894 | /// that is defined in the same block as the branch and if any PHI entries are |
| 895 | /// constants, thread edges corresponding to that entry to be branches to their |
| 896 | /// ultimate destination. |
| 897 | static bool FoldCondBranchOnPHI(BranchInst *BI) { |
| 898 | BasicBlock *BB = BI->getParent(); |
| 899 | PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
| 900 | if (!PN || PN->getParent() != BB) return false; |
| 901 | |
| 902 | // Degenerate case of a single entry PHI. |
| 903 | if (PN->getNumIncomingValues() == 1) { |
| 904 | if (PN->getIncomingValue(0) != PN) |
| 905 | PN->replaceAllUsesWith(PN->getIncomingValue(0)); |
| 906 | else |
| 907 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
| 908 | PN->eraseFromParent(); |
| 909 | return true; |
| 910 | } |
| 911 | |
| 912 | // Now we know that this block has multiple preds and two succs. |
| 913 | |
| 914 | // If this basic block contains anything other than the PHI and branch, bail |
| 915 | // out. FIXME: improve this in the future. |
| 916 | BasicBlock::iterator BBI = BB->begin(); |
| 917 | if (&*BBI != PN || &*++BBI != BI) |
| 918 | return false; |
| 919 | |
| 920 | // Okay, this is a simple enough basic block. See if any phi values are |
| 921 | // constants. |
| 922 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 923 | if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) { |
| 924 | // Okay, we now know that all edges from PredBB should be revectored to |
| 925 | // branch to RealDest. |
| 926 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
| 927 | BasicBlock *RealDest = BI->getSuccessor(!CB->getValue()); |
| 928 | |
| 929 | // If there are PHI nodes in the destination block, we have to add an |
| 930 | // entry for PredBB. Instead of being smart about this, just split the |
| 931 | // critical edge, which will eliminate the PHI-ness. |
| 932 | if (isa<PHINode>(RealDest->begin())) { |
| 933 | SplitCriticalEdge(BI, !CB->getValue()); |
| 934 | RealDest = BI->getSuccessor(!CB->getValue()); |
| 935 | } |
| 936 | assert(!isa<PHINode>(RealDest->begin()) && "Crit edge split failure!"); |
| 937 | |
| 938 | // Loop over all of the edges from PredBB to BB, changing them to branch |
| 939 | // to RealDest instead. |
| 940 | TerminatorInst *PredBBTI = PredBB->getTerminator(); |
| 941 | for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| 942 | if (PredBBTI->getSuccessor(i) == BB) { |
| 943 | BB->removePredecessor(PredBB); |
| 944 | PredBBTI->setSuccessor(i, RealDest); |
| 945 | } |
| 946 | |
| 947 | std::cerr << *BB; |
| 948 | |
| 949 | // Recurse, simplifying any other constants. |
| 950 | return FoldCondBranchOnPHI(BI) | true; |
| 951 | } |
| 952 | |
| 953 | return false; |
| 954 | } |
| 955 | |
| 956 | |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 957 | namespace { |
| 958 | /// ConstantIntOrdering - This class implements a stable ordering of constant |
| 959 | /// integers that does not depend on their address. This is important for |
| 960 | /// applications that sort ConstantInt's to ensure uniqueness. |
| 961 | struct ConstantIntOrdering { |
| 962 | bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
| 963 | return LHS->getRawValue() < RHS->getRawValue(); |
| 964 | } |
| 965 | }; |
| 966 | } |
| 967 | |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 968 | // SimplifyCFG - This function is used to do simplification of a CFG. For |
| 969 | // example, it adjusts branches to branches to eliminate the extra hop, it |
| 970 | // eliminates unreachable basic blocks, and does other "peephole" optimization |
Chris Lattner | 31116ba | 2003-03-05 21:01:52 +0000 | [diff] [blame] | 971 | // of the CFG. It returns true if a modification was made. |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 972 | // |
| 973 | // WARNING: The entry node of a function may not be simplified. |
| 974 | // |
Chris Lattner | df3c342 | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 975 | bool llvm::SimplifyCFG(BasicBlock *BB) { |
Chris Lattner | 3f5823f | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 976 | bool Changed = false; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 977 | Function *M = BB->getParent(); |
| 978 | |
| 979 | assert(BB && BB->getParent() && "Block not embedded in function!"); |
| 980 | assert(BB->getTerminator() && "Degenerate basic block encountered!"); |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 981 | assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 982 | |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 983 | // Remove basic blocks that have no predecessors... which are unreachable. |
Chris Lattner | a2ab489 | 2004-02-24 07:23:58 +0000 | [diff] [blame] | 984 | if (pred_begin(BB) == pred_end(BB) || |
| 985 | *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) { |
Chris Lattner | 32c518e | 2004-07-15 02:06:12 +0000 | [diff] [blame] | 986 | DEBUG(std::cerr << "Removing BB: \n" << *BB); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 987 | |
| 988 | // Loop through all of our successors and make sure they know that one |
| 989 | // of their predecessors is going away. |
Chris Lattner | 95f16a3 | 2005-04-12 18:51:33 +0000 | [diff] [blame] | 990 | for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) |
| 991 | SI->removePredecessor(BB); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 992 | |
| 993 | while (!BB->empty()) { |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 994 | Instruction &I = BB->back(); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 995 | // If this instruction is used, replace uses with an arbitrary |
Chris Lattner | eee90f7 | 2005-08-02 23:29:23 +0000 | [diff] [blame] | 996 | // value. Because control flow can't get here, we don't care |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 997 | // what we replace the value with. Note that since this block is |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 998 | // unreachable, and all values contained within it must dominate their |
| 999 | // uses, that all uses will eventually be removed. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1000 | if (!I.use_empty()) |
Chris Lattner | eee90f7 | 2005-08-02 23:29:23 +0000 | [diff] [blame] | 1001 | // Make all users of this instruction use undef instead |
| 1002 | I.replaceAllUsesWith(UndefValue::get(I.getType())); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1003 | |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1004 | // Remove the instruction from the basic block |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1005 | BB->getInstList().pop_back(); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1006 | } |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1007 | M->getBasicBlockList().erase(BB); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1008 | return true; |
| 1009 | } |
| 1010 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 1011 | // Check to see if we can constant propagate this terminator instruction |
| 1012 | // away... |
Chris Lattner | 3f5823f | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 1013 | Changed |= ConstantFoldTerminator(BB); |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 1014 | |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1015 | // If this is a returning block with only PHI nodes in it, fold the return |
| 1016 | // instruction into any unconditional branch predecessors. |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1017 | // |
| 1018 | // If any predecessor is a conditional branch that just selects among |
| 1019 | // different return values, fold the replace the branch/return with a select |
| 1020 | // and return. |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1021 | if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { |
| 1022 | BasicBlock::iterator BBI = BB->getTerminator(); |
| 1023 | if (BBI == BB->begin() || isa<PHINode>(--BBI)) { |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1024 | // Find predecessors that end with branches. |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1025 | std::vector<BasicBlock*> UncondBranchPreds; |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1026 | std::vector<BranchInst*> CondBranchPreds; |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1027 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 1028 | TerminatorInst *PTI = (*PI)->getTerminator(); |
| 1029 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) |
| 1030 | if (BI->isUnconditional()) |
| 1031 | UncondBranchPreds.push_back(*PI); |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1032 | else |
| 1033 | CondBranchPreds.push_back(BI); |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1034 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1035 | |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1036 | // If we found some, do the transformation! |
| 1037 | if (!UncondBranchPreds.empty()) { |
| 1038 | while (!UncondBranchPreds.empty()) { |
| 1039 | BasicBlock *Pred = UncondBranchPreds.back(); |
| 1040 | UncondBranchPreds.pop_back(); |
| 1041 | Instruction *UncondBranch = Pred->getTerminator(); |
| 1042 | // Clone the return and add it to the end of the predecessor. |
| 1043 | Instruction *NewRet = RI->clone(); |
| 1044 | Pred->getInstList().push_back(NewRet); |
| 1045 | |
| 1046 | // If the return instruction returns a value, and if the value was a |
| 1047 | // PHI node in "BB", propagate the right value into the return. |
| 1048 | if (NewRet->getNumOperands() == 1) |
| 1049 | if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0))) |
| 1050 | if (PN->getParent() == BB) |
| 1051 | NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred)); |
| 1052 | // Update any PHI nodes in the returning block to realize that we no |
| 1053 | // longer branch to them. |
| 1054 | BB->removePredecessor(Pred); |
| 1055 | Pred->getInstList().erase(UncondBranch); |
| 1056 | } |
| 1057 | |
| 1058 | // If we eliminated all predecessors of the block, delete the block now. |
| 1059 | if (pred_begin(BB) == pred_end(BB)) |
| 1060 | // We know there are no successors, so just nuke the block. |
| 1061 | M->getBasicBlockList().erase(BB); |
| 1062 | |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1063 | return true; |
| 1064 | } |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1065 | |
| 1066 | // Check out all of the conditional branches going to this return |
| 1067 | // instruction. If any of them just select between returns, change the |
| 1068 | // branch itself into a select/return pair. |
| 1069 | while (!CondBranchPreds.empty()) { |
| 1070 | BranchInst *BI = CondBranchPreds.back(); |
| 1071 | CondBranchPreds.pop_back(); |
| 1072 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 1073 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 1074 | BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc; |
| 1075 | |
| 1076 | // Check to see if the non-BB successor is also a return block. |
| 1077 | if (isa<ReturnInst>(OtherSucc->getTerminator())) { |
| 1078 | // Check to see if there are only PHI instructions in this block. |
| 1079 | BasicBlock::iterator OSI = OtherSucc->getTerminator(); |
| 1080 | if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) { |
| 1081 | // Okay, we found a branch that is going to two return nodes. If |
| 1082 | // there is no return value for this function, just change the |
| 1083 | // branch into a return. |
| 1084 | if (RI->getNumOperands() == 0) { |
| 1085 | TrueSucc->removePredecessor(BI->getParent()); |
| 1086 | FalseSucc->removePredecessor(BI->getParent()); |
| 1087 | new ReturnInst(0, BI); |
| 1088 | BI->getParent()->getInstList().erase(BI); |
| 1089 | return true; |
| 1090 | } |
| 1091 | |
| 1092 | // Otherwise, figure out what the true and false return values are |
| 1093 | // so we can insert a new select instruction. |
| 1094 | Value *TrueValue = TrueSucc->getTerminator()->getOperand(0); |
| 1095 | Value *FalseValue = FalseSucc->getTerminator()->getOperand(0); |
| 1096 | |
| 1097 | // Unwrap any PHI nodes in the return blocks. |
| 1098 | if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue)) |
| 1099 | if (TVPN->getParent() == TrueSucc) |
| 1100 | TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| 1101 | if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue)) |
| 1102 | if (FVPN->getParent() == FalseSucc) |
| 1103 | FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
| 1104 | |
Chris Lattner | eed034b | 2004-04-02 18:15:10 +0000 | [diff] [blame] | 1105 | TrueSucc->removePredecessor(BI->getParent()); |
| 1106 | FalseSucc->removePredecessor(BI->getParent()); |
| 1107 | |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1108 | // Insert a new select instruction. |
Chris Lattner | 879ce78 | 2004-09-29 05:43:32 +0000 | [diff] [blame] | 1109 | Value *NewRetVal; |
| 1110 | Value *BrCond = BI->getCondition(); |
| 1111 | if (TrueValue != FalseValue) |
| 1112 | NewRetVal = new SelectInst(BrCond, TrueValue, |
| 1113 | FalseValue, "retval", BI); |
| 1114 | else |
| 1115 | NewRetVal = TrueValue; |
| 1116 | |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1117 | new ReturnInst(NewRetVal, BI); |
| 1118 | BI->getParent()->getInstList().erase(BI); |
Chris Lattner | 879ce78 | 2004-09-29 05:43:32 +0000 | [diff] [blame] | 1119 | if (BrCond->use_empty()) |
| 1120 | if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond)) |
| 1121 | BrCondI->getParent()->getInstList().erase(BrCondI); |
Chris Lattner | 9f0db32 | 2004-04-02 18:13:43 +0000 | [diff] [blame] | 1122 | return true; |
| 1123 | } |
| 1124 | } |
| 1125 | } |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1126 | } |
Chris Lattner | 3cd98f0 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1127 | } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) { |
| 1128 | // Check to see if the first instruction in this block is just an unwind. |
| 1129 | // If so, replace any invoke instructions which use this as an exception |
Chris Lattner | 5823ac1 | 2004-07-20 01:17:38 +0000 | [diff] [blame] | 1130 | // destination with call instructions, and any unconditional branch |
| 1131 | // predecessor with an unwind. |
Chris Lattner | 3cd98f0 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1132 | // |
| 1133 | std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); |
| 1134 | while (!Preds.empty()) { |
| 1135 | BasicBlock *Pred = Preds.back(); |
Chris Lattner | 5823ac1 | 2004-07-20 01:17:38 +0000 | [diff] [blame] | 1136 | if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) { |
| 1137 | if (BI->isUnconditional()) { |
| 1138 | Pred->getInstList().pop_back(); // nuke uncond branch |
| 1139 | new UnwindInst(Pred); // Use unwind. |
| 1140 | Changed = true; |
| 1141 | } |
| 1142 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator())) |
Chris Lattner | 3cd98f0 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1143 | if (II->getUnwindDest() == BB) { |
| 1144 | // Insert a new branch instruction before the invoke, because this |
| 1145 | // is now a fall through... |
| 1146 | BranchInst *BI = new BranchInst(II->getNormalDest(), II); |
| 1147 | Pred->getInstList().remove(II); // Take out of symbol table |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1148 | |
Chris Lattner | 3cd98f0 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1149 | // Insert the call now... |
| 1150 | std::vector<Value*> Args(II->op_begin()+3, II->op_end()); |
| 1151 | CallInst *CI = new CallInst(II->getCalledValue(), Args, |
| 1152 | II->getName(), BI); |
Chris Lattner | bcefcf8 | 2005-05-14 12:21:56 +0000 | [diff] [blame] | 1153 | CI->setCallingConv(II->getCallingConv()); |
Chris Lattner | 3cd98f0 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1154 | // If the invoke produced a value, the Call now does instead |
| 1155 | II->replaceAllUsesWith(CI); |
| 1156 | delete II; |
| 1157 | Changed = true; |
| 1158 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1159 | |
Chris Lattner | 3cd98f0 | 2004-02-24 05:54:22 +0000 | [diff] [blame] | 1160 | Preds.pop_back(); |
| 1161 | } |
Chris Lattner | 90ea78e | 2004-02-24 16:09:21 +0000 | [diff] [blame] | 1162 | |
| 1163 | // If this block is now dead, remove it. |
| 1164 | if (pred_begin(BB) == pred_end(BB)) { |
| 1165 | // We know there are no successors, so just nuke the block. |
| 1166 | M->getBasicBlockList().erase(BB); |
| 1167 | return true; |
| 1168 | } |
| 1169 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 1170 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
| 1171 | if (isValueEqualityComparison(SI)) { |
| 1172 | // If we only have one predecessor, and if it is a branch on this value, |
| 1173 | // see if that predecessor totally determines the outcome of this switch. |
| 1174 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 1175 | if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred)) |
| 1176 | return SimplifyCFG(BB) || 1; |
| 1177 | |
| 1178 | // If the block only contains the switch, see if we can fold the block |
| 1179 | // away into any preds. |
| 1180 | if (SI == &BB->front()) |
| 1181 | if (FoldValueComparisonIntoPredecessors(SI)) |
| 1182 | return SimplifyCFG(BB) || 1; |
| 1183 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1184 | } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 1185 | if (BI->isUnconditional()) { |
| 1186 | BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes... |
| 1187 | while (isa<PHINode>(*BBI)) ++BBI; |
| 1188 | |
| 1189 | BasicBlock *Succ = BI->getSuccessor(0); |
| 1190 | if (BBI->isTerminator() && // Terminator is the only non-phi instruction! |
| 1191 | Succ != BB) // Don't hurt infinite loops! |
| 1192 | if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ)) |
| 1193 | return 1; |
| 1194 | |
| 1195 | } else { // Conditional branch |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1196 | if (Value *CompVal = isValueEqualityComparison(BI)) { |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 1197 | // If we only have one predecessor, and if it is a branch on this value, |
| 1198 | // see if that predecessor totally determines the outcome of this |
| 1199 | // switch. |
| 1200 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 1201 | if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred)) |
| 1202 | return SimplifyCFG(BB) || 1; |
| 1203 | |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1204 | // This block must be empty, except for the setcond inst, if it exists. |
| 1205 | BasicBlock::iterator I = BB->begin(); |
| 1206 | if (&*I == BI || |
| 1207 | (&*I == cast<Instruction>(BI->getCondition()) && |
| 1208 | &*++I == BI)) |
| 1209 | if (FoldValueComparisonIntoPredecessors(BI)) |
| 1210 | return SimplifyCFG(BB) | true; |
| 1211 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame^] | 1212 | |
| 1213 | // If this is a branch on a phi node in the current block, thread control |
| 1214 | // through this block if any PHI node entries are constants. |
| 1215 | if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) |
| 1216 | if (PN->getParent() == BI->getParent()) |
| 1217 | if (FoldCondBranchOnPHI(BI)) |
| 1218 | return SimplifyCFG(BB) | true; |
| 1219 | |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1220 | |
| 1221 | // If this basic block is ONLY a setcc and a branch, and if a predecessor |
| 1222 | // branches to us and one of our successors, fold the setcc into the |
| 1223 | // predecessor and use logical operations to pick the right destination. |
Chris Lattner | 51a6dbc | 2004-05-02 05:02:03 +0000 | [diff] [blame] | 1224 | BasicBlock *TrueDest = BI->getSuccessor(0); |
| 1225 | BasicBlock *FalseDest = BI->getSuccessor(1); |
Chris Lattner | be6f068 | 2004-05-02 05:19:36 +0000 | [diff] [blame] | 1226 | if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition())) |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1227 | if (Cond->getParent() == BB && &BB->front() == Cond && |
Chris Lattner | 51a6dbc | 2004-05-02 05:02:03 +0000 | [diff] [blame] | 1228 | Cond->getNext() == BI && Cond->hasOneUse() && |
| 1229 | TrueDest != BB && FalseDest != BB) |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1230 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI) |
| 1231 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | 1e94ed6 | 2004-05-02 01:00:44 +0000 | [diff] [blame] | 1232 | if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) { |
Chris Lattner | f12c4a3 | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1233 | BasicBlock *PredBlock = *PI; |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1234 | if (PBI->getSuccessor(0) == FalseDest || |
| 1235 | PBI->getSuccessor(1) == TrueDest) { |
| 1236 | // Invert the predecessors condition test (xor it with true), |
| 1237 | // which allows us to write this code once. |
| 1238 | Value *NewCond = |
| 1239 | BinaryOperator::createNot(PBI->getCondition(), |
| 1240 | PBI->getCondition()->getName()+".not", PBI); |
| 1241 | PBI->setCondition(NewCond); |
| 1242 | BasicBlock *OldTrue = PBI->getSuccessor(0); |
| 1243 | BasicBlock *OldFalse = PBI->getSuccessor(1); |
| 1244 | PBI->setSuccessor(0, OldFalse); |
| 1245 | PBI->setSuccessor(1, OldTrue); |
| 1246 | } |
| 1247 | |
| 1248 | if (PBI->getSuccessor(0) == TrueDest || |
| 1249 | PBI->getSuccessor(1) == FalseDest) { |
Chris Lattner | f12c4a3 | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1250 | // Clone Cond into the predecessor basic block, and or/and the |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1251 | // two conditions together. |
| 1252 | Instruction *New = Cond->clone(); |
| 1253 | New->setName(Cond->getName()); |
| 1254 | Cond->setName(Cond->getName()+".old"); |
Chris Lattner | f12c4a3 | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1255 | PredBlock->getInstList().insert(PBI, New); |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1256 | Instruction::BinaryOps Opcode = |
| 1257 | PBI->getSuccessor(0) == TrueDest ? |
| 1258 | Instruction::Or : Instruction::And; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1259 | Value *NewCond = |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1260 | BinaryOperator::create(Opcode, PBI->getCondition(), |
| 1261 | New, "bothcond", PBI); |
| 1262 | PBI->setCondition(NewCond); |
| 1263 | if (PBI->getSuccessor(0) == BB) { |
Chris Lattner | f12c4a3 | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1264 | AddPredecessorToBlock(TrueDest, PredBlock, BB); |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1265 | PBI->setSuccessor(0, TrueDest); |
| 1266 | } |
| 1267 | if (PBI->getSuccessor(1) == BB) { |
Chris Lattner | f12c4a3 | 2004-06-21 07:19:01 +0000 | [diff] [blame] | 1268 | AddPredecessorToBlock(FalseDest, PredBlock, BB); |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1269 | PBI->setSuccessor(1, FalseDest); |
| 1270 | } |
| 1271 | return SimplifyCFG(BB) | 1; |
| 1272 | } |
| 1273 | } |
Chris Lattner | 2e93c42 | 2004-05-01 23:35:43 +0000 | [diff] [blame] | 1274 | |
Chris Lattner | 88da6f7 | 2004-05-01 22:36:37 +0000 | [diff] [blame] | 1275 | // If this block ends with a branch instruction, and if there is one |
| 1276 | // predecessor, see if the previous block ended with a branch on the same |
| 1277 | // condition, which makes this conditional branch redundant. |
Chris Lattner | 733d670 | 2005-08-03 00:11:16 +0000 | [diff] [blame] | 1278 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
Chris Lattner | 88da6f7 | 2004-05-01 22:36:37 +0000 | [diff] [blame] | 1279 | if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator())) |
| 1280 | if (PBI->isConditional() && |
| 1281 | PBI->getCondition() == BI->getCondition() && |
Chris Lattner | 4cbd160 | 2004-05-01 22:41:51 +0000 | [diff] [blame] | 1282 | (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) { |
Chris Lattner | 88da6f7 | 2004-05-01 22:36:37 +0000 | [diff] [blame] | 1283 | // Okay, the outcome of this conditional branch is statically |
| 1284 | // knowable. Delete the outgoing CFG edge that is impossible to |
| 1285 | // execute. |
| 1286 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
| 1287 | BI->getSuccessor(CondIsTrue)->removePredecessor(BB); |
| 1288 | new BranchInst(BI->getSuccessor(!CondIsTrue), BB); |
| 1289 | BB->getInstList().erase(BI); |
| 1290 | return SimplifyCFG(BB) | true; |
| 1291 | } |
Chris Lattner | a2ab489 | 2004-02-24 07:23:58 +0000 | [diff] [blame] | 1292 | } |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1293 | } else if (isa<UnreachableInst>(BB->getTerminator())) { |
| 1294 | // If there are any instructions immediately before the unreachable that can |
| 1295 | // be removed, do so. |
| 1296 | Instruction *Unreachable = BB->getTerminator(); |
| 1297 | while (Unreachable != BB->begin()) { |
| 1298 | BasicBlock::iterator BBI = Unreachable; |
| 1299 | --BBI; |
| 1300 | if (isa<CallInst>(BBI)) break; |
| 1301 | // Delete this instruction |
| 1302 | BB->getInstList().erase(BBI); |
| 1303 | Changed = true; |
| 1304 | } |
| 1305 | |
| 1306 | // If the unreachable instruction is the first in the block, take a gander |
| 1307 | // at all of the predecessors of this instruction, and simplify them. |
| 1308 | if (&BB->front() == Unreachable) { |
| 1309 | std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); |
| 1310 | for (unsigned i = 0, e = Preds.size(); i != e; ++i) { |
| 1311 | TerminatorInst *TI = Preds[i]->getTerminator(); |
| 1312 | |
| 1313 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 1314 | if (BI->isUnconditional()) { |
| 1315 | if (BI->getSuccessor(0) == BB) { |
| 1316 | new UnreachableInst(TI); |
| 1317 | TI->eraseFromParent(); |
| 1318 | Changed = true; |
| 1319 | } |
| 1320 | } else { |
| 1321 | if (BI->getSuccessor(0) == BB) { |
| 1322 | new BranchInst(BI->getSuccessor(1), BI); |
| 1323 | BI->eraseFromParent(); |
| 1324 | } else if (BI->getSuccessor(1) == BB) { |
| 1325 | new BranchInst(BI->getSuccessor(0), BI); |
| 1326 | BI->eraseFromParent(); |
| 1327 | Changed = true; |
| 1328 | } |
| 1329 | } |
| 1330 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 1331 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
| 1332 | if (SI->getSuccessor(i) == BB) { |
Chris Lattner | 19f9f32 | 2005-05-20 22:19:54 +0000 | [diff] [blame] | 1333 | BB->removePredecessor(SI->getParent()); |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1334 | SI->removeCase(i); |
| 1335 | --i; --e; |
| 1336 | Changed = true; |
| 1337 | } |
| 1338 | // If the default value is unreachable, figure out the most popular |
| 1339 | // destination and make it the default. |
| 1340 | if (SI->getSuccessor(0) == BB) { |
| 1341 | std::map<BasicBlock*, unsigned> Popularity; |
| 1342 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
| 1343 | Popularity[SI->getSuccessor(i)]++; |
| 1344 | |
| 1345 | // Find the most popular block. |
| 1346 | unsigned MaxPop = 0; |
| 1347 | BasicBlock *MaxBlock = 0; |
| 1348 | for (std::map<BasicBlock*, unsigned>::iterator |
| 1349 | I = Popularity.begin(), E = Popularity.end(); I != E; ++I) { |
| 1350 | if (I->second > MaxPop) { |
| 1351 | MaxPop = I->second; |
| 1352 | MaxBlock = I->first; |
| 1353 | } |
| 1354 | } |
| 1355 | if (MaxBlock) { |
| 1356 | // Make this the new default, allowing us to delete any explicit |
| 1357 | // edges to it. |
| 1358 | SI->setSuccessor(0, MaxBlock); |
| 1359 | Changed = true; |
| 1360 | |
Chris Lattner | 19f9f32 | 2005-05-20 22:19:54 +0000 | [diff] [blame] | 1361 | // If MaxBlock has phinodes in it, remove MaxPop-1 entries from |
| 1362 | // it. |
| 1363 | if (isa<PHINode>(MaxBlock->begin())) |
| 1364 | for (unsigned i = 0; i != MaxPop-1; ++i) |
| 1365 | MaxBlock->removePredecessor(SI->getParent()); |
| 1366 | |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1367 | for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) |
| 1368 | if (SI->getSuccessor(i) == MaxBlock) { |
| 1369 | SI->removeCase(i); |
| 1370 | --i; --e; |
| 1371 | } |
| 1372 | } |
| 1373 | } |
| 1374 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { |
| 1375 | if (II->getUnwindDest() == BB) { |
| 1376 | // Convert the invoke to a call instruction. This would be a good |
| 1377 | // place to note that the call does not throw though. |
| 1378 | BranchInst *BI = new BranchInst(II->getNormalDest(), II); |
| 1379 | II->removeFromParent(); // Take out of symbol table |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1380 | |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1381 | // Insert the call now... |
| 1382 | std::vector<Value*> Args(II->op_begin()+3, II->op_end()); |
| 1383 | CallInst *CI = new CallInst(II->getCalledValue(), Args, |
| 1384 | II->getName(), BI); |
Chris Lattner | bcefcf8 | 2005-05-14 12:21:56 +0000 | [diff] [blame] | 1385 | CI->setCallingConv(II->getCallingConv()); |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 1386 | // If the invoke produced a value, the Call does now instead. |
| 1387 | II->replaceAllUsesWith(CI); |
| 1388 | delete II; |
| 1389 | Changed = true; |
| 1390 | } |
| 1391 | } |
| 1392 | } |
| 1393 | |
| 1394 | // If this block is now dead, remove it. |
| 1395 | if (pred_begin(BB) == pred_end(BB)) { |
| 1396 | // We know there are no successors, so just nuke the block. |
| 1397 | M->getBasicBlockList().erase(BB); |
| 1398 | return true; |
| 1399 | } |
| 1400 | } |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 1401 | } |
| 1402 | |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1403 | // Merge basic blocks into their predecessor if there is only one distinct |
| 1404 | // pred, and if there is only one distinct successor of the predecessor, and |
| 1405 | // if there are no PHI nodes. |
| 1406 | // |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1407 | pred_iterator PI(pred_begin(BB)), PE(pred_end(BB)); |
| 1408 | BasicBlock *OnlyPred = *PI++; |
| 1409 | for (; PI != PE; ++PI) // Search all predecessors, see if they are all same |
| 1410 | if (*PI != OnlyPred) { |
| 1411 | OnlyPred = 0; // There are multiple different predecessors... |
| 1412 | break; |
| 1413 | } |
Chris Lattner | 88da6f7 | 2004-05-01 22:36:37 +0000 | [diff] [blame] | 1414 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1415 | BasicBlock *OnlySucc = 0; |
| 1416 | if (OnlyPred && OnlyPred != BB && // Don't break self loops |
| 1417 | OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) { |
| 1418 | // Check to see if there is only one distinct successor... |
| 1419 | succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred)); |
| 1420 | OnlySucc = BB; |
| 1421 | for (; SI != SE; ++SI) |
| 1422 | if (*SI != OnlySucc) { |
| 1423 | OnlySucc = 0; // There are multiple distinct successors! |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1424 | break; |
| 1425 | } |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1426 | } |
| 1427 | |
| 1428 | if (OnlySucc) { |
Chris Lattner | 32c518e | 2004-07-15 02:06:12 +0000 | [diff] [blame] | 1429 | DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred); |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1430 | TerminatorInst *Term = OnlyPred->getTerminator(); |
| 1431 | |
| 1432 | // Resolve any PHI nodes at the start of the block. They are all |
| 1433 | // guaranteed to have exactly one entry if they exist, unless there are |
| 1434 | // multiple duplicate (but guaranteed to be equal) entries for the |
| 1435 | // incoming edges. This occurs when there are multiple edges from |
| 1436 | // OnlyPred to OnlySucc. |
| 1437 | // |
| 1438 | while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { |
| 1439 | PN->replaceAllUsesWith(PN->getIncomingValue(0)); |
| 1440 | BB->getInstList().pop_front(); // Delete the phi node... |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1441 | } |
| 1442 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1443 | // Delete the unconditional branch from the predecessor... |
| 1444 | OnlyPred->getInstList().pop_back(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1445 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1446 | // Move all definitions in the successor to the predecessor... |
| 1447 | OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList()); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1448 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1449 | // Make all PHI nodes that referred to BB now refer to Pred as their |
| 1450 | // source... |
| 1451 | BB->replaceAllUsesWith(OnlyPred); |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1452 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1453 | std::string OldName = BB->getName(); |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1454 | |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1455 | // Erase basic block from the function... |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1456 | M->getBasicBlockList().erase(BB); |
Chris Lattner | fda72b1 | 2002-06-25 16:12:52 +0000 | [diff] [blame] | 1457 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1458 | // Inherit predecessors name if it exists... |
| 1459 | if (!OldName.empty() && !OnlyPred->hasName()) |
| 1460 | OnlyPred->setName(OldName); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1461 | |
Chris Lattner | 838b845 | 2004-02-11 01:17:07 +0000 | [diff] [blame] | 1462 | return true; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1463 | } |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1464 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1465 | // Otherwise, if this block only has a single predecessor, and if that block |
| 1466 | // is a conditional branch, see if we can hoist any code from this block up |
| 1467 | // into our predecessor. |
| 1468 | if (OnlyPred) |
Chris Lattner | 4fc998d | 2004-12-10 17:42:31 +0000 | [diff] [blame] | 1469 | if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator())) |
| 1470 | if (BI->isConditional()) { |
| 1471 | // Get the other block. |
| 1472 | BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB); |
| 1473 | PI = pred_begin(OtherBB); |
| 1474 | ++PI; |
| 1475 | if (PI == pred_end(OtherBB)) { |
| 1476 | // We have a conditional branch to two blocks that are only reachable |
| 1477 | // from the condbr. We know that the condbr dominates the two blocks, |
| 1478 | // so see if there is any identical code in the "then" and "else" |
| 1479 | // blocks. If so, we can hoist it up to the branching block. |
| 1480 | Changed |= HoistThenElseCodeToIf(BI); |
| 1481 | } |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1482 | } |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1483 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1484 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 1485 | if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
| 1486 | // Change br (X == 0 | X == 1), T, F into a switch instruction. |
| 1487 | if (BI->isConditional() && isa<Instruction>(BI->getCondition())) { |
| 1488 | Instruction *Cond = cast<Instruction>(BI->getCondition()); |
| 1489 | // If this is a bunch of seteq's or'd together, or if it's a bunch of |
| 1490 | // 'setne's and'ed together, collect them. |
| 1491 | Value *CompVal = 0; |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 1492 | std::vector<ConstantInt*> Values; |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1493 | bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values); |
| 1494 | if (CompVal && CompVal->getType()->isInteger()) { |
| 1495 | // There might be duplicate constants in the list, which the switch |
| 1496 | // instruction can't handle, remove them now. |
Chris Lattner | b2b151d | 2004-06-19 07:02:14 +0000 | [diff] [blame] | 1497 | std::sort(Values.begin(), Values.end(), ConstantIntOrdering()); |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1498 | Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1499 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1500 | // Figure out which block is which destination. |
| 1501 | BasicBlock *DefaultBB = BI->getSuccessor(1); |
| 1502 | BasicBlock *EdgeBB = BI->getSuccessor(0); |
| 1503 | if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1504 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1505 | // Create the new switch instruction now. |
Chris Lattner | a35dfce | 2005-01-29 00:38:26 +0000 | [diff] [blame] | 1506 | SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1507 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1508 | // Add all of the 'cases' to the switch instruction. |
| 1509 | for (unsigned i = 0, e = Values.size(); i != e; ++i) |
| 1510 | New->addCase(Values[i], EdgeBB); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1511 | |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1512 | // We added edges from PI to the EdgeBB. As such, if there were any |
| 1513 | // PHI nodes in EdgeBB, they need entries to be added corresponding to |
| 1514 | // the number of edges added. |
| 1515 | for (BasicBlock::iterator BBI = EdgeBB->begin(); |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1516 | isa<PHINode>(BBI); ++BBI) { |
| 1517 | PHINode *PN = cast<PHINode>(BBI); |
Chris Lattner | 6f4b45a | 2004-02-24 05:38:11 +0000 | [diff] [blame] | 1518 | Value *InVal = PN->getIncomingValueForBlock(*PI); |
| 1519 | for (unsigned i = 0, e = Values.size()-1; i != e; ++i) |
| 1520 | PN->addIncoming(InVal, *PI); |
| 1521 | } |
| 1522 | |
| 1523 | // Erase the old branch instruction. |
| 1524 | (*PI)->getInstList().erase(BI); |
| 1525 | |
| 1526 | // Erase the potentially condition tree that was used to computed the |
| 1527 | // branch condition. |
| 1528 | ErasePossiblyDeadInstructionTree(Cond); |
| 1529 | return true; |
| 1530 | } |
| 1531 | } |
| 1532 | |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1533 | // If there is a trivial two-entry PHI node in this basic block, and we can |
| 1534 | // eliminate it, do so now. |
| 1535 | if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) |
| 1536 | if (PN->getNumIncomingValues() == 2) { |
| 1537 | // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| 1538 | // statement", which has a very simple dominance structure. Basically, we |
| 1539 | // are trying to find the condition that is being branched on, which |
| 1540 | // subsequently causes this merge to happen. We really want control |
| 1541 | // dependence information for this check, but simplifycfg can't keep it up |
| 1542 | // to date, and this catches most of the cases we care about anyway. |
| 1543 | // |
| 1544 | BasicBlock *IfTrue, *IfFalse; |
| 1545 | if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) { |
Chris Lattner | 9734fd0 | 2004-06-20 01:13:18 +0000 | [diff] [blame] | 1546 | DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: " |
| 1547 | << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1548 | |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1549 | // Loop over the PHI's seeing if we can promote them all to select |
| 1550 | // instructions. While we are at it, keep track of the instructions |
| 1551 | // that need to be moved to the dominating block. |
| 1552 | std::set<Instruction*> AggressiveInsts; |
| 1553 | bool CanPromote = true; |
| 1554 | |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1555 | BasicBlock::iterator AfterPHIIt = BB->begin(); |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1556 | while (isa<PHINode>(AfterPHIIt)) { |
| 1557 | PHINode *PN = cast<PHINode>(AfterPHIIt++); |
Chris Lattner | 5e73529 | 2005-06-17 01:45:53 +0000 | [diff] [blame] | 1558 | if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) { |
| 1559 | if (PN->getIncomingValue(0) != PN) |
| 1560 | PN->replaceAllUsesWith(PN->getIncomingValue(0)); |
| 1561 | else |
| 1562 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
| 1563 | } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB, |
| 1564 | &AggressiveInsts) || |
| 1565 | !DominatesMergePoint(PN->getIncomingValue(1), BB, |
| 1566 | &AggressiveInsts)) { |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1567 | CanPromote = false; |
| 1568 | break; |
| 1569 | } |
| 1570 | } |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1571 | |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1572 | // Did we eliminate all PHI's? |
| 1573 | CanPromote |= AfterPHIIt == BB->begin(); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1574 | |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1575 | // If we all PHI nodes are promotable, check to make sure that all |
| 1576 | // instructions in the predecessor blocks can be promoted as well. If |
| 1577 | // not, we won't be able to get rid of the control flow, so it's not |
| 1578 | // worth promoting to select instructions. |
Reid Spencer | fad217c | 2004-10-22 16:10:39 +0000 | [diff] [blame] | 1579 | BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0; |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1580 | if (CanPromote) { |
| 1581 | PN = cast<PHINode>(BB->begin()); |
| 1582 | BasicBlock *Pred = PN->getIncomingBlock(0); |
| 1583 | if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) { |
| 1584 | IfBlock1 = Pred; |
| 1585 | DomBlock = *pred_begin(Pred); |
| 1586 | for (BasicBlock::iterator I = Pred->begin(); |
| 1587 | !isa<TerminatorInst>(I); ++I) |
| 1588 | if (!AggressiveInsts.count(I)) { |
| 1589 | // This is not an aggressive instruction that we can promote. |
| 1590 | // Because of this, we won't be able to get rid of the control |
| 1591 | // flow, so the xform is not worth it. |
| 1592 | CanPromote = false; |
| 1593 | break; |
| 1594 | } |
| 1595 | } |
| 1596 | |
| 1597 | Pred = PN->getIncomingBlock(1); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1598 | if (CanPromote && |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1599 | cast<BranchInst>(Pred->getTerminator())->isUnconditional()) { |
| 1600 | IfBlock2 = Pred; |
| 1601 | DomBlock = *pred_begin(Pred); |
| 1602 | for (BasicBlock::iterator I = Pred->begin(); |
| 1603 | !isa<TerminatorInst>(I); ++I) |
| 1604 | if (!AggressiveInsts.count(I)) { |
| 1605 | // This is not an aggressive instruction that we can promote. |
| 1606 | // Because of this, we won't be able to get rid of the control |
| 1607 | // flow, so the xform is not worth it. |
| 1608 | CanPromote = false; |
| 1609 | break; |
| 1610 | } |
| 1611 | } |
| 1612 | } |
| 1613 | |
| 1614 | // If we can still promote the PHI nodes after this gauntlet of tests, |
| 1615 | // do all of the PHI's now. |
| 1616 | if (CanPromote) { |
| 1617 | // Move all 'aggressive' instructions, which are defined in the |
| 1618 | // conditional parts of the if's up to the dominating block. |
| 1619 | if (IfBlock1) { |
| 1620 | DomBlock->getInstList().splice(DomBlock->getTerminator(), |
| 1621 | IfBlock1->getInstList(), |
| 1622 | IfBlock1->begin(), |
| 1623 | IfBlock1->getTerminator()); |
| 1624 | } |
| 1625 | if (IfBlock2) { |
| 1626 | DomBlock->getInstList().splice(DomBlock->getTerminator(), |
| 1627 | IfBlock2->getInstList(), |
| 1628 | IfBlock2->begin(), |
| 1629 | IfBlock2->getTerminator()); |
| 1630 | } |
| 1631 | |
| 1632 | while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| 1633 | // Change the PHI node into a select instruction. |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1634 | Value *TrueVal = |
| 1635 | PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
| 1636 | Value *FalseVal = |
| 1637 | PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
| 1638 | |
Chris Lattner | 81bdcb9 | 2004-03-30 19:44:05 +0000 | [diff] [blame] | 1639 | std::string Name = PN->getName(); PN->setName(""); |
| 1640 | PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal, |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1641 | Name, AfterPHIIt)); |
Chris Lattner | 81bdcb9 | 2004-03-30 19:44:05 +0000 | [diff] [blame] | 1642 | BB->getInstList().erase(PN); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1643 | } |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 1644 | Changed = true; |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 1645 | } |
| 1646 | } |
| 1647 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1648 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 1649 | return Changed; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1650 | } |