blob: 0edf7cadc8d23e96c9a2a5f297fb092b32289244 [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner01d1ee32002-05-21 20:50:24 +00009//
Chris Lattnerbb190ac2002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner01d1ee32002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner218a8222004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner01d1ee32002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000016#include "llvm/Constants.h"
Nick Lewycky9d523102011-12-26 20:37:40 +000017#include "llvm/DerivedTypes.h"
18#include "llvm/GlobalVariable.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000019#include "llvm/IRBuilder.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000020#include "llvm/Instructions.h"
Devang Patel383d7ed2009-02-03 22:12:02 +000021#include "llvm/IntrinsicInst.h"
Nick Lewycky06cc66f2011-12-27 04:31:52 +000022#include "llvm/LLVMContext.h"
Chandler Carruth0baa4802012-07-15 23:26:50 +000023#include "llvm/MDBuilder.h"
Nick Lewycky06cc66f2011-12-27 04:31:52 +000024#include "llvm/Metadata.h"
Hans Wennborg486270a2012-09-06 09:43:28 +000025#include "llvm/Module.h"
Dan Gohman3b205172012-01-05 23:58:56 +000026#include "llvm/Operator.h"
Chris Lattner0d560082004-02-24 05:38:11 +000027#include "llvm/Type.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000034#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramer10fcfb52011-05-14 15:57:25 +000035#include "llvm/Analysis/ValueTracking.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000036#include "llvm/Support/CFG.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000037#include "llvm/Support/CommandLine.h"
Chris Lattnere27db742010-12-17 06:20:15 +000038#include "llvm/Support/ConstantRange.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000039#include "llvm/Support/Debug.h"
Devang Pateld3a17882011-05-19 20:52:46 +000040#include "llvm/Support/NoFolder.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000044#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000045#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000046#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Peter Collingbourne57808b32011-04-29 18:47:38 +000049static cl::opt<unsigned>
50PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
51 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
52
Evan Chengc3f507f2011-01-29 04:46:23 +000053static cl::opt<bool>
54DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
55 cl::desc("Duplicate return instructions into unconditional branches"));
56
Manman Ren554da1a2012-09-20 22:37:36 +000057static cl::opt<bool>
58SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
59 cl::desc("Sink common instructions down to the end block"));
60
Hans Wennborgd72271c2012-09-26 09:44:49 +000061STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Hans Wennborg50b7d702012-09-26 14:01:53 +000062STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Manman Ren554da1a2012-09-20 22:37:36 +000063STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborg50b7d702012-09-26 14:01:53 +000064STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng502a4f52008-06-12 21:15:59 +000065
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000066namespace {
Eric Christopherc723eb12012-07-02 23:22:21 +000067 /// ValueEqualityComparisonCase - Represents a case of a switch.
68 struct ValueEqualityComparisonCase {
69 ConstantInt *Value;
70 BasicBlock *Dest;
71
72 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
73 : Value(Value), Dest(Dest) {}
74
75 bool operator<(ValueEqualityComparisonCase RHS) const {
76 // Comparing pointers is ok as we only rely on the order for uniquing.
77 return Value < RHS.Value;
78 }
79 };
80
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000081class SimplifyCFGOpt {
82 const TargetData *const TD;
83
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000084 Value *isValueEqualityComparison(TerminatorInst *TI);
85 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherc723eb12012-07-02 23:22:21 +000086 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000087 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patel007349d2011-05-18 20:35:38 +000088 BasicBlock *Pred,
89 IRBuilder<> &Builder);
Devang Patelb55d9242011-05-18 20:53:17 +000090 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
91 IRBuilder<> &Builder);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000092
Devang Patel176ec402011-05-18 21:33:11 +000093 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingaa5abe82012-02-06 21:16:41 +000094 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000095 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patel007349d2011-05-18 20:35:38 +000096 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000097 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patela23812c2011-05-18 18:28:48 +000098 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patel007349d2011-05-18 20:35:38 +000099 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner3d512132010-12-13 06:25:44 +0000100
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000101public:
102 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
103 bool run(BasicBlock *BB);
104};
105}
106
Chris Lattner2bdcb562005-08-03 00:19:45 +0000107/// SafeToMergeTerminators - Return true if it is safe to merge these two
108/// terminator instructions together.
109///
110static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
111 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trick6b014382012-08-29 21:46:36 +0000112
Chris Lattner2bdcb562005-08-03 00:19:45 +0000113 // It is not safe to merge these two switch instructions if they have a common
114 // successor, and if that successor has a PHI node, and if *that* PHI node has
115 // conflicting incoming values from the two switch blocks.
116 BasicBlock *SI1BB = SI1->getParent();
117 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +0000118 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trick6b014382012-08-29 21:46:36 +0000119
Chris Lattner2bdcb562005-08-03 00:19:45 +0000120 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
121 if (SI1Succs.count(*I))
122 for (BasicBlock::iterator BBI = (*I)->begin();
123 isa<PHINode>(BBI); ++BBI) {
124 PHINode *PN = cast<PHINode>(BBI);
125 if (PN->getIncomingValueForBlock(SI1BB) !=
126 PN->getIncomingValueForBlock(SI2BB))
127 return false;
128 }
Andrew Trick6b014382012-08-29 21:46:36 +0000129
Chris Lattner2bdcb562005-08-03 00:19:45 +0000130 return true;
131}
132
Manman Renee28e0f2012-06-13 05:43:29 +0000133/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
134/// to merge these two terminator instructions together, where SI1 is an
135/// unconditional branch. PhiNodes will store all PHI nodes in common
136/// successors.
137///
138static bool isProfitableToFoldUnconditional(BranchInst *SI1,
139 BranchInst *SI2,
Nick Lewyckyedb58422012-06-24 10:15:42 +0000140 Instruction *Cond,
Manman Renee28e0f2012-06-13 05:43:29 +0000141 SmallVectorImpl<PHINode*> &PhiNodes) {
142 if (SI1 == SI2) return false; // Can't merge with self!
143 assert(SI1->isUnconditional() && SI2->isConditional());
144
145 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trick6b014382012-08-29 21:46:36 +0000146 // common successors:
Manman Renee28e0f2012-06-13 05:43:29 +0000147 // 1> We have a constant incoming value for the conditional branch;
148 // 2> We have "Cond" as the incoming value for the unconditional branch;
149 // 3> SI2->getCondition() and Cond have same operands.
150 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
151 if (!Ci2) return false;
152 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
153 Cond->getOperand(1) == Ci2->getOperand(1)) &&
154 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
155 Cond->getOperand(1) == Ci2->getOperand(0)))
156 return false;
157
158 BasicBlock *SI1BB = SI1->getParent();
159 BasicBlock *SI2BB = SI2->getParent();
160 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
161 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
162 if (SI1Succs.count(*I))
163 for (BasicBlock::iterator BBI = (*I)->begin();
164 isa<PHINode>(BBI); ++BBI) {
165 PHINode *PN = cast<PHINode>(BBI);
166 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewyckyedb58422012-06-24 10:15:42 +0000167 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Renee28e0f2012-06-13 05:43:29 +0000168 return false;
169 PhiNodes.push_back(PN);
170 }
171 return true;
172}
173
Chris Lattner2bdcb562005-08-03 00:19:45 +0000174/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
175/// now be entries in it from the 'NewPred' block. The values that will be
176/// flowing into the PHI nodes will be the same as those coming in from
177/// ExistPred, an existing predecessor of Succ.
178static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
179 BasicBlock *ExistPred) {
Chris Lattner2bdcb562005-08-03 00:19:45 +0000180 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trick6b014382012-08-29 21:46:36 +0000181
Chris Lattner093a4382008-07-13 22:23:11 +0000182 PHINode *PN;
183 for (BasicBlock::iterator I = Succ->begin();
184 (PN = dyn_cast<PHINode>(I)); ++I)
185 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000186}
187
Chris Lattner7e663482005-08-03 00:11:16 +0000188
Chris Lattner73c50a62010-12-14 07:00:00 +0000189/// GetIfCondition - Given a basic block (BB) with two predecessors (and at
190/// least one PHI node in it), check to see if the merge at this block is due
Chris Lattner723c66d2004-02-11 03:36:04 +0000191/// to an "if condition". If so, return the boolean condition that determines
192/// which entry into BB will be taken. Also, return by references the block
193/// that will be entered from if the condition is true, and the block that will
194/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000195///
Chris Lattner995ba1b2010-12-14 07:15:21 +0000196/// This does no checking to see if the true/false blocks have large or unsavory
197/// instructions in them.
Chris Lattner73c50a62010-12-14 07:00:00 +0000198static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
199 BasicBlock *&IfFalse) {
200 PHINode *SomePHI = cast<PHINode>(BB->begin());
201 assert(SomePHI->getNumIncomingValues() == 2 &&
Chris Lattner723c66d2004-02-11 03:36:04 +0000202 "Function can only handle blocks with 2 predecessors!");
Chris Lattner73c50a62010-12-14 07:00:00 +0000203 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
204 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
Chris Lattner723c66d2004-02-11 03:36:04 +0000205
206 // We can only handle branches. Other control flow will be lowered to
207 // branches if possible anyway.
Chris Lattner995ba1b2010-12-14 07:15:21 +0000208 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
209 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
210 if (Pred1Br == 0 || Pred2Br == 0)
Chris Lattner723c66d2004-02-11 03:36:04 +0000211 return 0;
Chris Lattner723c66d2004-02-11 03:36:04 +0000212
213 // Eliminate code duplication by ensuring that Pred1Br is conditional if
214 // either are.
215 if (Pred2Br->isConditional()) {
216 // If both branches are conditional, we don't have an "if statement". In
217 // reality, we could transform this case, but since the condition will be
218 // required anyway, we stand no chance of eliminating it, so the xform is
219 // probably not profitable.
220 if (Pred1Br->isConditional())
221 return 0;
222
223 std::swap(Pred1, Pred2);
224 std::swap(Pred1Br, Pred2Br);
225 }
226
227 if (Pred1Br->isConditional()) {
Chris Lattner995ba1b2010-12-14 07:15:21 +0000228 // The only thing we have to watch out for here is to make sure that Pred2
229 // doesn't have incoming edges from other blocks. If it does, the condition
230 // doesn't dominate BB.
231 if (Pred2->getSinglePredecessor() == 0)
232 return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000233
Chris Lattner723c66d2004-02-11 03:36:04 +0000234 // If we found a conditional branch predecessor, make sure that it branches
235 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
236 if (Pred1Br->getSuccessor(0) == BB &&
237 Pred1Br->getSuccessor(1) == Pred2) {
238 IfTrue = Pred1;
239 IfFalse = Pred2;
240 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
241 Pred1Br->getSuccessor(1) == BB) {
242 IfTrue = Pred2;
243 IfFalse = Pred1;
244 } else {
245 // We know that one arm of the conditional goes to BB, so the other must
246 // go somewhere unrelated, and this must not be an "if statement".
247 return 0;
248 }
249
Chris Lattner723c66d2004-02-11 03:36:04 +0000250 return Pred1Br->getCondition();
251 }
252
253 // Ok, if we got here, both predecessors end with an unconditional branch to
254 // BB. Don't panic! If both blocks only have a single (identical)
255 // predecessor, and THAT is a conditional branch, then we're all ok!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000256 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
257 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
Chris Lattner723c66d2004-02-11 03:36:04 +0000258 return 0;
259
260 // Otherwise, if this is a conditional branch, then we can use it!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000261 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
262 if (BI == 0) return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000263
Chris Lattner995ba1b2010-12-14 07:15:21 +0000264 assert(BI->isConditional() && "Two successors but not conditional?");
265 if (BI->getSuccessor(0) == Pred1) {
266 IfTrue = Pred1;
267 IfFalse = Pred2;
268 } else {
269 IfTrue = Pred2;
270 IfFalse = Pred1;
Chris Lattner723c66d2004-02-11 03:36:04 +0000271 }
Chris Lattner995ba1b2010-12-14 07:15:21 +0000272 return BI->getCondition();
Chris Lattner723c66d2004-02-11 03:36:04 +0000273}
274
Dan Gohman3b205172012-01-05 23:58:56 +0000275/// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
276/// given instruction, which is assumed to be safe to speculate. 1 means
277/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
278static unsigned ComputeSpeculationCost(const User *I) {
279 assert(isSafeToSpeculativelyExecute(I) &&
280 "Instruction is not safe to speculatively execute!");
281 switch (Operator::getOpcode(I)) {
282 default:
283 // In doubt, be conservative.
284 return UINT_MAX;
285 case Instruction::GetElementPtr:
286 // GEPs are cheap if all indices are constant.
287 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
288 return UINT_MAX;
289 return 1;
290 case Instruction::Load:
291 case Instruction::Add:
292 case Instruction::Sub:
293 case Instruction::And:
294 case Instruction::Or:
295 case Instruction::Xor:
296 case Instruction::Shl:
297 case Instruction::LShr:
298 case Instruction::AShr:
299 case Instruction::ICmp:
300 case Instruction::Trunc:
301 case Instruction::ZExt:
302 case Instruction::SExt:
303 return 1; // These are all cheap.
304
305 case Instruction::Call:
306 case Instruction::Select:
307 return 2;
308 }
309}
310
Bill Wendling5049fa62009-01-19 23:43:56 +0000311/// DominatesMergePoint - If we have a merge point of an "if condition" as
312/// accepted above, return true if the specified value dominates the block. We
313/// don't handle the true generality of domination here, just a special case
314/// which works well enough for us.
315///
316/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournef15907f2011-04-29 18:47:31 +0000317/// see if V (which must be an instruction) and its recursive operands
318/// that do not dominate BB have a combined cost lower than CostRemaining and
319/// are non-trapping. If both are true, the instruction is inserted into the
320/// set and true is returned.
321///
322/// The cost for most non-trapping instructions is defined as 1 except for
323/// Select whose cost is 2.
324///
325/// After this function returns, CostRemaining is decreased by the cost of
326/// V plus its non-dominating operands. If that cost is greater than
327/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner9c078662004-10-14 05:13:36 +0000328static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Peter Collingbournef15907f2011-04-29 18:47:31 +0000329 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
330 unsigned &CostRemaining) {
Chris Lattner570751c2004-04-09 22:50:22 +0000331 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000332 if (!I) {
333 // Non-instructions all dominate instructions, but not all constantexprs
334 // can be executed unconditionally.
335 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
336 if (C->canTrap())
337 return false;
338 return true;
339 }
Chris Lattner570751c2004-04-09 22:50:22 +0000340 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000341
Chris Lattnerda895d62005-02-27 06:18:25 +0000342 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000343 // the bottom of this block.
344 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000345
Chris Lattner570751c2004-04-09 22:50:22 +0000346 // If this instruction is defined in a block that contains an unconditional
347 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner44da7ca2010-12-14 07:41:39 +0000348 // statement". If not, it definitely dominates the region.
349 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
350 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
351 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +0000352
Chris Lattner44da7ca2010-12-14 07:41:39 +0000353 // If we aren't allowing aggressive promotion anymore, then don't consider
354 // instructions in the 'if region'.
355 if (AggressiveInsts == 0) return false;
Andrew Trick6b014382012-08-29 21:46:36 +0000356
Peter Collingbournef15907f2011-04-29 18:47:31 +0000357 // If we have seen this instruction before, don't count it again.
358 if (AggressiveInsts->count(I)) return true;
359
Chris Lattner44da7ca2010-12-14 07:41:39 +0000360 // Okay, it looks like the instruction IS in the "condition". Check to
361 // see if it's a cheap instruction to unconditionally compute, and if it
362 // only uses stuff defined outside of the condition. If so, hoist it out.
Dan Gohmanf0426602011-12-14 23:49:11 +0000363 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner44da7ca2010-12-14 07:41:39 +0000364 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000365
Dan Gohman3b205172012-01-05 23:58:56 +0000366 unsigned Cost = ComputeSpeculationCost(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000367
Peter Collingbournef15907f2011-04-29 18:47:31 +0000368 if (Cost > CostRemaining)
369 return false;
370
371 CostRemaining -= Cost;
372
373 // Okay, we can only really hoist these out if their operands do
374 // not take us over the cost threshold.
Chris Lattner44da7ca2010-12-14 07:41:39 +0000375 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Peter Collingbournef15907f2011-04-29 18:47:31 +0000376 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
Chris Lattner44da7ca2010-12-14 07:41:39 +0000377 return false;
378 // Okay, it's safe to do this! Remember this instruction.
379 AggressiveInsts->insert(I);
Chris Lattner723c66d2004-02-11 03:36:04 +0000380 return true;
381}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000382
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000383/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
384/// and PointerNullValue. Return NULL if value is not a constant int.
Chris Lattner28acc132010-12-13 03:30:12 +0000385static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000386 // Normal constant int.
387 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000388 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000389 return CI;
390
391 // This is some kind of pointer constant. Turn it into a pointer-sized
392 // ConstantInt if possible.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000393 IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000394
395 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
396 if (isa<ConstantPointerNull>(V))
397 return ConstantInt::get(PtrTy, 0);
398
399 // IntToPtr const int.
400 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
401 if (CE->getOpcode() == Instruction::IntToPtr)
402 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
403 // The constant is very likely to have the right type already.
404 if (CI->getType() == PtrTy)
405 return CI;
406 else
407 return cast<ConstantInt>
408 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
409 }
410 return 0;
411}
412
Chris Lattner0aa749b2010-12-13 04:26:26 +0000413/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
414/// collection of icmp eq/ne instructions that compare a value against a
415/// constant, return the value being compared, and stick the constant into the
416/// Values vector.
Chris Lattner28acc132010-12-13 03:30:12 +0000417static Value *
Chris Lattner0aa749b2010-12-13 04:26:26 +0000418GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000419 const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000420 Instruction *I = dyn_cast<Instruction>(V);
421 if (I == 0) return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000422
Chris Lattner7312a222010-12-13 04:50:38 +0000423 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000424 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Chris Lattnere27db742010-12-17 06:20:15 +0000425 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
426 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000427 UsedICmps++;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000428 Vals.push_back(C);
429 return I->getOperand(0);
430 }
Andrew Trick6b014382012-08-29 21:46:36 +0000431
Chris Lattnere27db742010-12-17 06:20:15 +0000432 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
433 // the set.
434 ConstantRange Span =
Chris Lattnera37029c2010-12-18 20:22:49 +0000435 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Andrew Trick6b014382012-08-29 21:46:36 +0000436
Chris Lattnere27db742010-12-17 06:20:15 +0000437 // If this is an and/!= check then we want to optimize "x ugt 2" into
438 // x != 0 && x != 1.
439 if (!isEQ)
440 Span = Span.inverse();
Andrew Trick6b014382012-08-29 21:46:36 +0000441
Chris Lattnere27db742010-12-17 06:20:15 +0000442 // If there are a ton of values, we don't want to make a ginormous switch.
Nick Lewyckyf460bf82012-01-19 18:19:42 +0000443 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
Chris Lattnere27db742010-12-17 06:20:15 +0000444 return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000445
Chris Lattnere27db742010-12-17 06:20:15 +0000446 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
447 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000448 UsedICmps++;
Chris Lattnere27db742010-12-17 06:20:15 +0000449 return I->getOperand(0);
450 }
Chris Lattner662269d2010-12-13 04:18:32 +0000451 return 0;
452 }
Andrew Trick6b014382012-08-29 21:46:36 +0000453
Chris Lattner7312a222010-12-13 04:50:38 +0000454 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000455 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Chris Lattner662269d2010-12-13 04:18:32 +0000456 return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000457
Chris Lattner7312a222010-12-13 04:50:38 +0000458 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000459 unsigned UsedICmpsBeforeLHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000460 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000461 isEQ, UsedICmps)) {
Chris Lattner7312a222010-12-13 04:50:38 +0000462 unsigned NumVals = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000463 unsigned UsedICmpsBeforeRHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000464 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000465 isEQ, UsedICmps)) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000466 if (LHS == RHS)
467 return LHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000468 Vals.resize(NumVals);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000469 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000470 }
Chris Lattner7312a222010-12-13 04:50:38 +0000471
472 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
473 // set it and return success.
474 if (Extra == 0 || Extra == I->getOperand(1)) {
475 Extra = I->getOperand(1);
476 return LHS;
477 }
Andrew Trick6b014382012-08-29 21:46:36 +0000478
Chris Lattner7312a222010-12-13 04:50:38 +0000479 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000480 UsedICmps = UsedICmpsBeforeLHS;
Chris Lattner7312a222010-12-13 04:50:38 +0000481 return 0;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000482 }
Andrew Trick6b014382012-08-29 21:46:36 +0000483
Chris Lattner7312a222010-12-13 04:50:38 +0000484 // If the LHS can't be folded in, but Extra is available and RHS can, try to
485 // use LHS as Extra.
486 if (Extra == 0 || Extra == I->getOperand(0)) {
Chris Lattner92407e52010-12-13 07:41:29 +0000487 Value *OldExtra = Extra;
Chris Lattner7312a222010-12-13 04:50:38 +0000488 Extra = I->getOperand(0);
489 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000490 isEQ, UsedICmps))
Chris Lattner7312a222010-12-13 04:50:38 +0000491 return RHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000492 assert(Vals.size() == NumValsBeforeLHS);
493 Extra = OldExtra;
Chris Lattner7312a222010-12-13 04:50:38 +0000494 }
Andrew Trick6b014382012-08-29 21:46:36 +0000495
Chris Lattner0d560082004-02-24 05:38:11 +0000496 return 0;
497}
Nick Lewycky9d523102011-12-26 20:37:40 +0000498
Eli Friedman080efb82008-12-16 20:54:32 +0000499static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Nick Lewycky9d523102011-12-26 20:37:40 +0000500 Instruction *Cond = 0;
Eli Friedman080efb82008-12-16 20:54:32 +0000501 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
502 Cond = dyn_cast<Instruction>(SI->getCondition());
503 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
504 if (BI->isConditional())
505 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000506 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
507 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000508 }
509
510 TI->eraseFromParent();
511 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
512}
513
Chris Lattner9fd49552008-11-27 23:25:44 +0000514/// isValueEqualityComparison - Return true if the specified terminator checks
515/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000516Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
517 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000518 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
519 // Do not permit merging of large switch instructions into their
520 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000521 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
522 pred_end(SI->getParent())) <= 128)
523 CV = SI->getCondition();
524 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000525 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000526 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
527 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
528 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Chris Lattner28acc132010-12-13 03:30:12 +0000529 GetConstantInt(ICI->getOperand(1), TD))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000530 CV = ICI->getOperand(0);
531
532 // Unwrap any lossless ptrtoint cast.
533 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
534 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
535 CV = PTII->getOperand(0);
536 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000537}
538
Bill Wendling5049fa62009-01-19 23:43:56 +0000539/// GetValueEqualityComparisonCases - Given a value comparison instruction,
540/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000541BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000542GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherc723eb12012-07-02 23:22:21 +0000543 std::vector<ValueEqualityComparisonCase>
544 &Cases) {
Chris Lattner542f1492004-02-28 21:28:10 +0000545 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherc723eb12012-07-02 23:22:21 +0000546 Cases.reserve(SI->getNumCases());
547 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
548 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
549 i.getCaseSuccessor()));
Chris Lattner542f1492004-02-28 21:28:10 +0000550 return SI->getDefaultDest();
551 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000552
Chris Lattner542f1492004-02-28 21:28:10 +0000553 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherc723eb12012-07-02 23:22:21 +0000555 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
556 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
557 TD),
558 Succ));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000559 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000560}
561
Eric Christopherc723eb12012-07-02 23:22:21 +0000562
563/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
564/// in the list that match the specified block.
565static void EliminateBlockCases(BasicBlock *BB,
566 std::vector<ValueEqualityComparisonCase> &Cases) {
567 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
568 if (Cases[i].Dest == BB) {
569 Cases.erase(Cases.begin()+i);
570 --i; --e;
571 }
572}
573
574/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
575/// well.
576static bool
577ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
578 std::vector<ValueEqualityComparisonCase > &C2) {
579 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
580
581 // Make V1 be smaller than V2.
582 if (V1->size() > V2->size())
583 std::swap(V1, V2);
584
585 if (V1->size() == 0) return false;
586 if (V1->size() == 1) {
587 // Just scan V2.
588 ConstantInt *TheVal = (*V1)[0].Value;
589 for (unsigned i = 0, e = V2->size(); i != e; ++i)
590 if (TheVal == (*V2)[i].Value)
591 return true;
592 }
593
594 // Otherwise, just sort both lists and compare element by element.
595 array_pod_sort(V1->begin(), V1->end());
596 array_pod_sort(V2->begin(), V2->end());
597 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
598 while (i1 != e1 && i2 != e2) {
599 if ((*V1)[i1].Value == (*V2)[i2].Value)
600 return true;
601 if ((*V1)[i1].Value < (*V2)[i2].Value)
602 ++i1;
603 else
604 ++i2;
605 }
606 return false;
607}
608
Bill Wendling5049fa62009-01-19 23:43:56 +0000609/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
610/// terminator instruction and its block is known to only have a single
611/// predecessor block, check to see if that predecessor is also a value
612/// comparison with the same value, and if that comparison determines the
613/// outcome of this comparison. If so, simplify TI. This does a very limited
614/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000615bool SimplifyCFGOpt::
616SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patel007349d2011-05-18 20:35:38 +0000617 BasicBlock *Pred,
618 IRBuilder<> &Builder) {
Chris Lattner623369a2005-02-24 06:17:52 +0000619 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
620 if (!PredVal) return false; // Not a value comparison in predecessor.
621
622 Value *ThisVal = isValueEqualityComparison(TI);
623 assert(ThisVal && "This isn't a value comparison!!");
624 if (ThisVal != PredVal) return false; // Different predicates.
625
Andrew Trickb1b97832012-08-29 21:46:38 +0000626 // TODO: Preserve branch weight metadata, similarly to how
627 // FoldValueComparisonIntoPredecessors preserves it.
628
Chris Lattner623369a2005-02-24 06:17:52 +0000629 // Find out information about when control will move from Pred to TI's block.
Eric Christopherc723eb12012-07-02 23:22:21 +0000630 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000631 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
632 PredCases);
Eric Christopherc723eb12012-07-02 23:22:21 +0000633 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000634
Chris Lattner623369a2005-02-24 06:17:52 +0000635 // Find information about how control leaves this block.
Eric Christopherc723eb12012-07-02 23:22:21 +0000636 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000637 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherc723eb12012-07-02 23:22:21 +0000638 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner623369a2005-02-24 06:17:52 +0000639
640 // If TI's block is the default block from Pred's comparison, potentially
641 // simplify TI based on this knowledge.
642 if (PredDef == TI->getParent()) {
643 // If we are here, we know that the value is none of those cases listed in
644 // PredCases. If there are any cases in ThisCases that are in PredCases, we
645 // can simplify TI.
Eric Christopherc723eb12012-07-02 23:22:21 +0000646 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000647 return false;
Andrew Trick6b014382012-08-29 21:46:36 +0000648
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000649 if (isa<BranchInst>(TI)) {
650 // Okay, one of the successors of this condbr is dead. Convert it to a
651 // uncond br.
652 assert(ThisCases.size() == 1 && "Branch can only have one case!");
653 // Insert the new branch.
Devang Patel007349d2011-05-18 20:35:38 +0000654 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000655 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000656
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000657 // Remove PHI node entries for the dead edge.
Eric Christopherc723eb12012-07-02 23:22:21 +0000658 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000659
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000660 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
661 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000662
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000663 EraseTerminatorInstAndDCECond(TI);
664 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000665 }
Andrew Trick6b014382012-08-29 21:46:36 +0000666
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000667 SwitchInst *SI = cast<SwitchInst>(TI);
668 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherc723eb12012-07-02 23:22:21 +0000669 SmallPtrSet<Constant*, 16> DeadCases;
670 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
671 DeadCases.insert(PredCases[i].Value);
Chris Lattner623369a2005-02-24 06:17:52 +0000672
David Greene89d6fd32010-01-05 01:26:52 +0000673 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000674 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000675
Manman Renad289072012-09-14 21:53:06 +0000676 // Collect branch weights into a vector.
677 SmallVector<uint32_t, 8> Weights;
678 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
679 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
680 if (HasWeight)
681 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
682 ++MD_i) {
683 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
684 assert(CI);
685 Weights.push_back(CI->getValue().getZExtValue());
686 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000687 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
688 --i;
689 if (DeadCases.count(i.getCaseValue())) {
Manman Renad289072012-09-14 21:53:06 +0000690 if (HasWeight) {
691 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
692 Weights.pop_back();
693 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000694 i.getCaseSuccessor()->removePredecessor(TI->getParent());
695 SI->removeCase(i);
696 }
697 }
Manman Renad289072012-09-14 21:53:06 +0000698 if (HasWeight)
699 SI->setMetadata(LLVMContext::MD_prof,
700 MDBuilder(SI->getParent()->getContext()).
701 createBranchWeights(Weights));
Eric Christopherc723eb12012-07-02 23:22:21 +0000702
703 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000704 return true;
705 }
Andrew Trick6b014382012-08-29 21:46:36 +0000706
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000707 // Otherwise, TI's block must correspond to some matched value. Find out
708 // which value (or set of values) this is.
Eric Christopherc723eb12012-07-02 23:22:21 +0000709 ConstantInt *TIV = 0;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000710 BasicBlock *TIBB = TI->getParent();
Eric Christopherc723eb12012-07-02 23:22:21 +0000711 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
712 if (PredCases[i].Dest == TIBB) {
713 if (TIV != 0)
714 return false; // Cannot handle multiple values coming to this block.
715 TIV = PredCases[i].Value;
716 }
717 assert(TIV && "No edge from pred to succ?");
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000718
719 // Okay, we found the one constant that our value can be if we get into TI's
720 // BB. Find out which successor will unconditionally be branched to.
Eric Christopherc723eb12012-07-02 23:22:21 +0000721 BasicBlock *TheRealDest = 0;
722 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
723 if (ThisCases[i].Value == TIV) {
724 TheRealDest = ThisCases[i].Dest;
725 break;
726 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000727
728 // If not handled by any explicit cases, it is handled by the default case.
729 if (TheRealDest == 0) TheRealDest = ThisDef;
730
731 // Remove PHI node entries for dead edges.
732 BasicBlock *CheckEdge = TheRealDest;
733 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
734 if (*SI != CheckEdge)
735 (*SI)->removePredecessor(TIBB);
736 else
737 CheckEdge = 0;
738
739 // Insert the new branch.
Devang Patel007349d2011-05-18 20:35:38 +0000740 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000741 (void) NI;
742
743 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
744 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
745
746 EraseTerminatorInstAndDCECond(TI);
747 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000748}
749
Dale Johannesenc81f5442009-03-12 21:01:11 +0000750namespace {
751 /// ConstantIntOrdering - This class implements a stable ordering of constant
752 /// integers that does not depend on their address. This is important for
753 /// applications that sort ConstantInt's to ensure uniqueness.
754 struct ConstantIntOrdering {
755 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
756 return LHS->getValue().ult(RHS->getValue());
757 }
758 };
759}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000760
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000761static int ConstantIntSortPredicate(const void *P1, const void *P2) {
Roman Divacky59324292012-09-05 22:26:57 +0000762 const ConstantInt *LHS = *(const ConstantInt*const*)P1;
763 const ConstantInt *RHS = *(const ConstantInt*const*)P2;
Chris Lattnerba3c8152010-12-15 04:52:41 +0000764 if (LHS->getValue().ult(RHS->getValue()))
765 return 1;
766 if (LHS->getValue() == RHS->getValue())
767 return 0;
768 return -1;
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000769}
770
Andrew Trickb1b97832012-08-29 21:46:38 +0000771static inline bool HasBranchWeights(const Instruction* I) {
772 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
773 if (ProfMD && ProfMD->getOperand(0))
774 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
775 return MDS->getString().equals("branch_weights");
776
777 return false;
778}
779
Manman Ren020aba02012-09-11 17:43:35 +0000780/// Get Weights of a given TerminatorInst, the default weight is at the front
781/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
782/// metadata.
783static void GetBranchWeights(TerminatorInst *TI,
784 SmallVectorImpl<uint64_t> &Weights) {
785 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
786 assert(MD);
787 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
788 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(i));
Andrew Trickb1b97832012-08-29 21:46:38 +0000789 assert(CI);
Manman Ren020aba02012-09-11 17:43:35 +0000790 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trickb1b97832012-08-29 21:46:38 +0000791 }
792
Manman Ren020aba02012-09-11 17:43:35 +0000793 // If TI is a conditional eq, the default case is the false case,
794 // and the corresponding branch-weight data is at index 2. We swap the
795 // default weight to be the first entry.
796 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
797 assert(Weights.size() == 2);
798 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
799 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
800 std::swap(Weights.front(), Weights.back());
Andrew Trickb1b97832012-08-29 21:46:38 +0000801 }
802}
803
804/// Sees if any of the weights are too big for a uint32_t, and halves all the
805/// weights if any are.
806static void FitWeights(MutableArrayRef<uint64_t> Weights) {
807 bool Halve = false;
808 for (unsigned i = 0; i < Weights.size(); ++i)
809 if (Weights[i] > UINT_MAX) {
810 Halve = true;
811 break;
812 }
813
814 if (! Halve)
815 return;
816
817 for (unsigned i = 0; i < Weights.size(); ++i)
818 Weights[i] /= 2;
819}
820
Bill Wendling5049fa62009-01-19 23:43:56 +0000821/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
822/// equality comparison instruction (either a switch or a branch on "X == c").
823/// See if any of the predecessors of the terminator block are value comparisons
824/// on the same value. If so, and if safe to do so, fold them together.
Devang Patelb55d9242011-05-18 20:53:17 +0000825bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
826 IRBuilder<> &Builder) {
Chris Lattner542f1492004-02-28 21:28:10 +0000827 BasicBlock *BB = TI->getParent();
828 Value *CV = isValueEqualityComparison(TI); // CondVal
829 assert(CV && "Not a comparison?");
830 bool Changed = false;
831
Chris Lattner82442432008-02-18 07:42:56 +0000832 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000833 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000834 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000835
Chris Lattner542f1492004-02-28 21:28:10 +0000836 // See if the predecessor is a comparison with the same value.
837 TerminatorInst *PTI = Pred->getTerminator();
838 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
839
840 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
841 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherc723eb12012-07-02 23:22:21 +0000842 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000843 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
844
Eric Christopherc723eb12012-07-02 23:22:21 +0000845 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000846 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
847
848 // Based on whether the default edge from PTI goes to BB or not, fill in
849 // PredCases and PredDefault with the new switch cases we would like to
850 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000851 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000852
Andrew Trickb1b97832012-08-29 21:46:38 +0000853 // Update the branch weight metadata along the way
854 SmallVector<uint64_t, 8> Weights;
Andrew Trickb1b97832012-08-29 21:46:38 +0000855 bool PredHasWeights = HasBranchWeights(PTI);
856 bool SuccHasWeights = HasBranchWeights(TI);
857
Manman Ren796d9452012-09-14 19:05:19 +0000858 if (PredHasWeights) {
Manman Ren020aba02012-09-11 17:43:35 +0000859 GetBranchWeights(PTI, Weights);
Manman Ren796d9452012-09-14 19:05:19 +0000860 // branch-weight metadata is inconsistant here.
861 if (Weights.size() != 1 + PredCases.size())
862 PredHasWeights = SuccHasWeights = false;
863 } else if (SuccHasWeights)
Andrew Trickb1b97832012-08-29 21:46:38 +0000864 // If there are no predecessor weights but there are successor weights,
865 // populate Weights with 1, which will later be scaled to the sum of
866 // successor's weights
867 Weights.assign(1 + PredCases.size(), 1);
Andrew Trickb1b97832012-08-29 21:46:38 +0000868
Manman Ren020aba02012-09-11 17:43:35 +0000869 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren796d9452012-09-14 19:05:19 +0000870 if (SuccHasWeights) {
Manman Ren020aba02012-09-11 17:43:35 +0000871 GetBranchWeights(TI, SuccWeights);
Manman Ren796d9452012-09-14 19:05:19 +0000872 // branch-weight metadata is inconsistant here.
873 if (SuccWeights.size() != 1 + BBCases.size())
874 PredHasWeights = SuccHasWeights = false;
875 } else if (PredHasWeights)
Manman Ren020aba02012-09-11 17:43:35 +0000876 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trickb1b97832012-08-29 21:46:38 +0000877
Chris Lattner542f1492004-02-28 21:28:10 +0000878 if (PredDefault == BB) {
879 // If this is the default destination from PTI, only the edges in TI
880 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherc723eb12012-07-02 23:22:21 +0000881 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
882 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
883 if (PredCases[i].Dest != BB)
884 PTIHandled.insert(PredCases[i].Value);
885 else {
886 // The default destination is BB, we don't need explicit targets.
887 std::swap(PredCases[i], PredCases.back());
Andrew Trickb1b97832012-08-29 21:46:38 +0000888
Manman Ren020aba02012-09-11 17:43:35 +0000889 if (PredHasWeights || SuccHasWeights) {
890 // Increase weight for the default case.
891 Weights[0] += Weights[i+1];
Andrew Trickb1b97832012-08-29 21:46:38 +0000892 std::swap(Weights[i+1], Weights.back());
893 Weights.pop_back();
894 }
895
Eric Christopherc723eb12012-07-02 23:22:21 +0000896 PredCases.pop_back();
897 --i; --e;
898 }
Chris Lattner542f1492004-02-28 21:28:10 +0000899
Eric Christopherc723eb12012-07-02 23:22:21 +0000900 // Reconstruct the new switch statement we will be building.
Chris Lattner542f1492004-02-28 21:28:10 +0000901 if (PredDefault != BBDefault) {
902 PredDefault->removePredecessor(Pred);
903 PredDefault = BBDefault;
904 NewSuccessors.push_back(BBDefault);
905 }
Andrew Trickb1b97832012-08-29 21:46:38 +0000906
Manman Ren020aba02012-09-11 17:43:35 +0000907 unsigned CasesFromPred = Weights.size();
908 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherc723eb12012-07-02 23:22:21 +0000909 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
910 if (!PTIHandled.count(BBCases[i].Value) &&
911 BBCases[i].Dest != BBDefault) {
912 PredCases.push_back(BBCases[i]);
913 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren020aba02012-09-11 17:43:35 +0000914 if (SuccHasWeights || PredHasWeights) {
915 // The default weight is at index 0, so weight for the ith case
916 // should be at index i+1. Scale the cases from successor by
917 // PredDefaultWeight (Weights[0]).
918 Weights.push_back(Weights[0] * SuccWeights[i+1]);
919 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trickb1b97832012-08-29 21:46:38 +0000920 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000921 }
Chris Lattner542f1492004-02-28 21:28:10 +0000922
Manman Ren020aba02012-09-11 17:43:35 +0000923 if (SuccHasWeights || PredHasWeights) {
924 ValidTotalSuccWeight += SuccWeights[0];
925 // Scale the cases from predecessor by ValidTotalSuccWeight.
926 for (unsigned i = 1; i < CasesFromPred; ++i)
927 Weights[i] *= ValidTotalSuccWeight;
928 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
929 Weights[0] *= SuccWeights[0];
930 }
Chris Lattner542f1492004-02-28 21:28:10 +0000931 } else {
932 // If this is not the default destination from PSI, only the edges
933 // in SI that occur in PSI with a destination of BB will be
934 // activated.
Eric Christopherc723eb12012-07-02 23:22:21 +0000935 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rena8a2b992012-09-14 17:29:56 +0000936 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherc723eb12012-07-02 23:22:21 +0000937 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
938 if (PredCases[i].Dest == BB) {
939 PTIHandled.insert(PredCases[i].Value);
Manman Rena8a2b992012-09-14 17:29:56 +0000940
941 if (PredHasWeights || SuccHasWeights) {
942 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
943 std::swap(Weights[i+1], Weights.back());
944 Weights.pop_back();
945 }
946
Eric Christopherc723eb12012-07-02 23:22:21 +0000947 std::swap(PredCases[i], PredCases.back());
948 PredCases.pop_back();
949 --i; --e;
950 }
Chris Lattner542f1492004-02-28 21:28:10 +0000951
952 // Okay, now we know which constants were sent to BB from the
953 // predecessor. Figure out where they will all go now.
Eric Christopherc723eb12012-07-02 23:22:21 +0000954 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
955 if (PTIHandled.count(BBCases[i].Value)) {
956 // If this is one we are capable of getting...
Manman Rena8a2b992012-09-14 17:29:56 +0000957 if (PredHasWeights || SuccHasWeights)
958 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherc723eb12012-07-02 23:22:21 +0000959 PredCases.push_back(BBCases[i]);
960 NewSuccessors.push_back(BBCases[i].Dest);
961 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
962 }
963
Chris Lattner542f1492004-02-28 21:28:10 +0000964 // If there are any constants vectored to BB that TI doesn't handle,
965 // they must go to the default destination of TI.
Andrew Trick6b014382012-08-29 21:46:36 +0000966 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherc723eb12012-07-02 23:22:21 +0000967 PTIHandled.begin(),
968 E = PTIHandled.end(); I != E; ++I) {
Manman Rena8a2b992012-09-14 17:29:56 +0000969 if (PredHasWeights || SuccHasWeights)
970 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherc723eb12012-07-02 23:22:21 +0000971 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattner542f1492004-02-28 21:28:10 +0000972 NewSuccessors.push_back(BBDefault);
Eric Christopherc723eb12012-07-02 23:22:21 +0000973 }
Chris Lattner542f1492004-02-28 21:28:10 +0000974 }
975
976 // Okay, at this point, we know which new successor Pred will get. Make
977 // sure we update the number of entries in the PHI nodes for these
978 // successors.
979 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
980 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
981
Devang Patelb55d9242011-05-18 20:53:17 +0000982 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000983 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000984 if (CV->getType()->isPointerTy()) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000985 assert(TD && "Cannot switch on pointer without TargetData");
Devang Patelb55d9242011-05-18 20:53:17 +0000986 CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
987 "magicptr");
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000988 }
989
Chris Lattner542f1492004-02-28 21:28:10 +0000990 // Now that the successors are updated, create the new Switch instruction.
Devang Patelb55d9242011-05-18 20:53:17 +0000991 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
992 PredCases.size());
Devang Pateld80e8ed2011-05-17 23:29:05 +0000993 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherc723eb12012-07-02 23:22:21 +0000994 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
995 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner13b2f762005-01-01 16:02:12 +0000996
Andrew Trickb1b97832012-08-29 21:46:38 +0000997 if (PredHasWeights || SuccHasWeights) {
998 // Halve the weights if any of them cannot fit in an uint32_t
999 FitWeights(Weights);
1000
1001 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1002
1003 NewSI->setMetadata(LLVMContext::MD_prof,
1004 MDBuilder(BB->getContext()).
1005 createBranchWeights(MDWeights));
1006 }
1007
Eli Friedman080efb82008-12-16 20:54:32 +00001008 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +00001009
Chris Lattner542f1492004-02-28 21:28:10 +00001010 // Okay, last check. If BB is still a successor of PSI, then we must
1011 // have an infinite loop case. If so, add an infinitely looping block
1012 // to handle the case to preserve the behavior of the code.
1013 BasicBlock *InfLoopBlock = 0;
1014 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1015 if (NewSI->getSuccessor(i) == BB) {
1016 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +00001017 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +00001018 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001019 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1020 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +00001021 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +00001022 }
1023 NewSI->setSuccessor(i, InfLoopBlock);
1024 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001025
Chris Lattner542f1492004-02-28 21:28:10 +00001026 Changed = true;
1027 }
1028 }
1029 return Changed;
1030}
1031
Dale Johannesenc1f10402009-06-15 20:59:27 +00001032// isSafeToHoistInvoke - If we would need to insert a select that uses the
1033// value of this invoke (comments in HoistThenElseCodeToIf explain why we
1034// would need to do this), we can't hoist the invoke, as there is nowhere
1035// to put the select in this case.
1036static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1037 Instruction *I1, Instruction *I2) {
1038 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1039 PHINode *PN;
1040 for (BasicBlock::iterator BBI = SI->begin();
1041 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1042 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1043 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1044 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1045 return false;
1046 }
1047 }
1048 }
1049 return true;
1050}
1051
Chris Lattner6306d072005-08-03 17:59:45 +00001052/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +00001053/// BB2, hoist any common code in the two blocks up into the branch block. The
1054/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Rafael Espindola216dde92011-05-19 02:26:30 +00001055static bool HoistThenElseCodeToIf(BranchInst *BI) {
Chris Lattner37dc9382004-11-30 00:29:14 +00001056 // This does very trivial matching, with limited scanning, to find identical
1057 // instructions in the two blocks. In particular, we don't want to get into
1058 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1059 // such, we currently just scan for obviously identical instructions in an
1060 // identical order.
1061 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1062 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1063
Devang Patel65085cf2009-02-04 00:03:08 +00001064 BasicBlock::iterator BB1_Itr = BB1->begin();
1065 BasicBlock::iterator BB2_Itr = BB2->begin();
1066
1067 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel949666e2011-04-07 17:27:36 +00001068 // Skip debug info if it is not identical.
1069 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1070 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1071 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1072 while (isa<DbgInfoIntrinsic>(I1))
1073 I1 = BB1_Itr++;
1074 while (isa<DbgInfoIntrinsic>(I2))
1075 I2 = BB2_Itr++;
1076 }
Devang Patelae6c95b2011-04-07 00:30:15 +00001077 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +00001078 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +00001079 return false;
1080
1081 // If we get here, we can hoist at least one instruction.
1082 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +00001083
1084 do {
1085 // If we are hoisting the terminator instruction, don't move one (making a
1086 // broken BB), instead clone it, and remove BI.
1087 if (isa<TerminatorInst>(I1))
1088 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +00001089
Chris Lattner37dc9382004-11-30 00:29:14 +00001090 // For a normal instruction, we just move one to right before the branch,
1091 // then replace all uses of the other with the first. Finally, we remove
1092 // the now redundant second instruction.
1093 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1094 if (!I2->use_empty())
1095 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +00001096 I1->intersectOptionalDataWith(I2);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001097 I2->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001098
Devang Patel65085cf2009-02-04 00:03:08 +00001099 I1 = BB1_Itr++;
Devang Patel65085cf2009-02-04 00:03:08 +00001100 I2 = BB2_Itr++;
Devang Patel949666e2011-04-07 17:27:36 +00001101 // Skip debug info if it is not identical.
1102 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1103 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1104 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1105 while (isa<DbgInfoIntrinsic>(I1))
1106 I1 = BB1_Itr++;
1107 while (isa<DbgInfoIntrinsic>(I2))
1108 I2 = BB2_Itr++;
1109 }
Devang Patelae6c95b2011-04-07 00:30:15 +00001110 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +00001111
1112 return true;
1113
1114HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +00001115 // It may not be possible to hoist an invoke.
1116 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1117 return true;
1118
Chris Lattner37dc9382004-11-30 00:29:14 +00001119 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +00001120 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +00001121 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +00001122 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +00001123 I1->replaceAllUsesWith(NT);
1124 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +00001125 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +00001126 }
1127
Devang Pateld3a17882011-05-19 20:52:46 +00001128 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner37dc9382004-11-30 00:29:14 +00001129 // Hoisting one of the terminators from our successor is a great thing.
1130 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1131 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1132 // nodes, so we insert select instruction to compute the final result.
1133 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1134 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1135 PHINode *PN;
1136 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +00001137 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +00001138 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1139 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001140 if (BB1V == BB2V) continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001141
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001142 // These values do not agree. Insert a select instruction before NT
1143 // that determines the right value.
1144 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Andrew Trick6b014382012-08-29 21:46:36 +00001145 if (SI == 0)
Devang Pateld3a17882011-05-19 20:52:46 +00001146 SI = cast<SelectInst>
1147 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1148 BB1V->getName()+"."+BB2V->getName()));
1149
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001150 // Make the PHI node use the select for all incoming values for BB1/BB2
1151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1152 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1153 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +00001154 }
1155 }
1156
1157 // Update any PHI nodes in our new successors.
1158 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1159 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +00001160
Eli Friedman080efb82008-12-16 20:54:32 +00001161 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +00001162 return true;
1163}
1164
Manman Ren554da1a2012-09-20 22:37:36 +00001165/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1166/// check whether BBEnd has only two predecessors and the other predecessor
1167/// ends with an unconditional branch. If it is true, sink any common code
1168/// in the two predecessors to BBEnd.
1169static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1170 assert(BI1->isUnconditional());
1171 BasicBlock *BB1 = BI1->getParent();
1172 BasicBlock *BBEnd = BI1->getSuccessor(0);
1173
1174 // Check that BBEnd has two predecessors and the other predecessor ends with
1175 // an unconditional branch.
Benjamin Kramerfdb96062012-09-30 21:03:56 +00001176 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1177 BasicBlock *Pred0 = *PI++;
1178 if (PI == PE) // Only one predecessor.
Manman Ren554da1a2012-09-20 22:37:36 +00001179 return false;
Benjamin Kramerfdb96062012-09-30 21:03:56 +00001180 BasicBlock *Pred1 = *PI++;
1181 if (PI != PE) // More than two predecessors.
1182 return false;
1183 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren554da1a2012-09-20 22:37:36 +00001184 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1185 if (!BI2 || !BI2->isUnconditional())
1186 return false;
1187
1188 // Gather the PHI nodes in BBEnd.
1189 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1190 Instruction *FirstNonPhiInBBEnd = 0;
1191 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1192 I != E; ++I) {
1193 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1194 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1195 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1196 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1197 } else {
1198 FirstNonPhiInBBEnd = &*I;
1199 break;
1200 }
1201 }
1202 if (!FirstNonPhiInBBEnd)
1203 return false;
1204
1205
1206 // This does very trivial matching, with limited scanning, to find identical
1207 // instructions in the two blocks. We scan backward for obviously identical
1208 // instructions in an identical order.
1209 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1210 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1211 RE2 = BB2->getInstList().rend();
1212 // Skip debug info.
1213 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1214 if (RI1 == RE1)
1215 return false;
1216 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1217 if (RI2 == RE2)
1218 return false;
1219 // Skip the unconditional branches.
1220 ++RI1;
1221 ++RI2;
1222
1223 bool Changed = false;
1224 while (RI1 != RE1 && RI2 != RE2) {
1225 // Skip debug info.
1226 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1227 if (RI1 == RE1)
1228 return Changed;
1229 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1230 if (RI2 == RE2)
1231 return Changed;
1232
1233 Instruction *I1 = &*RI1, *I2 = &*RI2;
1234 // I1 and I2 should have a single use in the same PHI node, and they
1235 // perform the same operation.
1236 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1237 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1238 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1239 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1240 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1241 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1242 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1243 !I1->hasOneUse() || !I2->hasOneUse() ||
1244 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1245 MapValueFromBB1ToBB2[I1].first != I2)
1246 return Changed;
1247
1248 // Check whether we should swap the operands of ICmpInst.
1249 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1250 bool SwapOpnds = false;
1251 if (ICmp1 && ICmp2 &&
1252 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1253 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1254 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1255 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1256 ICmp2->swapOperands();
1257 SwapOpnds = true;
1258 }
1259 if (!I1->isSameOperationAs(I2)) {
1260 if (SwapOpnds)
1261 ICmp2->swapOperands();
1262 return Changed;
1263 }
1264
1265 // The operands should be either the same or they need to be generated
1266 // with a PHI node after sinking. We only handle the case where there is
1267 // a single pair of different operands.
1268 Value *DifferentOp1 = 0, *DifferentOp2 = 0;
1269 unsigned Op1Idx = 0;
1270 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1271 if (I1->getOperand(I) == I2->getOperand(I))
1272 continue;
1273 // Early exit if we have more-than one pair of different operands or
1274 // the different operand is already in MapValueFromBB1ToBB2.
1275 // Early exit if we need a PHI node to replace a constant.
1276 if (DifferentOp1 ||
1277 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1278 MapValueFromBB1ToBB2.end() ||
1279 isa<Constant>(I1->getOperand(I)) ||
1280 isa<Constant>(I2->getOperand(I))) {
1281 // If we can't sink the instructions, undo the swapping.
1282 if (SwapOpnds)
1283 ICmp2->swapOperands();
1284 return Changed;
1285 }
1286 DifferentOp1 = I1->getOperand(I);
1287 Op1Idx = I;
1288 DifferentOp2 = I2->getOperand(I);
1289 }
1290
1291 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1292 // remove (I1, I2) from MapValueFromBB1ToBB2.
1293 if (DifferentOp1) {
1294 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1295 DifferentOp1->getName() + ".sink",
1296 BBEnd->begin());
1297 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1298 // I1 should use NewPN instead of DifferentOp1.
1299 I1->setOperand(Op1Idx, NewPN);
1300 NewPN->addIncoming(DifferentOp1, BB1);
1301 NewPN->addIncoming(DifferentOp2, BB2);
1302 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1303 }
1304 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1305 MapValueFromBB1ToBB2.erase(I1);
1306
1307 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1308 DEBUG(dbgs() << " " << *I2 << "\n";);
1309 // We need to update RE1 and RE2 if we are going to sink the first
1310 // instruction in the basic block down.
1311 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1312 // Sink the instruction.
1313 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1314 if (!OldPN->use_empty())
1315 OldPN->replaceAllUsesWith(I1);
1316 OldPN->eraseFromParent();
1317
1318 if (!I2->use_empty())
1319 I2->replaceAllUsesWith(I1);
1320 I1->intersectOptionalDataWith(I2);
1321 I2->eraseFromParent();
1322
1323 if (UpdateRE1)
1324 RE1 = BB1->getInstList().rend();
1325 if (UpdateRE2)
1326 RE2 = BB2->getInstList().rend();
1327 FirstNonPhiInBBEnd = I1;
1328 NumSinkCommons++;
1329 Changed = true;
1330 }
1331 return Changed;
1332}
1333
Evan Cheng4d09efd2008-06-07 08:52:29 +00001334/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
1335/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
1336/// (for now, restricted to a single instruction that's side effect free) from
1337/// the BB1 into the branch block to speculatively execute it.
Dan Gohman3b205172012-01-05 23:58:56 +00001338///
1339/// Turn
1340/// BB:
1341/// %t1 = icmp
1342/// br i1 %t1, label %BB1, label %BB2
1343/// BB1:
1344/// %t3 = add %t2, c
1345/// br label BB2
1346/// BB2:
1347/// =>
1348/// BB:
1349/// %t1 = icmp
1350/// %t4 = add %t2, c
1351/// %t3 = select i1 %t1, %t2, %t3
Rafael Espindola216dde92011-05-19 02:26:30 +00001352static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
Evan Cheng4d09efd2008-06-07 08:52:29 +00001353 // Only speculatively execution a single instruction (not counting the
1354 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +00001355 Instruction *HInst = NULL;
1356 Instruction *Term = BB1->getTerminator();
1357 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
1358 BBI != BBE; ++BBI) {
1359 Instruction *I = BBI;
1360 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001361 if (isa<DbgInfoIntrinsic>(I)) continue;
1362 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +00001363
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001364 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +00001365 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001366 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +00001367 }
Dan Gohman3b205172012-01-05 23:58:56 +00001368
1369 BasicBlock *BIParent = BI->getParent();
1370
1371 // Check the instruction to be hoisted, if there is one.
1372 if (HInst) {
1373 // Don't hoist the instruction if it's unsafe or expensive.
1374 if (!isSafeToSpeculativelyExecute(HInst))
1375 return false;
1376 if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
1377 return false;
1378
1379 // Do not hoist the instruction if any of its operands are defined but not
1380 // used in this BB. The transformation will prevent the operand from
1381 // being sunk into the use block.
Andrew Trick6b014382012-08-29 21:46:36 +00001382 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
Dan Gohman3b205172012-01-05 23:58:56 +00001383 i != e; ++i) {
1384 Instruction *OpI = dyn_cast<Instruction>(*i);
1385 if (OpI && OpI->getParent() == BIParent &&
1386 !OpI->mayHaveSideEffects() &&
1387 !OpI->isUsedInBasicBlock(BIParent))
1388 return false;
1389 }
1390 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001391
Evan Cheng797d9512008-06-11 19:18:20 +00001392 // Be conservative for now. FP select instruction can often be expensive.
1393 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001394 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +00001395 return false;
1396
Evan Cheng4d09efd2008-06-07 08:52:29 +00001397 // If BB1 is actually on the false edge of the conditional branch, remember
1398 // to swap the select operands later.
1399 bool Invert = false;
1400 if (BB1 != BI->getSuccessor(0)) {
1401 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1402 Invert = true;
1403 }
1404
Dan Gohman3b205172012-01-05 23:58:56 +00001405 // Collect interesting PHIs, and scan for hazards.
1406 SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001407 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Dan Gohman3b205172012-01-05 23:58:56 +00001408 for (BasicBlock::iterator I = BB2->begin();
1409 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1410 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1411 Value *BIParentV = PN->getIncomingValueForBlock(BIParent);
1412
1413 // Skip PHIs which are trivial.
1414 if (BB1V == BIParentV)
1415 continue;
1416
1417 // Check for saftey.
1418 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BB1V)) {
1419 // An unfolded ConstantExpr could end up getting expanded into
1420 // Instructions. Don't speculate this and another instruction at
1421 // the same time.
1422 if (HInst)
1423 return false;
1424 if (!isSafeToSpeculativelyExecute(CE))
1425 return false;
1426 if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
1427 return false;
1428 }
1429
1430 // Ok, we may insert a select for this PHI.
1431 PHIs.insert(std::make_pair(BB1V, BIParentV));
Evan Cheng4d09efd2008-06-07 08:52:29 +00001432 }
Dan Gohman3b205172012-01-05 23:58:56 +00001433
1434 // If there are no PHIs to process, bail early. This helps ensure idempotence
1435 // as well.
1436 if (PHIs.empty())
1437 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001438
Dan Gohman3b205172012-01-05 23:58:56 +00001439 // If we get here, we can hoist the instruction and if-convert.
1440 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001441
Dan Gohman3b205172012-01-05 23:58:56 +00001442 // Hoist the instruction.
1443 if (HInst)
1444 BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
Evan Cheng502a4f52008-06-12 21:15:59 +00001445
Dan Gohman3b205172012-01-05 23:58:56 +00001446 // Insert selects and rewrite the PHI operands.
Devang Pateld3a17882011-05-19 20:52:46 +00001447 IRBuilder<true, NoFolder> Builder(BI);
Dan Gohman3b205172012-01-05 23:58:56 +00001448 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
1449 Value *TrueV = PHIs[i].first;
1450 Value *FalseV = PHIs[i].second;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001451
Dan Gohman3b205172012-01-05 23:58:56 +00001452 // Create a select whose true value is the speculatively executed value and
1453 // false value is the previously determined FalseV.
1454 SelectInst *SI;
1455 if (Invert)
1456 SI = cast<SelectInst>
1457 (Builder.CreateSelect(BrCond, FalseV, TrueV,
1458 FalseV->getName() + "." + TrueV->getName()));
1459 else
1460 SI = cast<SelectInst>
1461 (Builder.CreateSelect(BrCond, TrueV, FalseV,
1462 TrueV->getName() + "." + FalseV->getName()));
1463
1464 // Make the PHI node use the select for all incoming values for "then" and
1465 // "if" blocks.
1466 for (BasicBlock::iterator I = BB2->begin();
1467 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1468 unsigned BB1I = PN->getBasicBlockIndex(BB1);
1469 unsigned BIParentI = PN->getBasicBlockIndex(BIParent);
1470 Value *BB1V = PN->getIncomingValue(BB1I);
1471 Value *BIParentV = PN->getIncomingValue(BIParentI);
1472 if (TrueV == BB1V && FalseV == BIParentV) {
1473 PN->setIncomingValue(BB1I, SI);
1474 PN->setIncomingValue(BIParentI, SI);
1475 }
1476 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001477 }
1478
Evan Cheng502a4f52008-06-12 21:15:59 +00001479 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001480 return true;
1481}
1482
Chris Lattner2e42e362005-09-20 00:43:16 +00001483/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1484/// across this block.
1485static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1486 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001487 unsigned Size = 0;
Andrew Trick6b014382012-08-29 21:46:36 +00001488
Devang Patel9200c892009-03-10 18:00:05 +00001489 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001490 if (isa<DbgInfoIntrinsic>(BBI))
1491 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001492 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001493 ++Size;
Andrew Trick6b014382012-08-29 21:46:36 +00001494
Dale Johannesen8483e542009-03-12 23:18:09 +00001495 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001496 // live outside of the current basic block.
1497 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1498 UI != E; ++UI) {
1499 Instruction *U = cast<Instruction>(*UI);
1500 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1501 }
Andrew Trick6b014382012-08-29 21:46:36 +00001502
Chris Lattner2e42e362005-09-20 00:43:16 +00001503 // Looks ok, continue checking.
1504 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001505
Chris Lattner2e42e362005-09-20 00:43:16 +00001506 return true;
1507}
1508
Chris Lattnereaba3a12005-09-19 23:49:37 +00001509/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1510/// that is defined in the same block as the branch and if any PHI entries are
1511/// constants, thread edges corresponding to that entry to be branches to their
1512/// ultimate destination.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001513static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001514 BasicBlock *BB = BI->getParent();
1515 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001516 // NOTE: we currently cannot transform this case if the PHI node is used
1517 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001518 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1519 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001520
Chris Lattnereaba3a12005-09-19 23:49:37 +00001521 // Degenerate case of a single entry PHI.
1522 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001523 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00001524 return true;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001525 }
1526
1527 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001528 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001529
Chris Lattnereaba3a12005-09-19 23:49:37 +00001530 // Okay, this is a simple enough basic block. See if any phi values are
1531 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001532 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001533 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1534 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001535
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001536 // Okay, we now know that all edges from PredBB should be revectored to
1537 // branch to RealDest.
1538 BasicBlock *PredBB = PN->getIncomingBlock(i);
1539 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trick6b014382012-08-29 21:46:36 +00001540
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001541 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling6a648b82011-06-04 09:42:04 +00001542 // Skip if the predecessor's terminator is an indirect branch.
1543 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001544
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001545 // The dest block might have PHI nodes, other predecessors and other
1546 // difficult cases. Instead of being smart about this, just insert a new
1547 // block that jumps to the destination block, effectively splitting
1548 // the edge we are about to create.
1549 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1550 RealDest->getName()+".critedge",
1551 RealDest->getParent(), RealDest);
1552 BranchInst::Create(RealDest, EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00001553
Chris Lattner6de0a282010-12-14 07:09:42 +00001554 // Update PHI nodes.
1555 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001556
1557 // BB may have instructions that are being threaded over. Clone these
1558 // instructions into EdgeBB. We know that there will be no uses of the
1559 // cloned instructions outside of EdgeBB.
1560 BasicBlock::iterator InsertPt = EdgeBB->begin();
1561 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1562 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1563 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1564 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1565 continue;
1566 }
1567 // Clone the instruction.
1568 Instruction *N = BBI->clone();
1569 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trick6b014382012-08-29 21:46:36 +00001570
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001571 // Update operands due to translation.
1572 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1573 i != e; ++i) {
1574 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1575 if (PI != TranslateMap.end())
1576 *i = PI->second;
1577 }
Andrew Trick6b014382012-08-29 21:46:36 +00001578
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001579 // Check for trivial simplification.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001580 if (Value *V = SimplifyInstruction(N, TD)) {
1581 TranslateMap[BBI] = V;
1582 delete N; // Instruction folded away, don't need actual inst
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001583 } else {
1584 // Insert the new instruction into its new home.
1585 EdgeBB->getInstList().insert(InsertPt, N);
1586 if (!BBI->use_empty())
1587 TranslateMap[BBI] = N;
1588 }
1589 }
1590
1591 // Loop over all of the edges from PredBB to BB, changing them to branch
1592 // to EdgeBB instead.
1593 TerminatorInst *PredBBTI = PredBB->getTerminator();
1594 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1595 if (PredBBTI->getSuccessor(i) == BB) {
1596 BB->removePredecessor(PredBB);
1597 PredBBTI->setSuccessor(i, EdgeBB);
1598 }
Bill Wendling6a648b82011-06-04 09:42:04 +00001599
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001600 // Recurse, simplifying any other constants.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001601 return FoldCondBranchOnPHI(BI, TD) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001602 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001603
1604 return false;
1605}
1606
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001607/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1608/// PHI node, see if we can eliminate it.
Devang Pateld3a17882011-05-19 20:52:46 +00001609static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001610 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1611 // statement", which has a very simple dominance structure. Basically, we
1612 // are trying to find the condition that is being branched on, which
1613 // subsequently causes this merge to happen. We really want control
1614 // dependence information for this check, but simplifycfg can't keep it up
1615 // to date, and this catches most of the cases we care about anyway.
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001616 BasicBlock *BB = PN->getParent();
1617 BasicBlock *IfTrue, *IfFalse;
1618 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner60d410d2010-12-14 08:01:53 +00001619 if (!IfCond ||
1620 // Don't bother if the branch will be constant folded trivially.
1621 isa<ConstantInt>(IfCond))
1622 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001623
Chris Lattner822a8792006-11-18 19:19:36 +00001624 // Okay, we found that we can merge this two-entry phi node into a select.
1625 // Doing so would require us to fold *all* two entry phi nodes in this block.
1626 // At some point this becomes non-profitable (particularly if the target
1627 // doesn't support cmov's). Only do this transformation if there are two or
1628 // fewer PHI nodes in this block.
1629 unsigned NumPhis = 0;
1630 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1631 if (NumPhis > 2)
1632 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001633
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001634 // Loop over the PHI's seeing if we can promote them all to select
1635 // instructions. While we are at it, keep track of the instructions
1636 // that need to be moved to the dominating block.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001637 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne57808b32011-04-29 18:47:38 +00001638 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1639 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trick6b014382012-08-29 21:46:36 +00001640
Chris Lattner3aff13b2010-12-14 08:46:09 +00001641 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1642 PHINode *PN = cast<PHINode>(II++);
Chris Lattner07ff3532010-12-14 07:20:29 +00001643 if (Value *V = SimplifyInstruction(PN, TD)) {
1644 PN->replaceAllUsesWith(V);
Chris Lattner3aff13b2010-12-14 08:46:09 +00001645 PN->eraseFromParent();
Chris Lattner07ff3532010-12-14 07:20:29 +00001646 continue;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001647 }
Andrew Trick6b014382012-08-29 21:46:36 +00001648
Peter Collingbournef15907f2011-04-29 18:47:31 +00001649 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1650 MaxCostVal0) ||
1651 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1652 MaxCostVal1))
Chris Lattner07ff3532010-12-14 07:20:29 +00001653 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001654 }
Andrew Trick6b014382012-08-29 21:46:36 +00001655
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001656 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner44da7ca2010-12-14 07:41:39 +00001657 // we ran out of PHIs then we simplified them all.
1658 PN = dyn_cast<PHINode>(BB->begin());
1659 if (PN == 0) return true;
Andrew Trick6b014382012-08-29 21:46:36 +00001660
Chris Lattner3aff13b2010-12-14 08:46:09 +00001661 // Don't fold i1 branches on PHIs which contain binary operators. These can
1662 // often be turned into switches and other things.
1663 if (PN->getType()->isIntegerTy(1) &&
1664 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1665 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1666 isa<BinaryOperator>(IfCond)))
1667 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001668
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001669 // If we all PHI nodes are promotable, check to make sure that all
1670 // instructions in the predecessor blocks can be promoted as well. If
1671 // not, we won't be able to get rid of the control flow, so it's not
1672 // worth promoting to select instructions.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001673 BasicBlock *DomBlock = 0;
1674 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1675 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1676 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1677 IfBlock1 = 0;
1678 } else {
1679 DomBlock = *pred_begin(IfBlock1);
1680 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001681 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001682 // This is not an aggressive instruction that we can promote.
1683 // Because of this, we won't be able to get rid of the control
1684 // flow, so the xform is not worth it.
1685 return false;
1686 }
1687 }
Andrew Trick6b014382012-08-29 21:46:36 +00001688
Chris Lattner44da7ca2010-12-14 07:41:39 +00001689 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1690 IfBlock2 = 0;
1691 } else {
1692 DomBlock = *pred_begin(IfBlock2);
1693 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001694 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001695 // This is not an aggressive instruction that we can promote.
1696 // Because of this, we won't be able to get rid of the control
1697 // flow, so the xform is not worth it.
1698 return false;
1699 }
1700 }
Andrew Trick6b014382012-08-29 21:46:36 +00001701
Chris Lattnere0b18e52010-12-14 07:23:10 +00001702 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner44da7ca2010-12-14 07:41:39 +00001703 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trick6b014382012-08-29 21:46:36 +00001704
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001705 // If we can still promote the PHI nodes after this gauntlet of tests,
1706 // do all of the PHI's now.
Chris Lattner3aff13b2010-12-14 08:46:09 +00001707 Instruction *InsertPt = DomBlock->getTerminator();
Devang Pateld3a17882011-05-19 20:52:46 +00001708 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trick6b014382012-08-29 21:46:36 +00001709
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001710 // Move all 'aggressive' instructions, which are defined in the
1711 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001712 if (IfBlock1)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001713 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001714 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001715 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001716 if (IfBlock2)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001717 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001718 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001719 IfBlock2->getTerminator());
Andrew Trick6b014382012-08-29 21:46:36 +00001720
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001721 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1722 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001723 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1724 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trick6b014382012-08-29 21:46:36 +00001725
1726 SelectInst *NV =
Devang Patelf60364d2011-05-18 18:16:44 +00001727 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner86cc4232007-02-11 01:37:51 +00001728 PN->replaceAllUsesWith(NV);
1729 NV->takeName(PN);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001730 PN->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001731 }
Andrew Trick6b014382012-08-29 21:46:36 +00001732
Chris Lattner60d410d2010-12-14 08:01:53 +00001733 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1734 // has been flattened. Change DomBlock to jump directly to our new block to
1735 // avoid other simplifycfg's kicking in on the diamond.
1736 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patelf60364d2011-05-18 18:16:44 +00001737 Builder.SetInsertPoint(OldTI);
1738 Builder.CreateBr(BB);
Chris Lattner60d410d2010-12-14 08:01:53 +00001739 OldTI->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001740 return true;
1741}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001742
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001743/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1744/// to two returning blocks, try to merge them together into one return,
1745/// introducing a select if the return values disagree.
Andrew Trick6b014382012-08-29 21:46:36 +00001746static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Patel176ec402011-05-18 21:33:11 +00001747 IRBuilder<> &Builder) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001748 assert(BI->isConditional() && "Must be a conditional branch");
1749 BasicBlock *TrueSucc = BI->getSuccessor(0);
1750 BasicBlock *FalseSucc = BI->getSuccessor(1);
1751 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1752 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trick6b014382012-08-29 21:46:36 +00001753
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001754 // Check to ensure both blocks are empty (just a return) or optionally empty
1755 // with PHI nodes. If there are other instructions, merging would cause extra
1756 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001757 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001758 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001759 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001760 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001761
Devang Patel176ec402011-05-18 21:33:11 +00001762 Builder.SetInsertPoint(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001763 // Okay, we found a branch that is going to two return nodes. If
1764 // there is no return value for this function, just change the
1765 // branch into a return.
1766 if (FalseRet->getNumOperands() == 0) {
1767 TrueSucc->removePredecessor(BI->getParent());
1768 FalseSucc->removePredecessor(BI->getParent());
Devang Patel176ec402011-05-18 21:33:11 +00001769 Builder.CreateRetVoid();
Eli Friedman080efb82008-12-16 20:54:32 +00001770 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001771 return true;
1772 }
Andrew Trick6b014382012-08-29 21:46:36 +00001773
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001774 // Otherwise, figure out what the true and false return values are
1775 // so we can insert a new select instruction.
1776 Value *TrueValue = TrueRet->getReturnValue();
1777 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trick6b014382012-08-29 21:46:36 +00001778
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001779 // Unwrap any PHI nodes in the return blocks.
1780 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1781 if (TVPN->getParent() == TrueSucc)
1782 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1783 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1784 if (FVPN->getParent() == FalseSucc)
1785 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00001786
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001787 // In order for this transformation to be safe, we must be able to
1788 // unconditionally execute both operands to the return. This is
1789 // normally the case, but we could have a potentially-trapping
1790 // constant expression that prevents this transformation from being
1791 // safe.
1792 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1793 if (TCV->canTrap())
1794 return false;
1795 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1796 if (FCV->canTrap())
1797 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001798
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001799 // Okay, we collected all the mapped values and checked them for sanity, and
1800 // defined to really do this transformation. First, update the CFG.
1801 TrueSucc->removePredecessor(BI->getParent());
1802 FalseSucc->removePredecessor(BI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00001803
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001804 // Insert select instructions where needed.
1805 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001806 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001807 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001808 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1809 } else if (isa<UndefValue>(TrueValue)) {
1810 TrueValue = FalseValue;
1811 } else {
Devang Patel176ec402011-05-18 21:33:11 +00001812 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1813 FalseValue, "retval");
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001814 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001815 }
1816
Andrew Trick6b014382012-08-29 21:46:36 +00001817 Value *RI = !TrueValue ?
Devang Patel176ec402011-05-18 21:33:11 +00001818 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1819
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001820 (void) RI;
Andrew Trick6b014382012-08-29 21:46:36 +00001821
David Greene89d6fd32010-01-05 01:26:52 +00001822 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001823 << "\n " << *BI << "NewRet = " << *RI
1824 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trick6b014382012-08-29 21:46:36 +00001825
Eli Friedman080efb82008-12-16 20:54:32 +00001826 EraseTerminatorInstAndDCECond(BI);
1827
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001828 return true;
1829}
1830
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001831/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1832/// probabilities of the branch taking each edge. Fills in the two APInt
1833/// parameters and return true, or returns false if no or invalid metadata was
1834/// found.
1835static bool ExtractBranchMetadata(BranchInst *BI,
Manman Ren062986c2012-09-15 00:39:57 +00001836 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001837 assert(BI->isConditional() &&
1838 "Looking for probabilities on unconditional branch?");
1839 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky91968482011-12-27 18:27:22 +00001840 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001841 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1842 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky91968482011-12-27 18:27:22 +00001843 if (!CITrue || !CIFalse) return false;
Manman Ren062986c2012-09-15 00:39:57 +00001844 ProbTrue = CITrue->getValue().getZExtValue();
1845 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001846 return true;
1847}
1848
Manman Renee28e0f2012-06-13 05:43:29 +00001849/// checkCSEInPredecessor - Return true if the given instruction is available
1850/// in its predecessor block. If yes, the instruction will be removed.
1851///
Benjamin Kramer23d36222012-07-13 13:25:15 +00001852static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Renee28e0f2012-06-13 05:43:29 +00001853 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1854 return false;
1855 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1856 Instruction *PBI = &*I;
1857 // Check whether Inst and PBI generate the same value.
1858 if (Inst->isIdenticalTo(PBI)) {
1859 Inst->replaceAllUsesWith(PBI);
1860 Inst->eraseFromParent();
1861 return true;
1862 }
1863 }
1864 return false;
1865}
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001866
Chris Lattnerc8fbc342011-04-11 23:24:57 +00001867/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1868/// predecessor branches to us and one of our successors, fold the block into
1869/// the predecessor and use logical operations to pick the right destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001870bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001871 BasicBlock *BB = BI->getParent();
Devang Pateld3a17882011-05-19 20:52:46 +00001872
Manman Renee28e0f2012-06-13 05:43:29 +00001873 Instruction *Cond = 0;
1874 if (BI->isConditional())
1875 Cond = dyn_cast<Instruction>(BI->getCondition());
1876 else {
1877 // For unconditional branch, check for a simple CFG pattern, where
1878 // BB has a single predecessor and BB's successor is also its predecessor's
1879 // successor. If such pattern exisits, check for CSE between BB and its
1880 // predecessor.
1881 if (BasicBlock *PB = BB->getSinglePredecessor())
1882 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1883 if (PBI->isConditional() &&
1884 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1885 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1886 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1887 I != E; ) {
1888 Instruction *Curr = I++;
1889 if (isa<CmpInst>(Curr)) {
1890 Cond = Curr;
1891 break;
1892 }
1893 // Quit if we can't remove this instruction.
1894 if (!checkCSEInPredecessor(Curr, PB))
1895 return false;
1896 }
1897 }
1898
1899 if (Cond == 0)
1900 return false;
1901 }
Andrew Trick6b014382012-08-29 21:46:36 +00001902
Owen Andersone84178a2010-07-14 19:52:16 +00001903 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1904 Cond->getParent() != BB || !Cond->hasOneUse())
1905 return false;
Devang Pateld4181942011-04-06 22:37:20 +00001906
Chris Lattner1347e872008-07-13 21:12:01 +00001907 // Only allow this if the condition is a simple instruction that can be
1908 // executed unconditionally. It must be in the same block as the branch, and
1909 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001910 BasicBlock::iterator FrontIt = BB->front();
Chris Lattner3c6e7462011-04-14 02:44:53 +00001911
Devang Pateld0a203d2009-02-04 21:39:48 +00001912 // Ignore dbg intrinsics.
Chris Lattner3c6e7462011-04-14 02:44:53 +00001913 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Nick Lewycky9d523102011-12-26 20:37:40 +00001914
Owen Andersone84178a2010-07-14 19:52:16 +00001915 // Allow a single instruction to be hoisted in addition to the compare
1916 // that feeds the branch. We later ensure that any values that _it_ uses
1917 // were also live in the predecessor, so that we don't unnecessarily create
1918 // register pressure or inhibit out-of-order execution.
1919 Instruction *BonusInst = 0;
1920 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001921 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
Dan Gohmanf0426602011-12-14 23:49:11 +00001922 isSafeToSpeculativelyExecute(FrontIt)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001923 BonusInst = &*FrontIt;
1924 ++FrontIt;
Andrew Trick6b014382012-08-29 21:46:36 +00001925
Chris Lattner3c6e7462011-04-14 02:44:53 +00001926 // Ignore dbg intrinsics.
1927 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Devang Patel60d490c2011-04-07 23:11:25 +00001928 }
1929
Owen Andersone84178a2010-07-14 19:52:16 +00001930 // Only a single bonus inst is allowed.
1931 if (&*FrontIt != Cond)
1932 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001933
Chris Lattner1347e872008-07-13 21:12:01 +00001934 // Make sure the instruction after the condition is the cond branch.
1935 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattner3c6e7462011-04-14 02:44:53 +00001936
Devang Pateld0a203d2009-02-04 21:39:48 +00001937 // Ingore dbg intrinsics.
Chris Lattner3c6e7462011-04-14 02:44:53 +00001938 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trick6b014382012-08-29 21:46:36 +00001939
Chris Lattner3c6e7462011-04-14 02:44:53 +00001940 if (&*CondIt != BI)
Chris Lattner1347e872008-07-13 21:12:01 +00001941 return false;
Chris Lattner6ff645b2009-01-19 23:03:13 +00001942
1943 // Cond is known to be a compare or binary operator. Check to make sure that
1944 // neither operand is a potentially-trapping constant expression.
1945 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1946 if (CE->canTrap())
1947 return false;
1948 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1949 if (CE->canTrap())
1950 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001951
Chris Lattner1347e872008-07-13 21:12:01 +00001952 // Finally, don't infinitely unroll conditional loops.
1953 BasicBlock *TrueDest = BI->getSuccessor(0);
Manman Renee28e0f2012-06-13 05:43:29 +00001954 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : 0;
Chris Lattner1347e872008-07-13 21:12:01 +00001955 if (TrueDest == BB || FalseDest == BB)
1956 return false;
Devang Pateld4181942011-04-06 22:37:20 +00001957
Chris Lattner1347e872008-07-13 21:12:01 +00001958 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1959 BasicBlock *PredBlock = *PI;
1960 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trick6b014382012-08-29 21:46:36 +00001961
Chris Lattner093a4382008-07-13 22:23:11 +00001962 // Check that we have two conditional branches. If there is a PHI node in
1963 // the common successor, verify that the same value flows in from both
1964 // blocks.
Manman Renee28e0f2012-06-13 05:43:29 +00001965 SmallVector<PHINode*, 4> PHIs;
1966 if (PBI == 0 || PBI->isUnconditional() ||
Andrew Trick6b014382012-08-29 21:46:36 +00001967 (BI->isConditional() &&
Manman Renee28e0f2012-06-13 05:43:29 +00001968 !SafeToMergeTerminators(BI, PBI)) ||
1969 (!BI->isConditional() &&
1970 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner1347e872008-07-13 21:12:01 +00001971 continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001972
Chris Lattner3c6e7462011-04-14 02:44:53 +00001973 // Determine if the two branches share a common destination.
Axel Naumann3780ad82012-09-17 14:20:57 +00001974 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattner3c6e7462011-04-14 02:44:53 +00001975 bool InvertPredCond = false;
Andrew Trick6b014382012-08-29 21:46:36 +00001976
Manman Renee28e0f2012-06-13 05:43:29 +00001977 if (BI->isConditional()) {
1978 if (PBI->getSuccessor(0) == TrueDest)
1979 Opc = Instruction::Or;
1980 else if (PBI->getSuccessor(1) == FalseDest)
1981 Opc = Instruction::And;
1982 else if (PBI->getSuccessor(0) == FalseDest)
1983 Opc = Instruction::And, InvertPredCond = true;
1984 else if (PBI->getSuccessor(1) == TrueDest)
1985 Opc = Instruction::Or, InvertPredCond = true;
1986 else
1987 continue;
1988 } else {
1989 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
1990 continue;
1991 }
Chris Lattner3c6e7462011-04-14 02:44:53 +00001992
Owen Andersone84178a2010-07-14 19:52:16 +00001993 // Ensure that any values used in the bonus instruction are also used
1994 // by the terminator of the predecessor. This means that those values
Andrew Trick6b014382012-08-29 21:46:36 +00001995 // must already have been resolved, so we won't be inhibiting the
Owen Andersone84178a2010-07-14 19:52:16 +00001996 // out-of-order core by speculating them earlier.
1997 if (BonusInst) {
1998 // Collect the values used by the bonus inst
1999 SmallPtrSet<Value*, 4> UsedValues;
2000 for (Instruction::op_iterator OI = BonusInst->op_begin(),
2001 OE = BonusInst->op_end(); OI != OE; ++OI) {
Nick Lewycky9d523102011-12-26 20:37:40 +00002002 Value *V = *OI;
Owen Andersone84178a2010-07-14 19:52:16 +00002003 if (!isa<Constant>(V))
2004 UsedValues.insert(V);
2005 }
2006
2007 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2008 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
Andrew Trick6b014382012-08-29 21:46:36 +00002009
Owen Andersone84178a2010-07-14 19:52:16 +00002010 // Walk up to four levels back up the use-def chain of the predecessor's
2011 // terminator to see if all those values were used. The choice of four
2012 // levels is arbitrary, to provide a compile-time-cost bound.
2013 while (!Worklist.empty()) {
2014 std::pair<Value*, unsigned> Pair = Worklist.back();
2015 Worklist.pop_back();
Andrew Trick6b014382012-08-29 21:46:36 +00002016
Owen Andersone84178a2010-07-14 19:52:16 +00002017 if (Pair.second >= 4) continue;
2018 UsedValues.erase(Pair.first);
2019 if (UsedValues.empty()) break;
Andrew Trick6b014382012-08-29 21:46:36 +00002020
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002021 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Andersone84178a2010-07-14 19:52:16 +00002022 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2023 OI != OE; ++OI)
2024 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
Andrew Trick6b014382012-08-29 21:46:36 +00002025 }
Owen Andersone84178a2010-07-14 19:52:16 +00002026 }
Andrew Trick6b014382012-08-29 21:46:36 +00002027
Owen Andersone84178a2010-07-14 19:52:16 +00002028 if (!UsedValues.empty()) return false;
2029 }
Chris Lattner36989092008-07-13 21:20:19 +00002030
David Greene89d6fd32010-01-05 01:26:52 +00002031 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trick6b014382012-08-29 21:46:36 +00002032 IRBuilder<> Builder(PBI);
Devang Pateld3a17882011-05-19 20:52:46 +00002033
Chris Lattner36989092008-07-13 21:20:19 +00002034 // If we need to invert the condition in the pred block to match, do so now.
2035 if (InvertPredCond) {
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002036 Value *NewCond = PBI->getCondition();
Andrew Trick6b014382012-08-29 21:46:36 +00002037
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002038 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2039 CmpInst *CI = cast<CmpInst>(NewCond);
2040 CI->setPredicate(CI->getInversePredicate());
2041 } else {
Andrew Trick6b014382012-08-29 21:46:36 +00002042 NewCond = Builder.CreateNot(NewCond,
Devang Pateld3a17882011-05-19 20:52:46 +00002043 PBI->getCondition()->getName()+".not");
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002044 }
Andrew Trick6b014382012-08-29 21:46:36 +00002045
Chris Lattner1347e872008-07-13 21:12:01 +00002046 PBI->setCondition(NewCond);
Nick Lewyckyc9a1aed2011-12-26 20:54:14 +00002047 PBI->swapSuccessors();
Chris Lattner1347e872008-07-13 21:12:01 +00002048 }
Andrew Trick6b014382012-08-29 21:46:36 +00002049
Owen Andersone84178a2010-07-14 19:52:16 +00002050 // If we have a bonus inst, clone it into the predecessor block.
2051 Instruction *NewBonus = 0;
2052 if (BonusInst) {
2053 NewBonus = BonusInst->clone();
2054 PredBlock->getInstList().insert(PBI, NewBonus);
2055 NewBonus->takeName(BonusInst);
2056 BonusInst->setName(BonusInst->getName()+".old");
2057 }
Andrew Trick6b014382012-08-29 21:46:36 +00002058
Chris Lattner36989092008-07-13 21:20:19 +00002059 // Clone Cond into the predecessor basic block, and or/and the
2060 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00002061 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00002062 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00002063 PredBlock->getInstList().insert(PBI, New);
2064 New->takeName(Cond);
2065 Cond->setName(New->getName()+".old");
Andrew Trick6b014382012-08-29 21:46:36 +00002066
Manman Renee28e0f2012-06-13 05:43:29 +00002067 if (BI->isConditional()) {
Andrew Trick6b014382012-08-29 21:46:36 +00002068 Instruction *NewCond =
Manman Renee28e0f2012-06-13 05:43:29 +00002069 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Pateld3a17882011-05-19 20:52:46 +00002070 New, "or.cond"));
Manman Renee28e0f2012-06-13 05:43:29 +00002071 PBI->setCondition(NewCond);
2072
Manman Ren062986c2012-09-15 00:39:57 +00002073 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2074 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2075 PredFalseWeight);
2076 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2077 SuccFalseWeight);
2078 SmallVector<uint64_t, 8> NewWeights;
2079
Manman Renee28e0f2012-06-13 05:43:29 +00002080 if (PBI->getSuccessor(0) == BB) {
Manman Ren062986c2012-09-15 00:39:57 +00002081 if (PredHasWeights && SuccHasWeights) {
2082 // PBI: br i1 %x, BB, FalseDest
2083 // BI: br i1 %y, TrueDest, FalseDest
2084 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2085 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2086 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2087 // TrueWeight for PBI * FalseWeight for BI.
2088 // We assume that total weights of a BranchInst can fit into 32 bits.
2089 // Therefore, we will not have overflow using 64-bit arithmetic.
2090 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2091 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2092 }
Manman Renee28e0f2012-06-13 05:43:29 +00002093 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2094 PBI->setSuccessor(0, TrueDest);
2095 }
2096 if (PBI->getSuccessor(1) == BB) {
Manman Ren062986c2012-09-15 00:39:57 +00002097 if (PredHasWeights && SuccHasWeights) {
2098 // PBI: br i1 %x, TrueDest, BB
2099 // BI: br i1 %y, TrueDest, FalseDest
2100 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2101 // FalseWeight for PBI * TrueWeight for BI.
2102 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2103 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2104 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2105 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2106 }
Manman Renee28e0f2012-06-13 05:43:29 +00002107 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2108 PBI->setSuccessor(1, FalseDest);
2109 }
Manman Ren062986c2012-09-15 00:39:57 +00002110 if (NewWeights.size() == 2) {
2111 // Halve the weights if any of them cannot fit in an uint32_t
2112 FitWeights(NewWeights);
2113
2114 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2115 PBI->setMetadata(LLVMContext::MD_prof,
2116 MDBuilder(BI->getContext()).
2117 createBranchWeights(MDWeights));
2118 } else
2119 PBI->setMetadata(LLVMContext::MD_prof, NULL);
Manman Renee28e0f2012-06-13 05:43:29 +00002120 } else {
2121 // Update PHI nodes in the common successors.
2122 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewyckyedb58422012-06-24 10:15:42 +00002123 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Renee28e0f2012-06-13 05:43:29 +00002124 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2125 assert(PBI_C->getType()->isIntegerTy(1));
2126 Instruction *MergedCond = 0;
2127 if (PBI->getSuccessor(0) == TrueDest) {
2128 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2129 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2130 // is false: !PBI_Cond and BI_Value
2131 Instruction *NotCond =
2132 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2133 "not.cond"));
2134 MergedCond =
2135 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2136 NotCond, New,
2137 "and.cond"));
2138 if (PBI_C->isOne())
2139 MergedCond =
2140 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2141 PBI->getCondition(), MergedCond,
2142 "or.cond"));
2143 } else {
2144 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2145 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2146 // is false: PBI_Cond and BI_Value
Andrew Trick6b014382012-08-29 21:46:36 +00002147 MergedCond =
Manman Renee28e0f2012-06-13 05:43:29 +00002148 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2149 PBI->getCondition(), New,
2150 "and.cond"));
2151 if (PBI_C->isOne()) {
2152 Instruction *NotCond =
2153 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2154 "not.cond"));
Andrew Trick6b014382012-08-29 21:46:36 +00002155 MergedCond =
Manman Renee28e0f2012-06-13 05:43:29 +00002156 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2157 NotCond, MergedCond,
2158 "or.cond"));
2159 }
2160 }
2161 // Update PHI Node.
2162 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2163 MergedCond);
2164 }
2165 // Change PBI from Conditional to Unconditional.
2166 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2167 EraseTerminatorInstAndDCECond(PBI);
2168 PBI = New_PBI;
Chris Lattner36989092008-07-13 21:20:19 +00002169 }
Devang Pateld4181942011-04-06 22:37:20 +00002170
Nick Lewycky06cc66f2011-12-27 04:31:52 +00002171 // TODO: If BB is reachable from all paths through PredBlock, then we
2172 // could replace PBI's branch probabilities with BI's.
2173
Chris Lattner3c6e7462011-04-14 02:44:53 +00002174 // Copy any debug value intrinsics into the end of PredBlock.
2175 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2176 if (isa<DbgInfoIntrinsic>(*I))
2177 I->clone()->insertBefore(PBI);
Andrew Trick6b014382012-08-29 21:46:36 +00002178
Chris Lattner117f8cf2010-12-14 05:57:30 +00002179 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00002180 }
2181 return false;
2182}
2183
Chris Lattner867661a2008-07-13 21:53:26 +00002184/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2185/// predecessor of another block, this function tries to simplify it. We know
2186/// that PBI and BI are both conditional branches, and BI is in one of the
2187/// successor blocks of PBI - PBI branches to BI.
2188static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2189 assert(PBI->isConditional() && BI->isConditional());
2190 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00002191
Chris Lattner867661a2008-07-13 21:53:26 +00002192 // If this block ends with a branch instruction, and if there is a
Andrew Trick6b014382012-08-29 21:46:36 +00002193 // predecessor that ends on a branch of the same condition, make
Chris Lattner867661a2008-07-13 21:53:26 +00002194 // this conditional branch redundant.
2195 if (PBI->getCondition() == BI->getCondition() &&
2196 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2197 // Okay, the outcome of this conditional branch is statically
2198 // knowable. If this block had a single pred, handle specially.
2199 if (BB->getSinglePredecessor()) {
2200 // Turn this into a branch on constant.
2201 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trick6b014382012-08-29 21:46:36 +00002202 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +00002203 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00002204 return true; // Nuke the branch on constant.
2205 }
Andrew Trick6b014382012-08-29 21:46:36 +00002206
Chris Lattner867661a2008-07-13 21:53:26 +00002207 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2208 // in the constant and simplify the block result. Subsequent passes of
2209 // simplifycfg will thread the block.
2210 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foadd8b4fb42011-03-30 11:19:20 +00002211 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson1d0be152009-08-13 21:58:54 +00002212 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad3ecfc862011-03-30 11:28:46 +00002213 std::distance(PB, PE),
Chris Lattner867661a2008-07-13 21:53:26 +00002214 BI->getCondition()->getName() + ".pr",
2215 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00002216 // Okay, we're going to insert the PHI node. Since PBI is not the only
2217 // predecessor, compute the PHI'd conditional value for all of the preds.
2218 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foadd8b4fb42011-03-30 11:19:20 +00002219 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif62539832010-07-12 10:59:23 +00002220 BasicBlock *P = *PI;
2221 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00002222 PBI != BI && PBI->isConditional() &&
2223 PBI->getCondition() == BI->getCondition() &&
2224 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2225 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trick6b014382012-08-29 21:46:36 +00002226 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00002227 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00002228 } else {
Gabor Greif62539832010-07-12 10:59:23 +00002229 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00002230 }
Gabor Greif62539832010-07-12 10:59:23 +00002231 }
Andrew Trick6b014382012-08-29 21:46:36 +00002232
Chris Lattner867661a2008-07-13 21:53:26 +00002233 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00002234 return true;
2235 }
2236 }
Andrew Trick6b014382012-08-29 21:46:36 +00002237
Chris Lattner867661a2008-07-13 21:53:26 +00002238 // If this is a conditional branch in an empty block, and if any
2239 // predecessors is a conditional branch to one of our destinations,
2240 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00002241 BasicBlock::iterator BBI = BB->begin();
2242 // Ignore dbg intrinsics.
2243 while (isa<DbgInfoIntrinsic>(BBI))
2244 ++BBI;
2245 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00002246 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00002247
Andrew Trick6b014382012-08-29 21:46:36 +00002248
Chris Lattner63bf29b2009-01-20 01:15:41 +00002249 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2250 if (CE->canTrap())
2251 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002252
Chris Lattnerb8245122008-07-13 22:04:41 +00002253 int PBIOp, BIOp;
2254 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2255 PBIOp = BIOp = 0;
2256 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2257 PBIOp = 0, BIOp = 1;
2258 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2259 PBIOp = 1, BIOp = 0;
2260 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2261 PBIOp = BIOp = 1;
2262 else
2263 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002264
Chris Lattnerb8245122008-07-13 22:04:41 +00002265 // Check to make sure that the other destination of this branch
2266 // isn't BB itself. If so, this is an infinite loop that will
2267 // keep getting unwound.
2268 if (PBI->getSuccessor(PBIOp) == BB)
2269 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002270
2271 // Do not perform this transformation if it would require
Chris Lattnerb8245122008-07-13 22:04:41 +00002272 // insertion of a large number of select instructions. For targets
2273 // without predication/cmovs, this is a big pessimization.
2274 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Andrew Trick6b014382012-08-29 21:46:36 +00002275
Chris Lattnerb8245122008-07-13 22:04:41 +00002276 unsigned NumPhis = 0;
2277 for (BasicBlock::iterator II = CommonDest->begin();
2278 isa<PHINode>(II); ++II, ++NumPhis)
2279 if (NumPhis > 2) // Disable this xform.
2280 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002281
Chris Lattnerb8245122008-07-13 22:04:41 +00002282 // Finally, if everything is ok, fold the branches to logical ops.
2283 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trick6b014382012-08-29 21:46:36 +00002284
David Greene89d6fd32010-01-05 01:26:52 +00002285 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00002286 << "AND: " << *BI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00002287
2288
Chris Lattner093a4382008-07-13 22:23:11 +00002289 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2290 // branch in it, where one edge (OtherDest) goes back to itself but the other
2291 // exits. We don't *know* that the program avoids the infinite loop
2292 // (even though that seems likely). If we do this xform naively, we'll end up
2293 // recursively unpeeling the loop. Since we know that (after the xform is
2294 // done) that the block *is* infinite if reached, we just make it an obviously
2295 // infinite loop with no cond branch.
2296 if (OtherDest == BB) {
2297 // Insert it at the end of the function, because it's either code,
2298 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00002299 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2300 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00002301 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2302 OtherDest = InfLoopBlock;
Andrew Trick6b014382012-08-29 21:46:36 +00002303 }
2304
David Greene89d6fd32010-01-05 01:26:52 +00002305 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Pateld3a17882011-05-19 20:52:46 +00002306
Chris Lattnerb8245122008-07-13 22:04:41 +00002307 // BI may have other predecessors. Because of this, we leave
2308 // it alone, but modify PBI.
Andrew Trick6b014382012-08-29 21:46:36 +00002309
Chris Lattnerb8245122008-07-13 22:04:41 +00002310 // Make sure we get to CommonDest on True&True directions.
2311 Value *PBICond = PBI->getCondition();
Devang Pateld3a17882011-05-19 20:52:46 +00002312 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattnerb8245122008-07-13 22:04:41 +00002313 if (PBIOp)
Devang Pateld3a17882011-05-19 20:52:46 +00002314 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2315
Chris Lattnerb8245122008-07-13 22:04:41 +00002316 Value *BICond = BI->getCondition();
2317 if (BIOp)
Devang Pateld3a17882011-05-19 20:52:46 +00002318 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2319
Chris Lattnerb8245122008-07-13 22:04:41 +00002320 // Merge the conditions.
Devang Pateld3a17882011-05-19 20:52:46 +00002321 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trick6b014382012-08-29 21:46:36 +00002322
Chris Lattnerb8245122008-07-13 22:04:41 +00002323 // Modify PBI to branch on the new condition to the new dests.
2324 PBI->setCondition(Cond);
2325 PBI->setSuccessor(0, CommonDest);
2326 PBI->setSuccessor(1, OtherDest);
Andrew Trick6b014382012-08-29 21:46:36 +00002327
Manman Ren56654032012-09-17 21:30:40 +00002328 // Update branch weight for PBI.
2329 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2330 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2331 PredFalseWeight);
2332 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2333 SuccFalseWeight);
2334 if (PredHasWeights && SuccHasWeights) {
2335 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2336 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2337 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2338 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2339 // The weight to CommonDest should be PredCommon * SuccTotal +
2340 // PredOther * SuccCommon.
2341 // The weight to OtherDest should be PredOther * SuccOther.
2342 SmallVector<uint64_t, 2> NewWeights;
2343 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2344 PredOther * SuccCommon);
2345 NewWeights.push_back(PredOther * SuccOther);
2346 // Halve the weights if any of them cannot fit in an uint32_t
2347 FitWeights(NewWeights);
2348
2349 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2350 PBI->setMetadata(LLVMContext::MD_prof,
2351 MDBuilder(BI->getContext()).
2352 createBranchWeights(MDWeights));
2353 }
2354
Chris Lattnerb8245122008-07-13 22:04:41 +00002355 // OtherDest may have phi nodes. If so, add an entry from PBI's
2356 // block that are identical to the entries for BI's block.
Chris Lattner6de0a282010-12-14 07:09:42 +00002357 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trick6b014382012-08-29 21:46:36 +00002358
Chris Lattnerb8245122008-07-13 22:04:41 +00002359 // We know that the CommonDest already had an edge from PBI to
2360 // it. If it has PHIs though, the PHIs may have different
2361 // entries for BB and PBI's BB. If so, insert a select to make
2362 // them agree.
Chris Lattner6de0a282010-12-14 07:09:42 +00002363 PHINode *PN;
Chris Lattnerb8245122008-07-13 22:04:41 +00002364 for (BasicBlock::iterator II = CommonDest->begin();
2365 (PN = dyn_cast<PHINode>(II)); ++II) {
2366 Value *BIV = PN->getIncomingValueForBlock(BB);
2367 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2368 Value *PBIV = PN->getIncomingValue(PBBIdx);
2369 if (BIV != PBIV) {
2370 // Insert a select in PBI to pick the right value.
Devang Pateld3a17882011-05-19 20:52:46 +00002371 Value *NV = cast<SelectInst>
2372 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattnerb8245122008-07-13 22:04:41 +00002373 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00002374 }
2375 }
Andrew Trick6b014382012-08-29 21:46:36 +00002376
David Greene89d6fd32010-01-05 01:26:52 +00002377 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2378 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00002379
Chris Lattnerb8245122008-07-13 22:04:41 +00002380 // This basic block is probably dead. We know it has at least
2381 // one fewer predecessor.
2382 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00002383}
2384
Frits van Bommel65fdded2011-01-11 12:52:11 +00002385// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2386// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2387// Takes care of updating the successors and removing the old terminator.
2388// Also makes sure not to introduce new successors by assuming that edges to
2389// non-successor TrueBBs and FalseBBs aren't reachable.
2390static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Renb11cbe62012-09-17 22:28:55 +00002391 BasicBlock *TrueBB, BasicBlock *FalseBB,
2392 uint32_t TrueWeight,
2393 uint32_t FalseWeight){
Frits van Bommel65fdded2011-01-11 12:52:11 +00002394 // Remove any superfluous successor edges from the CFG.
2395 // First, figure out which successors to preserve.
2396 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2397 // successor.
2398 BasicBlock *KeepEdge1 = TrueBB;
2399 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
2400
2401 // Then remove the rest.
2402 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2403 BasicBlock *Succ = OldTerm->getSuccessor(I);
2404 // Make sure only to keep exactly one copy of each edge.
2405 if (Succ == KeepEdge1)
2406 KeepEdge1 = 0;
2407 else if (Succ == KeepEdge2)
2408 KeepEdge2 = 0;
2409 else
2410 Succ->removePredecessor(OldTerm->getParent());
2411 }
2412
Devang Pateld3372b82011-05-18 18:43:31 +00002413 IRBuilder<> Builder(OldTerm);
2414 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2415
Frits van Bommel65fdded2011-01-11 12:52:11 +00002416 // Insert an appropriate new terminator.
2417 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
2418 if (TrueBB == FalseBB)
2419 // We were only looking for one successor, and it was present.
2420 // Create an unconditional branch to it.
Devang Pateld3372b82011-05-18 18:43:31 +00002421 Builder.CreateBr(TrueBB);
Manman Renb11cbe62012-09-17 22:28:55 +00002422 else {
Frits van Bommel65fdded2011-01-11 12:52:11 +00002423 // We found both of the successors we were looking for.
2424 // Create a conditional branch sharing the condition of the select.
Manman Renb11cbe62012-09-17 22:28:55 +00002425 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2426 if (TrueWeight != FalseWeight)
2427 NewBI->setMetadata(LLVMContext::MD_prof,
2428 MDBuilder(OldTerm->getContext()).
2429 createBranchWeights(TrueWeight, FalseWeight));
2430 }
Frits van Bommel65fdded2011-01-11 12:52:11 +00002431 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2432 // Neither of the selected blocks were successors, so this
2433 // terminator must be unreachable.
2434 new UnreachableInst(OldTerm->getContext(), OldTerm);
2435 } else {
2436 // One of the selected values was a successor, but the other wasn't.
2437 // Insert an unconditional branch to the one that was found;
2438 // the edge to the one that wasn't must be unreachable.
2439 if (KeepEdge1 == 0)
2440 // Only TrueBB was found.
Devang Pateld3372b82011-05-18 18:43:31 +00002441 Builder.CreateBr(TrueBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002442 else
2443 // Only FalseBB was found.
Devang Pateld3372b82011-05-18 18:43:31 +00002444 Builder.CreateBr(FalseBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002445 }
2446
2447 EraseTerminatorInstAndDCECond(OldTerm);
2448 return true;
2449}
2450
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002451// SimplifySwitchOnSelect - Replaces
2452// (switch (select cond, X, Y)) on constant X, Y
2453// with a branch - conditional if X and Y lead to distinct BBs,
2454// unconditional otherwise.
2455static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2456 // Check for constant integer values in the select.
2457 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2458 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2459 if (!TrueVal || !FalseVal)
2460 return false;
2461
2462 // Find the relevant condition and destinations.
2463 Value *Condition = Select->getCondition();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002464 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2465 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002466
Manman Renb11cbe62012-09-17 22:28:55 +00002467 // Get weight for TrueBB and FalseBB.
2468 uint32_t TrueWeight = 0, FalseWeight = 0;
2469 SmallVector<uint64_t, 8> Weights;
2470 bool HasWeights = HasBranchWeights(SI);
2471 if (HasWeights) {
2472 GetBranchWeights(SI, Weights);
2473 if (Weights.size() == 1 + SI->getNumCases()) {
2474 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2475 getSuccessorIndex()];
2476 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2477 getSuccessorIndex()];
2478 }
2479 }
2480
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002481 // Perform the actual simplification.
Manman Renb11cbe62012-09-17 22:28:55 +00002482 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2483 TrueWeight, FalseWeight);
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002484}
2485
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002486// SimplifyIndirectBrOnSelect - Replaces
2487// (indirectbr (select cond, blockaddress(@fn, BlockA),
2488// blockaddress(@fn, BlockB)))
2489// with
2490// (br cond, BlockA, BlockB).
2491static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2492 // Check that both operands of the select are block addresses.
2493 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2494 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2495 if (!TBA || !FBA)
2496 return false;
2497
2498 // Extract the actual blocks.
2499 BasicBlock *TrueBB = TBA->getBasicBlock();
2500 BasicBlock *FalseBB = FBA->getBasicBlock();
2501
Frits van Bommel65fdded2011-01-11 12:52:11 +00002502 // Perform the actual simplification.
Manman Renb11cbe62012-09-17 22:28:55 +00002503 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2504 0, 0);
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002505}
2506
Chris Lattner61c77442010-12-13 03:18:54 +00002507/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2508/// instruction (a seteq/setne with a constant) as the only instruction in a
2509/// block that ends with an uncond branch. We are looking for a very specific
2510/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2511/// this case, we merge the first two "or's of icmp" into a switch, but then the
2512/// default value goes to an uncond block with a seteq in it, we get something
2513/// like:
2514///
2515/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2516/// DEFAULT:
2517/// %tmp = icmp eq i8 %A, 92
2518/// br label %end
2519/// end:
2520/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trick6b014382012-08-29 21:46:36 +00002521///
Chris Lattner61c77442010-12-13 03:18:54 +00002522/// We prefer to split the edge to 'end' so that there is a true/false entry to
2523/// the PHI, merging the third icmp into the switch.
Chris Lattner302ba6f2010-12-14 06:17:25 +00002524static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
Devang Patela23812c2011-05-18 18:28:48 +00002525 const TargetData *TD,
2526 IRBuilder<> &Builder) {
Chris Lattner61c77442010-12-13 03:18:54 +00002527 BasicBlock *BB = ICI->getParent();
Devang Patela23812c2011-05-18 18:28:48 +00002528
Chris Lattner61c77442010-12-13 03:18:54 +00002529 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2530 // complex.
2531 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2532
2533 Value *V = ICI->getOperand(0);
2534 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trick6b014382012-08-29 21:46:36 +00002535
Chris Lattner61c77442010-12-13 03:18:54 +00002536 // The pattern we're looking for is where our only predecessor is a switch on
2537 // 'V' and this block is the default case for the switch. In this case we can
2538 // fold the compared value into the switch to simplify things.
2539 BasicBlock *Pred = BB->getSinglePredecessor();
2540 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002541
Chris Lattner61c77442010-12-13 03:18:54 +00002542 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2543 if (SI->getCondition() != V)
2544 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002545
Chris Lattner61c77442010-12-13 03:18:54 +00002546 // If BB is reachable on a non-default case, then we simply know the value of
2547 // V in this block. Substitute it and constant fold the icmp instruction
2548 // away.
2549 if (SI->getDefaultDest() != BB) {
2550 ConstantInt *VVal = SI->findCaseDest(BB);
2551 assert(VVal && "Should have a unique destination value");
2552 ICI->setOperand(0, VVal);
Andrew Trick6b014382012-08-29 21:46:36 +00002553
Chris Lattner302ba6f2010-12-14 06:17:25 +00002554 if (Value *V = SimplifyInstruction(ICI, TD)) {
2555 ICI->replaceAllUsesWith(V);
Chris Lattner61c77442010-12-13 03:18:54 +00002556 ICI->eraseFromParent();
2557 }
2558 // BB is now empty, so it is likely to simplify away.
2559 return SimplifyCFG(BB) | true;
2560 }
Andrew Trick6b014382012-08-29 21:46:36 +00002561
Chris Lattnerabf70672010-12-13 03:43:57 +00002562 // Ok, the block is reachable from the default dest. If the constant we're
2563 // comparing exists in one of the other edges, then we can constant fold ICI
2564 // and zap it.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002565 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattnerabf70672010-12-13 03:43:57 +00002566 Value *V;
2567 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2568 V = ConstantInt::getFalse(BB->getContext());
2569 else
2570 V = ConstantInt::getTrue(BB->getContext());
Andrew Trick6b014382012-08-29 21:46:36 +00002571
Chris Lattnerabf70672010-12-13 03:43:57 +00002572 ICI->replaceAllUsesWith(V);
2573 ICI->eraseFromParent();
2574 // BB is now empty, so it is likely to simplify away.
2575 return SimplifyCFG(BB) | true;
2576 }
Andrew Trick6b014382012-08-29 21:46:36 +00002577
Chris Lattner61c77442010-12-13 03:18:54 +00002578 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2579 // the block.
2580 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2581 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
2582 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
2583 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2584 return false;
2585
2586 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2587 // true in the PHI.
2588 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2589 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2590
2591 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2592 std::swap(DefaultCst, NewCst);
2593
2594 // Replace ICI (which is used by the PHI for the default value) with true or
2595 // false depending on if it is EQ or NE.
2596 ICI->replaceAllUsesWith(DefaultCst);
2597 ICI->eraseFromParent();
2598
2599 // Okay, the switch goes to this block on a default value. Add an edge from
2600 // the switch to the merge point on the compared value.
2601 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2602 BB->getParent(), BB);
Manman Renb0102772012-09-17 23:07:43 +00002603 SmallVector<uint64_t, 8> Weights;
2604 bool HasWeights = HasBranchWeights(SI);
2605 if (HasWeights) {
2606 GetBranchWeights(SI, Weights);
2607 if (Weights.size() == 1 + SI->getNumCases()) {
2608 // Split weight for default case to case for "Cst".
2609 Weights[0] = (Weights[0]+1) >> 1;
2610 Weights.push_back(Weights[0]);
2611
2612 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2613 SI->setMetadata(LLVMContext::MD_prof,
2614 MDBuilder(SI->getContext()).
2615 createBranchWeights(MDWeights));
2616 }
2617 }
Chris Lattner61c77442010-12-13 03:18:54 +00002618 SI->addCase(Cst, NewBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002619
Chris Lattner61c77442010-12-13 03:18:54 +00002620 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patela23812c2011-05-18 18:28:48 +00002621 Builder.SetInsertPoint(NewBB);
2622 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2623 Builder.CreateBr(SuccBlock);
Chris Lattner61c77442010-12-13 03:18:54 +00002624 PHIUse->addIncoming(NewCst, NewBB);
2625 return true;
2626}
2627
Chris Lattner97fdb892010-12-13 05:03:41 +00002628/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2629/// Check to see if it is branching on an or/and chain of icmp instructions, and
2630/// fold it into a switch instruction if so.
Devang Patel02dd5412011-05-18 23:18:47 +00002631static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD,
2632 IRBuilder<> &Builder) {
Chris Lattner97fdb892010-12-13 05:03:41 +00002633 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2634 if (Cond == 0) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002635
2636
Chris Lattner97fdb892010-12-13 05:03:41 +00002637 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2638 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2639 // 'setne's and'ed together, collect them.
2640 Value *CompVal = 0;
2641 std::vector<ConstantInt*> Values;
2642 bool TrueWhenEqual = true;
2643 Value *ExtraCase = 0;
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002644 unsigned UsedICmps = 0;
Andrew Trick6b014382012-08-29 21:46:36 +00002645
Chris Lattner97fdb892010-12-13 05:03:41 +00002646 if (Cond->getOpcode() == Instruction::Or) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002647 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
2648 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00002649 } else if (Cond->getOpcode() == Instruction::And) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002650 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
2651 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00002652 TrueWhenEqual = false;
2653 }
Andrew Trick6b014382012-08-29 21:46:36 +00002654
Chris Lattner97fdb892010-12-13 05:03:41 +00002655 // If we didn't have a multiply compared value, fail.
2656 if (CompVal == 0) return false;
2657
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002658 // Avoid turning single icmps into a switch.
2659 if (UsedICmps <= 1)
2660 return false;
2661
Chris Lattner97fdb892010-12-13 05:03:41 +00002662 // There might be duplicate constants in the list, which the switch
2663 // instruction can't handle, remove them now.
2664 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2665 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trick6b014382012-08-29 21:46:36 +00002666
Chris Lattner97fdb892010-12-13 05:03:41 +00002667 // If Extra was used, we require at least two switch values to do the
2668 // transformation. A switch with one value is just an cond branch.
2669 if (ExtraCase && Values.size() < 2) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002670
Andrew Trickb1b97832012-08-29 21:46:38 +00002671 // TODO: Preserve branch weight metadata, similarly to how
2672 // FoldValueComparisonIntoPredecessors preserves it.
2673
Chris Lattner97fdb892010-12-13 05:03:41 +00002674 // Figure out which block is which destination.
2675 BasicBlock *DefaultBB = BI->getSuccessor(1);
2676 BasicBlock *EdgeBB = BI->getSuccessor(0);
2677 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002678
Chris Lattner97fdb892010-12-13 05:03:41 +00002679 BasicBlock *BB = BI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002680
Chris Lattner302ba6f2010-12-14 06:17:25 +00002681 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner117f8cf2010-12-14 05:57:30 +00002682 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trick6b014382012-08-29 21:46:36 +00002683
Chris Lattner97fdb892010-12-13 05:03:41 +00002684 // If there are any extra values that couldn't be folded into the switch
2685 // then we evaluate them with an explicit branch first. Split the block
2686 // right before the condbr to handle it.
2687 if (ExtraCase) {
2688 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2689 // Remove the uncond branch added to the old block.
2690 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel02dd5412011-05-18 23:18:47 +00002691 Builder.SetInsertPoint(OldTI);
2692
Chris Lattner117f8cf2010-12-14 05:57:30 +00002693 if (TrueWhenEqual)
Devang Patel02dd5412011-05-18 23:18:47 +00002694 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner117f8cf2010-12-14 05:57:30 +00002695 else
Devang Patel02dd5412011-05-18 23:18:47 +00002696 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002697
Chris Lattner97fdb892010-12-13 05:03:41 +00002698 OldTI->eraseFromParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002699
Chris Lattner97bd89e2010-12-13 05:34:18 +00002700 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2701 // for the edge we just added.
Chris Lattner6de0a282010-12-14 07:09:42 +00002702 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002703
Chris Lattner302ba6f2010-12-14 06:17:25 +00002704 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2705 << "\nEXTRABB = " << *BB);
Chris Lattner97fdb892010-12-13 05:03:41 +00002706 BB = NewBB;
2707 }
Devang Patel02dd5412011-05-18 23:18:47 +00002708
2709 Builder.SetInsertPoint(BI);
Chris Lattner97fdb892010-12-13 05:03:41 +00002710 // Convert pointer to int before we switch.
2711 if (CompVal->getType()->isPointerTy()) {
2712 assert(TD && "Cannot switch on pointer without TargetData");
Devang Patel02dd5412011-05-18 23:18:47 +00002713 CompVal = Builder.CreatePtrToInt(CompVal,
2714 TD->getIntPtrType(CompVal->getContext()),
2715 "magicptr");
Chris Lattner97fdb892010-12-13 05:03:41 +00002716 }
Andrew Trick6b014382012-08-29 21:46:36 +00002717
Chris Lattner97fdb892010-12-13 05:03:41 +00002718 // Create the new switch instruction now.
Devang Patel02dd5412011-05-18 23:18:47 +00002719 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Pateld80e8ed2011-05-17 23:29:05 +00002720
Chris Lattner97fdb892010-12-13 05:03:41 +00002721 // Add all of the 'cases' to the switch instruction.
2722 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2723 New->addCase(Values[i], EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002724
Chris Lattner97fdb892010-12-13 05:03:41 +00002725 // We added edges from PI to the EdgeBB. As such, if there were any
2726 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2727 // the number of edges added.
2728 for (BasicBlock::iterator BBI = EdgeBB->begin();
2729 isa<PHINode>(BBI); ++BBI) {
2730 PHINode *PN = cast<PHINode>(BBI);
2731 Value *InVal = PN->getIncomingValueForBlock(BB);
2732 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2733 PN->addIncoming(InVal, BB);
2734 }
Andrew Trick6b014382012-08-29 21:46:36 +00002735
Chris Lattner97fdb892010-12-13 05:03:41 +00002736 // Erase the old branch instruction.
2737 EraseTerminatorInstAndDCECond(BI);
Andrew Trick6b014382012-08-29 21:46:36 +00002738
Chris Lattner302ba6f2010-12-14 06:17:25 +00002739 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattner97fdb892010-12-13 05:03:41 +00002740 return true;
2741}
2742
Duncan Sandsad99ef82011-09-05 12:57:57 +00002743bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2744 // If this is a trivial landing pad that just continues unwinding the caught
2745 // exception then zap the landing pad, turning its invokes into calls.
2746 BasicBlock *BB = RI->getParent();
2747 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2748 if (RI->getValue() != LPInst)
2749 // Not a landing pad, or the resume is not unwinding the exception that
2750 // caused control to branch here.
2751 return false;
2752
2753 // Check that there are no other instructions except for debug intrinsics.
2754 BasicBlock::iterator I = LPInst, E = RI;
2755 while (++I != E)
2756 if (!isa<DbgInfoIntrinsic>(I))
2757 return false;
2758
2759 // Turn all invokes that unwind here into calls and delete the basic block.
2760 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2761 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2762 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2763 // Insert a call instruction before the invoke.
2764 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2765 Call->takeName(II);
2766 Call->setCallingConv(II->getCallingConv());
2767 Call->setAttributes(II->getAttributes());
2768 Call->setDebugLoc(II->getDebugLoc());
2769
2770 // Anything that used the value produced by the invoke instruction now uses
2771 // the value produced by the call instruction. Note that we do this even
2772 // for void functions and calls with no uses so that the callgraph edge is
2773 // updated.
2774 II->replaceAllUsesWith(Call);
2775 BB->removePredecessor(II->getParent());
2776
2777 // Insert a branch to the normal destination right before the invoke.
2778 BranchInst::Create(II->getNormalDest(), II);
2779
2780 // Finally, delete the invoke instruction!
2781 II->eraseFromParent();
2782 }
2783
2784 // The landingpad is now unreachable. Zap it.
2785 BB->eraseFromParent();
2786 return true;
2787}
2788
Devang Patel176ec402011-05-18 21:33:11 +00002789bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00002790 BasicBlock *BB = RI->getParent();
2791 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002792
Chris Lattner3d512132010-12-13 06:25:44 +00002793 // Find predecessors that end with branches.
2794 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2795 SmallVector<BranchInst*, 8> CondBranchPreds;
2796 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2797 BasicBlock *P = *PI;
2798 TerminatorInst *PTI = P->getTerminator();
2799 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2800 if (BI->isUnconditional())
2801 UncondBranchPreds.push_back(P);
2802 else
2803 CondBranchPreds.push_back(BI);
2804 }
2805 }
Andrew Trick6b014382012-08-29 21:46:36 +00002806
Chris Lattner3d512132010-12-13 06:25:44 +00002807 // If we found some, do the transformation!
Evan Chengc3f507f2011-01-29 04:46:23 +00002808 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner3d512132010-12-13 06:25:44 +00002809 while (!UncondBranchPreds.empty()) {
2810 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2811 DEBUG(dbgs() << "FOLDING: " << *BB
2812 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengc3f507f2011-01-29 04:46:23 +00002813 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner3d512132010-12-13 06:25:44 +00002814 }
Andrew Trick6b014382012-08-29 21:46:36 +00002815
Chris Lattner3d512132010-12-13 06:25:44 +00002816 // If we eliminated all predecessors of the block, delete the block now.
2817 if (pred_begin(BB) == pred_end(BB))
2818 // We know there are no successors, so just nuke the block.
2819 BB->eraseFromParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002820
Chris Lattner3d512132010-12-13 06:25:44 +00002821 return true;
2822 }
Andrew Trick6b014382012-08-29 21:46:36 +00002823
Chris Lattner3d512132010-12-13 06:25:44 +00002824 // Check out all of the conditional branches going to this return
2825 // instruction. If any of them just select between returns, change the
2826 // branch itself into a select/return pair.
2827 while (!CondBranchPreds.empty()) {
2828 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trick6b014382012-08-29 21:46:36 +00002829
Chris Lattner3d512132010-12-13 06:25:44 +00002830 // Check to see if the non-BB successor is also a return block.
2831 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2832 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Patel176ec402011-05-18 21:33:11 +00002833 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002834 return true;
2835 }
2836 return false;
2837}
2838
Chris Lattner3d512132010-12-13 06:25:44 +00002839bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2840 BasicBlock *BB = UI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002841
Chris Lattner3d512132010-12-13 06:25:44 +00002842 bool Changed = false;
Andrew Trick6b014382012-08-29 21:46:36 +00002843
Chris Lattner3d512132010-12-13 06:25:44 +00002844 // If there are any instructions immediately before the unreachable that can
2845 // be removed, do so.
2846 while (UI != BB->begin()) {
2847 BasicBlock::iterator BBI = UI;
2848 --BBI;
Eli Friedman81763882011-08-15 23:59:28 +00002849 // Do not delete instructions that can have side effects which might cause
2850 // the unreachable to not be reachable; specifically, calls and volatile
2851 // operations may have this effect.
Chris Lattner3d512132010-12-13 06:25:44 +00002852 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman81763882011-08-15 23:59:28 +00002853
2854 if (BBI->mayHaveSideEffects()) {
2855 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2856 if (SI->isVolatile())
2857 break;
2858 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2859 if (LI->isVolatile())
2860 break;
2861 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2862 if (RMWI->isVolatile())
2863 break;
2864 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2865 if (CXI->isVolatile())
2866 break;
2867 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2868 !isa<LandingPadInst>(BBI)) {
Chris Lattner3d512132010-12-13 06:25:44 +00002869 break;
Eli Friedman81763882011-08-15 23:59:28 +00002870 }
Bill Wendling23b49ba2011-08-16 20:41:17 +00002871 // Note that deleting LandingPad's here is in fact okay, although it
2872 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2873 // all the predecessors of this block will be the unwind edges of Invokes,
2874 // and we can therefore guarantee this block will be erased.
Eli Friedman81763882011-08-15 23:59:28 +00002875 }
2876
Eli Friedman2adc5b62011-03-09 00:48:33 +00002877 // Delete this instruction (any uses are guaranteed to be dead)
2878 if (!BBI->use_empty())
2879 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattner302ba6f2010-12-14 06:17:25 +00002880 BBI->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002881 Changed = true;
2882 }
Andrew Trick6b014382012-08-29 21:46:36 +00002883
Chris Lattner3d512132010-12-13 06:25:44 +00002884 // If the unreachable instruction is the first in the block, take a gander
2885 // at all of the predecessors of this instruction, and simplify them.
2886 if (&BB->front() != UI) return Changed;
Andrew Trick6b014382012-08-29 21:46:36 +00002887
Chris Lattner3d512132010-12-13 06:25:44 +00002888 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2889 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2890 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel1aa89a22011-05-19 00:09:21 +00002891 IRBuilder<> Builder(TI);
Chris Lattner3d512132010-12-13 06:25:44 +00002892 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2893 if (BI->isUnconditional()) {
2894 if (BI->getSuccessor(0) == BB) {
2895 new UnreachableInst(TI->getContext(), TI);
2896 TI->eraseFromParent();
2897 Changed = true;
2898 }
2899 } else {
2900 if (BI->getSuccessor(0) == BB) {
Devang Patel1aa89a22011-05-19 00:09:21 +00002901 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner3d512132010-12-13 06:25:44 +00002902 EraseTerminatorInstAndDCECond(BI);
2903 } else if (BI->getSuccessor(1) == BB) {
Devang Patel1aa89a22011-05-19 00:09:21 +00002904 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner3d512132010-12-13 06:25:44 +00002905 EraseTerminatorInstAndDCECond(BI);
2906 Changed = true;
2907 }
2908 }
2909 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002910 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002911 i != e; ++i)
2912 if (i.getCaseSuccessor() == BB) {
Chris Lattner3d512132010-12-13 06:25:44 +00002913 BB->removePredecessor(SI->getParent());
2914 SI->removeCase(i);
2915 --i; --e;
2916 Changed = true;
2917 }
2918 // If the default value is unreachable, figure out the most popular
2919 // destination and make it the default.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002920 if (SI->getDefaultDest() == BB) {
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002921 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002922 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002923 i != e; ++i) {
Nick Lewycky9d523102011-12-26 20:37:40 +00002924 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002925 Popularity[i.getCaseSuccessor()];
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002926 if (entry.first == 0) {
2927 entry.first = 1;
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002928 entry.second = i.getCaseIndex();
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002929 } else {
2930 entry.first++;
2931 }
2932 }
2933
Chris Lattner3d512132010-12-13 06:25:44 +00002934 // Find the most popular block.
2935 unsigned MaxPop = 0;
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002936 unsigned MaxIndex = 0;
Chris Lattner3d512132010-12-13 06:25:44 +00002937 BasicBlock *MaxBlock = 0;
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002938 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner3d512132010-12-13 06:25:44 +00002939 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trick6b014382012-08-29 21:46:36 +00002940 if (I->second.first > MaxPop ||
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002941 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
2942 MaxPop = I->second.first;
2943 MaxIndex = I->second.second;
Chris Lattner3d512132010-12-13 06:25:44 +00002944 MaxBlock = I->first;
2945 }
2946 }
2947 if (MaxBlock) {
2948 // Make this the new default, allowing us to delete any explicit
2949 // edges to it.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002950 SI->setDefaultDest(MaxBlock);
Chris Lattner3d512132010-12-13 06:25:44 +00002951 Changed = true;
Andrew Trick6b014382012-08-29 21:46:36 +00002952
Chris Lattner3d512132010-12-13 06:25:44 +00002953 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2954 // it.
2955 if (isa<PHINode>(MaxBlock->begin()))
2956 for (unsigned i = 0; i != MaxPop-1; ++i)
2957 MaxBlock->removePredecessor(SI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00002958
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002959 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002960 i != e; ++i)
2961 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner3d512132010-12-13 06:25:44 +00002962 SI->removeCase(i);
2963 --i; --e;
2964 }
2965 }
2966 }
2967 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2968 if (II->getUnwindDest() == BB) {
2969 // Convert the invoke to a call instruction. This would be a good
2970 // place to note that the call does not throw though.
Devang Patel1aa89a22011-05-19 00:09:21 +00002971 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner3d512132010-12-13 06:25:44 +00002972 II->removeFromParent(); // Take out of symbol table
Andrew Trick6b014382012-08-29 21:46:36 +00002973
Chris Lattner3d512132010-12-13 06:25:44 +00002974 // Insert the call now...
2975 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel1aa89a22011-05-19 00:09:21 +00002976 Builder.SetInsertPoint(BI);
2977 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foada3efbb12011-07-15 08:37:34 +00002978 Args, II->getName());
Chris Lattner3d512132010-12-13 06:25:44 +00002979 CI->setCallingConv(II->getCallingConv());
2980 CI->setAttributes(II->getAttributes());
2981 // If the invoke produced a value, the call does now instead.
2982 II->replaceAllUsesWith(CI);
2983 delete II;
2984 Changed = true;
2985 }
2986 }
2987 }
Andrew Trick6b014382012-08-29 21:46:36 +00002988
Chris Lattner3d512132010-12-13 06:25:44 +00002989 // If this block is now dead, remove it.
2990 if (pred_begin(BB) == pred_end(BB) &&
2991 BB != &BB->getParent()->getEntryBlock()) {
2992 // We know there are no successors, so just nuke the block.
2993 BB->eraseFromParent();
2994 return true;
2995 }
2996
2997 return Changed;
2998}
2999
Benjamin Kramer56442df2011-02-02 15:56:22 +00003000/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3001/// integer range comparison into a sub, an icmp and a branch.
Devang Patel007349d2011-05-18 20:35:38 +00003002static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003003 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramer56442df2011-02-02 15:56:22 +00003004
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003005 // Make sure all cases point to the same destination and gather the values.
3006 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003007 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003008 Cases.push_back(I.getCaseValue());
3009 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003010 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003011 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003012 return false;
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003013 Cases.push_back(I.getCaseValue());
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003014 }
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003015 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003016
3017 // Sort the case values, then check if they form a range we can transform.
3018 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3019 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3020 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3021 return false;
3022 }
3023
3024 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003025 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramer56442df2011-02-02 15:56:22 +00003026
Benjamin Kramer33828bc2011-02-07 22:37:28 +00003027 Value *Sub = SI->getCondition();
3028 if (!Offset->isNullValue())
Devang Patel1f5812b2011-05-19 00:13:33 +00003029 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3030 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren222d6192012-09-18 00:47:33 +00003031 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003032 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramer56442df2011-02-02 15:56:22 +00003033
Manman Ren222d6192012-09-18 00:47:33 +00003034 // Update weight for the newly-created conditional branch.
3035 SmallVector<uint64_t, 8> Weights;
3036 bool HasWeights = HasBranchWeights(SI);
3037 if (HasWeights) {
3038 GetBranchWeights(SI, Weights);
3039 if (Weights.size() == 1 + SI->getNumCases()) {
3040 // Combine all weights for the cases to be the true weight of NewBI.
3041 // We assume that the sum of all weights for a Terminator can fit into 32
3042 // bits.
3043 uint32_t NewTrueWeight = 0;
3044 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3045 NewTrueWeight += (uint32_t)Weights[I];
3046 NewBI->setMetadata(LLVMContext::MD_prof,
3047 MDBuilder(SI->getContext()).
3048 createBranchWeights(NewTrueWeight,
3049 (uint32_t)Weights[0]));
3050 }
3051 }
3052
Benjamin Kramer56442df2011-02-02 15:56:22 +00003053 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003054 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramer56442df2011-02-02 15:56:22 +00003055 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003056 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramer56442df2011-02-02 15:56:22 +00003057 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3058 }
3059 SI->eraseFromParent();
3060
3061 return true;
3062}
Chris Lattner3d512132010-12-13 06:25:44 +00003063
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003064/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3065/// and use it to remove dead cases.
3066static bool EliminateDeadSwitchCases(SwitchInst *SI) {
3067 Value *Cond = SI->getCondition();
3068 unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
3069 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00003070 ComputeMaskedBits(Cond, KnownZero, KnownOne);
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003071
3072 // Gather dead cases.
3073 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003074 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003075 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3076 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3077 DeadCases.push_back(I.getCaseValue());
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003078 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003079 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003080 }
3081 }
3082
Manman Ren222d6192012-09-18 00:47:33 +00003083 SmallVector<uint64_t, 8> Weights;
3084 bool HasWeight = HasBranchWeights(SI);
3085 if (HasWeight) {
3086 GetBranchWeights(SI, Weights);
3087 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3088 }
3089
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003090 // Remove dead cases from the switch.
3091 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003092 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003093 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003094 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren222d6192012-09-18 00:47:33 +00003095 if (HasWeight) {
3096 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3097 Weights.pop_back();
3098 }
3099
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003100 // Prune unused values from PHI nodes.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003101 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003102 SI->removeCase(Case);
3103 }
Manman Ren222d6192012-09-18 00:47:33 +00003104 if (HasWeight) {
3105 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3106 SI->setMetadata(LLVMContext::MD_prof,
3107 MDBuilder(SI->getParent()->getContext()).
3108 createBranchWeights(MDWeights));
3109 }
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003110
3111 return !DeadCases.empty();
3112}
3113
Hans Wennborg448da512011-06-18 10:28:47 +00003114/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3115/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3116/// by an unconditional branch), look at the phi node for BB in the successor
3117/// block and see if the incoming value is equal to CaseValue. If so, return
3118/// the phi node, and set PhiIndex to BB's index in the phi node.
3119static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3120 BasicBlock *BB,
3121 int *PhiIndex) {
3122 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3123 return NULL; // BB must be empty to be a candidate for simplification.
3124 if (!BB->getSinglePredecessor())
3125 return NULL; // BB must be dominated by the switch.
3126
3127 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3128 if (!Branch || !Branch->isUnconditional())
3129 return NULL; // Terminator must be unconditional branch.
3130
3131 BasicBlock *Succ = Branch->getSuccessor(0);
3132
3133 BasicBlock::iterator I = Succ->begin();
3134 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3135 int Idx = PHI->getBasicBlockIndex(BB);
3136 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3137
3138 Value *InValue = PHI->getIncomingValue(Idx);
3139 if (InValue != CaseValue) continue;
3140
3141 *PhiIndex = Idx;
3142 return PHI;
3143 }
3144
3145 return NULL;
3146}
3147
3148/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3149/// instruction to a phi node dominated by the switch, if that would mean that
3150/// some of the destination blocks of the switch can be folded away.
3151/// Returns true if a change is made.
3152static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3153 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3154 ForwardingNodesMap ForwardingNodes;
3155
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003156 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003157 ConstantInt *CaseValue = I.getCaseValue();
3158 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg448da512011-06-18 10:28:47 +00003159
3160 int PhiIndex;
3161 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3162 &PhiIndex);
3163 if (!PHI) continue;
3164
3165 ForwardingNodes[PHI].push_back(PhiIndex);
3166 }
3167
3168 bool Changed = false;
3169
3170 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3171 E = ForwardingNodes.end(); I != E; ++I) {
3172 PHINode *Phi = I->first;
3173 SmallVector<int,4> &Indexes = I->second;
3174
3175 if (Indexes.size() < 2) continue;
3176
3177 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3178 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3179 Changed = true;
3180 }
3181
3182 return Changed;
3183}
3184
Hans Wennborg486270a2012-09-06 09:43:28 +00003185/// ValidLookupTableConstant - Return true if the backend will be able to handle
3186/// initializing an array of constants like C.
Hans Wennborgbf015822012-09-07 08:22:57 +00003187static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg486270a2012-09-06 09:43:28 +00003188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3189 return CE->isGEPWithNoNotionalOverIndexing();
3190
3191 return isa<ConstantFP>(C) ||
3192 isa<ConstantInt>(C) ||
3193 isa<ConstantPointerNull>(C) ||
3194 isa<GlobalValue>(C) ||
3195 isa<UndefValue>(C);
3196}
3197
3198/// GetCaseResulsts - Try to determine the resulting constant values in phi
3199/// nodes at the common destination basic block for one of the case
3200/// destinations of a switch instruction.
3201static bool GetCaseResults(SwitchInst *SI,
3202 BasicBlock *CaseDest,
3203 BasicBlock **CommonDest,
3204 SmallVector<std::pair<PHINode*,Constant*>, 4> &Res) {
3205 // The block from which we enter the common destination.
3206 BasicBlock *Pred = SI->getParent();
3207
3208 // If CaseDest is empty, continue to its successor.
3209 if (CaseDest->getFirstNonPHIOrDbg() == CaseDest->getTerminator() &&
3210 !isa<PHINode>(CaseDest->begin())) {
3211
3212 TerminatorInst *Terminator = CaseDest->getTerminator();
3213 if (Terminator->getNumSuccessors() != 1)
3214 return false;
3215
3216 Pred = CaseDest;
3217 CaseDest = Terminator->getSuccessor(0);
3218 }
3219
3220 // If we did not have a CommonDest before, use the current one.
3221 if (!*CommonDest)
3222 *CommonDest = CaseDest;
3223 // If the destination isn't the common one, abort.
3224 if (CaseDest != *CommonDest)
3225 return false;
3226
3227 // Get the values for this case from phi nodes in the destination block.
3228 BasicBlock::iterator I = (*CommonDest)->begin();
3229 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3230 int Idx = PHI->getBasicBlockIndex(Pred);
3231 if (Idx == -1)
3232 continue;
3233
3234 Constant *ConstVal = dyn_cast<Constant>(PHI->getIncomingValue(Idx));
3235 if (!ConstVal)
3236 return false;
3237
3238 // Be conservative about which kinds of constants we support.
3239 if (!ValidLookupTableConstant(ConstVal))
3240 return false;
3241
3242 Res.push_back(std::make_pair(PHI, ConstVal));
3243 }
3244
3245 return true;
3246}
3247
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003248namespace {
3249 /// SwitchLookupTable - This class represents a lookup table that can be used
3250 /// to replace a switch.
3251 class SwitchLookupTable {
3252 public:
3253 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3254 /// with the contents of Values, using DefaultValue to fill any holes in the
3255 /// table.
3256 SwitchLookupTable(Module &M,
3257 uint64_t TableSize,
3258 ConstantInt *Offset,
3259 const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003260 Constant *DefaultValue,
3261 const TargetData *TD);
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003262
3263 /// BuildLookup - Build instructions with Builder to retrieve the value at
3264 /// the position given by Index in the lookup table.
3265 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3266
Hans Wennborgd72271c2012-09-26 09:44:49 +00003267 /// WouldFitInRegister - Return true if a table with TableSize elements of
3268 /// type ElementType would fit in a target-legal register.
3269 static bool WouldFitInRegister(const TargetData *TD,
3270 uint64_t TableSize,
3271 const Type *ElementType);
3272
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003273 private:
3274 // Depending on the contents of the table, it can be represented in
3275 // different ways.
3276 enum {
3277 // For tables where each element contains the same value, we just have to
3278 // store that single value and return it for each lookup.
3279 SingleValueKind,
3280
Hans Wennborgd72271c2012-09-26 09:44:49 +00003281 // For small tables with integer elements, we can pack them into a bitmap
3282 // that fits into a target-legal register. Values are retrieved by
3283 // shift and mask operations.
3284 BitMapKind,
3285
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003286 // The table is stored as an array of values. Values are retrieved by load
3287 // instructions from the table.
3288 ArrayKind
3289 } Kind;
3290
3291 // For SingleValueKind, this is the single value.
3292 Constant *SingleValue;
3293
Hans Wennborgd72271c2012-09-26 09:44:49 +00003294 // For BitMapKind, this is the bitmap.
3295 ConstantInt *BitMap;
3296 IntegerType *BitMapElementTy;
3297
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003298 // For ArrayKind, this is the array.
3299 GlobalVariable *Array;
3300 };
3301}
3302
3303SwitchLookupTable::SwitchLookupTable(Module &M,
3304 uint64_t TableSize,
3305 ConstantInt *Offset,
3306 const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003307 Constant *DefaultValue,
3308 const TargetData *TD) {
Hans Wennborg565df792012-09-26 11:07:37 +00003309 assert(Values.size() && "Can't build lookup table without values!");
3310 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg486270a2012-09-06 09:43:28 +00003311
3312 // If all values in the table are equal, this is that value.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003313 SingleValue = Values.begin()->second;
Hans Wennborg486270a2012-09-06 09:43:28 +00003314
3315 // Build up the table contents.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003316 SmallVector<Constant*, 64> TableContents(TableSize);
3317 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3318 ConstantInt *CaseVal = Values[I].first;
3319 Constant *CaseRes = Values[I].second;
3320 assert(CaseRes->getType() == DefaultValue->getType());
Hans Wennborg486270a2012-09-06 09:43:28 +00003321
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003322 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3323 .getLimitedValue();
Hans Wennborg486270a2012-09-06 09:43:28 +00003324 TableContents[Idx] = CaseRes;
3325
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003326 if (CaseRes != SingleValue)
3327 SingleValue = NULL;
Hans Wennborg486270a2012-09-06 09:43:28 +00003328 }
3329
3330 // Fill in any holes in the table with the default result.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003331 if (Values.size() < TableSize) {
3332 for (uint64_t I = 0; I < TableSize; ++I) {
3333 if (!TableContents[I])
3334 TableContents[I] = DefaultValue;
Hans Wennborg486270a2012-09-06 09:43:28 +00003335 }
3336
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003337 if (DefaultValue != SingleValue)
3338 SingleValue = NULL;
Hans Wennborg486270a2012-09-06 09:43:28 +00003339 }
3340
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003341 // If each element in the table contains the same value, we only need to store
3342 // that single value.
3343 if (SingleValue) {
3344 Kind = SingleValueKind;
3345 return;
Hans Wennborg486270a2012-09-06 09:43:28 +00003346 }
3347
Hans Wennborgd72271c2012-09-26 09:44:49 +00003348 // If the type is integer and the table fits in a register, build a bitmap.
3349 if (WouldFitInRegister(TD, TableSize, DefaultValue->getType())) {
3350 IntegerType *IT = cast<IntegerType>(DefaultValue->getType());
3351 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3352 for (uint64_t I = TableSize; I > 0; --I) {
3353 TableInt <<= IT->getBitWidth();
Benjamin Kramer64f27e72012-10-01 11:31:48 +00003354 // Insert values into the bitmap. Undef values are set to zero.
3355 if (!isa<UndefValue>(TableContents[I - 1])) {
3356 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3357 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3358 }
Hans Wennborgd72271c2012-09-26 09:44:49 +00003359 }
3360 BitMap = ConstantInt::get(M.getContext(), TableInt);
3361 BitMapElementTy = IT;
3362 Kind = BitMapKind;
3363 ++NumBitMaps;
3364 return;
3365 }
3366
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003367 // Store the table in an array.
3368 ArrayType *ArrayTy = ArrayType::get(DefaultValue->getType(), TableSize);
Hans Wennborg486270a2012-09-06 09:43:28 +00003369 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3370
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003371 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3372 GlobalVariable::PrivateLinkage,
3373 Initializer,
3374 "switch.table");
3375 Array->setUnnamedAddr(true);
3376 Kind = ArrayKind;
3377}
3378
3379Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3380 switch (Kind) {
3381 case SingleValueKind:
3382 return SingleValue;
Hans Wennborgd72271c2012-09-26 09:44:49 +00003383 case BitMapKind: {
3384 // Type of the bitmap (e.g. i59).
3385 IntegerType *MapTy = BitMap->getType();
3386
3387 // Cast Index to the same type as the bitmap.
3388 // Note: The Index is <= the number of elements in the table, so
3389 // truncating it to the width of the bitmask is safe.
Hans Wennborg50b7d702012-09-26 14:01:53 +00003390 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborgd72271c2012-09-26 09:44:49 +00003391
3392 // Multiply the shift amount by the element width.
3393 ShiftAmt = Builder.CreateMul(ShiftAmt,
3394 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3395 "switch.shiftamt");
3396
3397 // Shift down.
3398 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3399 "switch.downshift");
3400 // Mask off.
3401 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3402 "switch.masked");
3403 }
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003404 case ArrayKind: {
3405 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3406 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3407 "switch.gep");
3408 return Builder.CreateLoad(GEP, "switch.load");
3409 }
3410 }
3411 llvm_unreachable("Unknown lookup table kind!");
3412}
3413
Hans Wennborgd72271c2012-09-26 09:44:49 +00003414bool SwitchLookupTable::WouldFitInRegister(const TargetData *TD,
3415 uint64_t TableSize,
3416 const Type *ElementType) {
3417 if (!TD)
3418 return false;
3419 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3420 if (!IT)
3421 return false;
3422 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3423 // are <= 15, we could try to narrow the type.
Benjamin Kramer465251a2012-09-27 18:29:58 +00003424
3425 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3426 if (TableSize >= UINT_MAX/IT->getBitWidth())
3427 return false;
Hans Wennborgd72271c2012-09-26 09:44:49 +00003428 return TD->fitsInLegalInteger(TableSize * IT->getBitWidth());
3429}
3430
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003431/// ShouldBuildLookupTable - Determine whether a lookup table should be built
3432/// for this switch, based on the number of caes, size of the table and the
3433/// types of the results.
3434static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003435 uint64_t TableSize,
3436 const TargetData *TD,
3437 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003438 // The table density should be at least 40%. This is the same criterion as for
3439 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3440 // FIXME: Find the best cut-off.
Hans Wennborg565df792012-09-26 11:07:37 +00003441 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3442 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003443 if (SI->getNumCases() * 10 >= TableSize * 4)
3444 return true;
3445
Hans Wennborgd72271c2012-09-26 09:44:49 +00003446 // If each table would fit in a register, we should build it anyway.
3447 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3448 E = ResultTypes.end(); I != E; ++I) {
3449 if (!SwitchLookupTable::WouldFitInRegister(TD, TableSize, I->second))
3450 return false;
3451 }
3452 return true;
Hans Wennborg486270a2012-09-06 09:43:28 +00003453}
3454
3455/// SwitchToLookupTable - If the switch is only used to initialize one or more
3456/// phi nodes in a common successor block with different constant values,
3457/// replace the switch with lookup tables.
3458static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003459 IRBuilder<> &Builder,
3460 const TargetData* TD) {
Hans Wennborg486270a2012-09-06 09:43:28 +00003461 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3462 // FIXME: Handle unreachable cases.
3463
3464 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3465 // split off a dense part and build a lookup table for that.
3466
Hans Wennborg486270a2012-09-06 09:43:28 +00003467 // FIXME: This creates arrays of GEPs to constant strings, which means each
3468 // GEP needs a runtime relocation in PIC code. We should just build one big
3469 // string and lookup indices into that.
3470
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003471 // Ignore the switch if the number of cases is too small.
Hans Wennborg486270a2012-09-06 09:43:28 +00003472 // This is similar to the check when building jump tables in
3473 // SelectionDAGBuilder::handleJTSwitchCase.
3474 // FIXME: Determine the best cut-off.
3475 if (SI->getNumCases() < 4)
3476 return false;
3477
3478 // Figure out the corresponding result for each case value and phi node in the
3479 // common destination, as well as the the min and max case values.
3480 assert(SI->case_begin() != SI->case_end());
3481 SwitchInst::CaseIt CI = SI->case_begin();
3482 ConstantInt *MinCaseVal = CI.getCaseValue();
3483 ConstantInt *MaxCaseVal = CI.getCaseValue();
3484
3485 BasicBlock *CommonDest = NULL;
Hans Wennborg2f9fc762012-09-10 07:44:22 +00003486 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg486270a2012-09-06 09:43:28 +00003487 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3488 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3489 SmallDenseMap<PHINode*, Type*> ResultTypes;
3490 SmallVector<PHINode*, 4> PHIs;
3491
3492 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3493 ConstantInt *CaseVal = CI.getCaseValue();
3494 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3495 MinCaseVal = CaseVal;
3496 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3497 MaxCaseVal = CaseVal;
3498
3499 // Resulting value at phi nodes for this case value.
3500 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3501 ResultsTy Results;
3502 if (!GetCaseResults(SI, CI.getCaseSuccessor(), &CommonDest, Results))
3503 return false;
3504
3505 // Append the result from this case to the list for each phi.
3506 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3507 if (!ResultLists.count(I->first))
3508 PHIs.push_back(I->first);
3509 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3510 }
3511 }
3512
3513 // Get the resulting values for the default case.
Hans Wennborg2f9fc762012-09-10 07:44:22 +00003514 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3515 if (!GetCaseResults(SI, SI->getDefaultDest(), &CommonDest, DefaultResultsList))
3516 return false;
3517 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3518 PHINode *PHI = DefaultResultsList[I].first;
3519 Constant *Result = DefaultResultsList[I].second;
3520 DefaultResults[PHI] = Result;
3521 ResultTypes[PHI] = Result->getType();
Hans Wennborg486270a2012-09-06 09:43:28 +00003522 }
3523
3524 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
Hans Wennborg486270a2012-09-06 09:43:28 +00003525 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
Hans Wennborgd72271c2012-09-26 09:44:49 +00003526 if (!ShouldBuildLookupTable(SI, TableSize, TD, ResultTypes))
Hans Wennborg486270a2012-09-06 09:43:28 +00003527 return false;
3528
Hans Wennborg486270a2012-09-06 09:43:28 +00003529 // Create the BB that does the lookups.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003530 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg486270a2012-09-06 09:43:28 +00003531 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3532 "switch.lookup",
3533 CommonDest->getParent(),
3534 CommonDest);
3535
3536 // Check whether the condition value is within the case range, and branch to
3537 // the new BB.
3538 Builder.SetInsertPoint(SI);
3539 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3540 "switch.tableidx");
3541 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3542 MinCaseVal->getType(), TableSize));
3543 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3544
3545 // Populate the BB that does the lookups.
3546 Builder.SetInsertPoint(LookupBB);
3547 bool ReturnedEarly = false;
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003548 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3549 PHINode *PHI = PHIs[I];
Hans Wennborg486270a2012-09-06 09:43:28 +00003550
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003551 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
Hans Wennborgd72271c2012-09-26 09:44:49 +00003552 DefaultResults[PHI], TD);
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003553
3554 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg486270a2012-09-06 09:43:28 +00003555
Hans Wennborg57933e32012-09-19 14:24:21 +00003556 // If the result is used to return immediately from the function, we want to
3557 // do that right here.
3558 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->use_begin()) &&
3559 *PHI->use_begin() == CommonDest->getFirstNonPHIOrDbg()) {
3560 Builder.CreateRet(Result);
3561 ReturnedEarly = true;
3562 break;
Hans Wennborg486270a2012-09-06 09:43:28 +00003563 }
3564
Hans Wennborg57933e32012-09-19 14:24:21 +00003565 PHI->addIncoming(Result, LookupBB);
Hans Wennborg486270a2012-09-06 09:43:28 +00003566 }
3567
3568 if (!ReturnedEarly)
3569 Builder.CreateBr(CommonDest);
3570
3571 // Remove the switch.
3572 for (unsigned i = 0; i < SI->getNumSuccessors(); ++i) {
3573 BasicBlock *Succ = SI->getSuccessor(i);
3574 if (Succ == SI->getDefaultDest()) continue;
3575 Succ->removePredecessor(SI->getParent());
3576 }
3577 SI->eraseFromParent();
3578
3579 ++NumLookupTables;
3580 return true;
3581}
3582
Devang Patel007349d2011-05-18 20:35:38 +00003583bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00003584 // If this switch is too complex to want to look at, ignore it.
3585 if (!isValueEqualityComparison(SI))
3586 return false;
3587
3588 BasicBlock *BB = SI->getParent();
3589
3590 // If we only have one predecessor, and if it is a branch on this value,
3591 // see if that predecessor totally determines the outcome of this switch.
3592 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patel007349d2011-05-18 20:35:38 +00003593 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Chris Lattner021c9d32010-12-13 06:36:51 +00003594 return SimplifyCFG(BB) | true;
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00003595
3596 Value *Cond = SI->getCondition();
3597 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3598 if (SimplifySwitchOnSelect(SI, Select))
3599 return SimplifyCFG(BB) | true;
3600
Chris Lattner3d512132010-12-13 06:25:44 +00003601 // If the block only contains the switch, see if we can fold the block
3602 // away into any preds.
3603 BasicBlock::iterator BBI = BB->begin();
3604 // Ignore dbg intrinsics.
3605 while (isa<DbgInfoIntrinsic>(BBI))
3606 ++BBI;
3607 if (SI == &*BBI)
Devang Patelb55d9242011-05-18 20:53:17 +00003608 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Chris Lattner021c9d32010-12-13 06:36:51 +00003609 return SimplifyCFG(BB) | true;
Benjamin Kramer56442df2011-02-02 15:56:22 +00003610
3611 // Try to transform the switch into an icmp and a branch.
Devang Patel007349d2011-05-18 20:35:38 +00003612 if (TurnSwitchRangeIntoICmp(SI, Builder))
Benjamin Kramer56442df2011-02-02 15:56:22 +00003613 return SimplifyCFG(BB) | true;
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003614
3615 // Remove unreachable cases.
3616 if (EliminateDeadSwitchCases(SI))
3617 return SimplifyCFG(BB) | true;
3618
Hans Wennborg448da512011-06-18 10:28:47 +00003619 if (ForwardSwitchConditionToPHI(SI))
3620 return SimplifyCFG(BB) | true;
3621
Hans Wennborgd72271c2012-09-26 09:44:49 +00003622 if (SwitchToLookupTable(SI, Builder, TD))
Hans Wennborg486270a2012-09-06 09:43:28 +00003623 return SimplifyCFG(BB) | true;
3624
Chris Lattner3d512132010-12-13 06:25:44 +00003625 return false;
3626}
3627
3628bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3629 BasicBlock *BB = IBI->getParent();
3630 bool Changed = false;
Andrew Trick6b014382012-08-29 21:46:36 +00003631
Chris Lattner3d512132010-12-13 06:25:44 +00003632 // Eliminate redundant destinations.
3633 SmallPtrSet<Value *, 8> Succs;
3634 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3635 BasicBlock *Dest = IBI->getDestination(i);
3636 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3637 Dest->removePredecessor(BB);
3638 IBI->removeDestination(i);
3639 --i; --e;
3640 Changed = true;
3641 }
Andrew Trick6b014382012-08-29 21:46:36 +00003642 }
Chris Lattner3d512132010-12-13 06:25:44 +00003643
3644 if (IBI->getNumDestinations() == 0) {
3645 // If the indirectbr has no successors, change it to unreachable.
3646 new UnreachableInst(IBI->getContext(), IBI);
3647 EraseTerminatorInstAndDCECond(IBI);
3648 return true;
3649 }
Andrew Trick6b014382012-08-29 21:46:36 +00003650
Chris Lattner3d512132010-12-13 06:25:44 +00003651 if (IBI->getNumDestinations() == 1) {
3652 // If the indirectbr has one successor, change it to a direct branch.
3653 BranchInst::Create(IBI->getDestination(0), IBI);
3654 EraseTerminatorInstAndDCECond(IBI);
3655 return true;
3656 }
Andrew Trick6b014382012-08-29 21:46:36 +00003657
Chris Lattner3d512132010-12-13 06:25:44 +00003658 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3659 if (SimplifyIndirectBrOnSelect(IBI, SI))
3660 return SimplifyCFG(BB) | true;
3661 }
3662 return Changed;
3663}
3664
Devang Patela23812c2011-05-18 18:28:48 +00003665bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner3d512132010-12-13 06:25:44 +00003666 BasicBlock *BB = BI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00003667
Manman Ren554da1a2012-09-20 22:37:36 +00003668 if (SinkCommon && SinkThenElseCodeToEnd(BI))
3669 return true;
3670
Chris Lattner3d512132010-12-13 06:25:44 +00003671 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindola77a2c372011-06-30 20:14:24 +00003672 BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
Chris Lattner3d512132010-12-13 06:25:44 +00003673 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3674 TryToSimplifyUncondBranchFromEmptyBlock(BB))
3675 return true;
Andrew Trick6b014382012-08-29 21:46:36 +00003676
Chris Lattner3d512132010-12-13 06:25:44 +00003677 // If the only instruction in the block is a seteq/setne comparison
3678 // against a constant, try to simplify the block.
3679 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3680 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3681 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
3682 ;
Nick Lewycky9d523102011-12-26 20:37:40 +00003683 if (I->isTerminator() &&
3684 TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003685 return true;
3686 }
Andrew Trick6b014382012-08-29 21:46:36 +00003687
Manman Renee28e0f2012-06-13 05:43:29 +00003688 // If this basic block is ONLY a compare and a branch, and if a predecessor
3689 // branches to us and our successor, fold the comparison into the
3690 // predecessor and use logical operations to update the incoming value
3691 // for PHI nodes in common successor.
3692 if (FoldBranchToCommonDest(BI))
3693 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00003694 return false;
3695}
3696
3697
Devang Patel007349d2011-05-18 20:35:38 +00003698bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00003699 BasicBlock *BB = BI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00003700
Chris Lattner3d512132010-12-13 06:25:44 +00003701 // Conditional branch
3702 if (isValueEqualityComparison(BI)) {
3703 // If we only have one predecessor, and if it is a branch on this value,
3704 // see if that predecessor totally determines the outcome of this
3705 // switch.
3706 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patel007349d2011-05-18 20:35:38 +00003707 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003708 return SimplifyCFG(BB) | true;
Andrew Trick6b014382012-08-29 21:46:36 +00003709
Chris Lattner3d512132010-12-13 06:25:44 +00003710 // This block must be empty, except for the setcond inst, if it exists.
3711 // Ignore dbg intrinsics.
3712 BasicBlock::iterator I = BB->begin();
3713 // Ignore dbg intrinsics.
3714 while (isa<DbgInfoIntrinsic>(I))
3715 ++I;
3716 if (&*I == BI) {
Devang Patelb55d9242011-05-18 20:53:17 +00003717 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003718 return SimplifyCFG(BB) | true;
3719 } else if (&*I == cast<Instruction>(BI->getCondition())){
3720 ++I;
3721 // Ignore dbg intrinsics.
3722 while (isa<DbgInfoIntrinsic>(I))
3723 ++I;
Devang Patelb55d9242011-05-18 20:53:17 +00003724 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003725 return SimplifyCFG(BB) | true;
3726 }
3727 }
Andrew Trick6b014382012-08-29 21:46:36 +00003728
Chris Lattner3d512132010-12-13 06:25:44 +00003729 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Devang Patel02dd5412011-05-18 23:18:47 +00003730 if (SimplifyBranchOnICmpChain(BI, TD, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003731 return true;
Andrew Trick6b014382012-08-29 21:46:36 +00003732
Dan Gohman3b205172012-01-05 23:58:56 +00003733 // If this basic block is ONLY a compare and a branch, and if a predecessor
3734 // branches to us and one of our successors, fold the comparison into the
3735 // predecessor and use logical operations to pick the right destination.
3736 if (FoldBranchToCommonDest(BI))
3737 return SimplifyCFG(BB) | true;
Andrew Trick6b014382012-08-29 21:46:36 +00003738
Chris Lattner3d512132010-12-13 06:25:44 +00003739 // We have a conditional branch to two blocks that are only reachable
3740 // from BI. We know that the condbr dominates the two blocks, so see if
3741 // there is any identical code in the "then" and "else" blocks. If so, we
3742 // can hoist it up to the branching block.
3743 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
3744 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
Rafael Espindola216dde92011-05-19 02:26:30 +00003745 if (HoistThenElseCodeToIf(BI))
Chris Lattner3d512132010-12-13 06:25:44 +00003746 return SimplifyCFG(BB) | true;
3747 } else {
3748 // If Successor #1 has multiple preds, we may be able to conditionally
3749 // execute Successor #0 if it branches to successor #1.
3750 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
3751 if (Succ0TI->getNumSuccessors() == 1 &&
3752 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Rafael Espindola216dde92011-05-19 02:26:30 +00003753 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
Chris Lattner3d512132010-12-13 06:25:44 +00003754 return SimplifyCFG(BB) | true;
3755 }
3756 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
3757 // If Successor #0 has multiple preds, we may be able to conditionally
3758 // execute Successor #1 if it branches to successor #0.
3759 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
3760 if (Succ1TI->getNumSuccessors() == 1 &&
3761 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Rafael Espindola216dde92011-05-19 02:26:30 +00003762 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
Chris Lattner3d512132010-12-13 06:25:44 +00003763 return SimplifyCFG(BB) | true;
3764 }
Andrew Trick6b014382012-08-29 21:46:36 +00003765
Chris Lattner3d512132010-12-13 06:25:44 +00003766 // If this is a branch on a phi node in the current block, thread control
3767 // through this block if any PHI node entries are constants.
3768 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
3769 if (PN->getParent() == BI->getParent())
Chris Lattner302ba6f2010-12-14 06:17:25 +00003770 if (FoldCondBranchOnPHI(BI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00003771 return SimplifyCFG(BB) | true;
Andrew Trick6b014382012-08-29 21:46:36 +00003772
Chris Lattner3d512132010-12-13 06:25:44 +00003773 // Scan predecessor blocks for conditional branches.
3774 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
3775 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
3776 if (PBI != BI && PBI->isConditional())
3777 if (SimplifyCondBranchToCondBranch(PBI, BI))
3778 return SimplifyCFG(BB) | true;
3779
3780 return false;
3781}
3782
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003783/// Check if passing a value to an instruction will cause undefined behavior.
3784static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
3785 Constant *C = dyn_cast<Constant>(V);
3786 if (!C)
3787 return false;
3788
Benjamin Kramer1e21db62012-10-04 16:11:49 +00003789 if (I->use_empty())
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003790 return false;
3791
3792 if (C->isNullValue()) {
Benjamin Kramer1e21db62012-10-04 16:11:49 +00003793 // Only look at the first use, avoid hurting compile time with long uselists
3794 User *Use = *I->use_begin();
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003795
3796 // Now make sure that there are no instructions in between that can alter
3797 // control flow (eg. calls)
3798 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer9bb54882011-08-26 02:25:55 +00003799 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003800 return false;
3801
3802 // Look through GEPs. A load from a GEP derived from NULL is still undefined
3803 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
3804 if (GEP->getPointerOperand() == I)
3805 return passingValueIsAlwaysUndefined(V, GEP);
3806
3807 // Look through bitcasts.
3808 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
3809 return passingValueIsAlwaysUndefined(V, BC);
3810
Benjamin Kramer9bb54882011-08-26 02:25:55 +00003811 // Load from null is undefined.
3812 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
3813 return LI->getPointerAddressSpace() == 0;
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003814
Benjamin Kramer9bb54882011-08-26 02:25:55 +00003815 // Store to null is undefined.
3816 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
3817 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003818 }
3819 return false;
3820}
3821
3822/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewycky9d523102011-12-26 20:37:40 +00003823/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003824static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
3825 for (BasicBlock::iterator i = BB->begin();
3826 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
3827 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
3828 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
3829 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
3830 IRBuilder<> Builder(T);
3831 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
3832 BB->removePredecessor(PHI->getIncomingBlock(i));
3833 // Turn uncoditional branches into unreachables and remove the dead
3834 // destination from conditional branches.
3835 if (BI->isUnconditional())
3836 Builder.CreateUnreachable();
3837 else
3838 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
3839 BI->getSuccessor(0));
3840 BI->eraseFromParent();
3841 return true;
3842 }
3843 // TODO: SwitchInst.
3844 }
3845
3846 return false;
3847}
3848
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003849bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00003850 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00003851
Chris Lattner302ba6f2010-12-14 06:17:25 +00003852 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00003853 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00003854
Dan Gohmane2c6d132010-08-14 00:29:42 +00003855 // Remove basic blocks that have no predecessors (except the entry block)...
3856 // or that just have themself as a predecessor. These are unreachable.
Chris Lattner302ba6f2010-12-14 06:17:25 +00003857 if ((pred_begin(BB) == pred_end(BB) &&
3858 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00003859 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00003860 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00003861 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00003862 return true;
3863 }
3864
Chris Lattner694e37f2003-08-17 19:41:53 +00003865 // Check to see if we can constant propagate this terminator instruction
3866 // away...
Frits van Bommel5649ba72011-05-22 16:24:18 +00003867 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner694e37f2003-08-17 19:41:53 +00003868
Dan Gohman2c635662009-10-30 22:39:04 +00003869 // Check for and eliminate duplicate PHI nodes in this block.
3870 Changed |= EliminateDuplicatePHINodes(BB);
3871
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003872 // Check for and remove branches that will always cause undefined behavior.
3873 Changed |= removeUndefIntroducingPredecessor(BB);
3874
Chris Lattnerddb97a22010-12-13 05:10:48 +00003875 // Merge basic blocks into their predecessor if there is only one distinct
3876 // pred, and if there is only one distinct successor of the predecessor, and
3877 // if there are no PHI nodes.
3878 //
3879 if (MergeBlockIntoPredecessor(BB))
3880 return true;
Andrew Trick6b014382012-08-29 21:46:36 +00003881
Devang Patel3e410c62011-05-18 18:01:27 +00003882 IRBuilder<> Builder(BB);
3883
Dan Gohman882d87d2008-03-11 21:53:06 +00003884 // If there is a trivial two-entry PHI node in this basic block, and we can
3885 // eliminate it, do so now.
3886 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
3887 if (PN->getNumIncomingValues() == 2)
Devang Pateld3a17882011-05-19 20:52:46 +00003888 Changed |= FoldTwoEntryPHINode(PN, TD);
Dan Gohman882d87d2008-03-11 21:53:06 +00003889
Devang Patel007349d2011-05-18 20:35:38 +00003890 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner3d512132010-12-13 06:25:44 +00003891 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner021c9d32010-12-13 06:36:51 +00003892 if (BI->isUnconditional()) {
Devang Patela23812c2011-05-18 18:28:48 +00003893 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003894 } else {
Devang Patel007349d2011-05-18 20:35:38 +00003895 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003896 }
3897 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Patel176ec402011-05-18 21:33:11 +00003898 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingaa5abe82012-02-06 21:16:41 +00003899 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
3900 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003901 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patel007349d2011-05-18 20:35:38 +00003902 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003903 } else if (UnreachableInst *UI =
3904 dyn_cast<UnreachableInst>(BB->getTerminator())) {
3905 if (SimplifyUnreachable(UI)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003906 } else if (IndirectBrInst *IBI =
3907 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
3908 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattner19831ec2004-02-16 06:35:48 +00003909 }
3910
Chris Lattner694e37f2003-08-17 19:41:53 +00003911 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00003912}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003913
3914/// SimplifyCFG - This function is used to do simplification of a CFG. For
3915/// example, it adjusts branches to branches to eliminate the extra hop, it
3916/// eliminates unreachable basic blocks, and does other "peephole" optimization
3917/// of the CFG. It returns true if a modification was made.
3918///
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003919bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
3920 return SimplifyCFGOpt(TD).run(BB);
3921}