blob: cb56abe294e0249e5ab484a2f7b44407d7953ea4 [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000021#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000038#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000042#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattner466a0492002-05-21 20:50:24 +000047#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000048#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000050using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000051using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000052
Chandler Carruth964daaa2014-04-22 02:55:47 +000053#define DEBUG_TYPE "simplifycfg"
54
Peter Collingbourne616044a2011-04-29 18:47:38 +000055static cl::opt<unsigned>
56PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
57 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
58
Evan Chengd983eba2011-01-29 04:46:23 +000059static cl::opt<bool>
60DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
61 cl::desc("Duplicate return instructions into unconditional branches"));
62
Manman Ren93ab6492012-09-20 22:37:36 +000063static cl::opt<bool>
64SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
65 cl::desc("Sink common instructions down to the end block"));
66
Alp Tokercb402912014-01-24 17:20:08 +000067static cl::opt<bool> HoistCondStores(
68 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
69 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000070
Hans Wennborg39583b82012-09-26 09:44:49 +000071STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000072STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000073STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Manman Ren93ab6492012-09-20 22:37:36 +000074STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000075STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000076
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000077namespace {
Eric Christopherb65acc62012-07-02 23:22:21 +000078 /// ValueEqualityComparisonCase - Represents a case of a switch.
79 struct ValueEqualityComparisonCase {
80 ConstantInt *Value;
81 BasicBlock *Dest;
82
83 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
84 : Value(Value), Dest(Dest) {}
85
86 bool operator<(ValueEqualityComparisonCase RHS) const {
87 // Comparing pointers is ok as we only rely on the order for uniquing.
88 return Value < RHS.Value;
89 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +000090
91 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +000092 };
93
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000094class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +000095 const TargetTransformInfo &TTI;
Rafael Espindola37dc9e12014-02-21 00:06:31 +000096 const DataLayout *const DL;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000097 Value *isValueEqualityComparison(TerminatorInst *TI);
98 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +000099 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000100 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000101 BasicBlock *Pred,
102 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000103 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
104 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000105
Devang Pateldd14e0f2011-05-18 21:33:11 +0000106 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000107 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000108 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000109 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000110 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000111 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000112 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000113
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000114public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000115 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *DL)
116 : TTI(TTI), DL(DL) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000117 bool run(BasicBlock *BB);
118};
119}
120
Chris Lattner76dc2042005-08-03 00:19:45 +0000121/// SafeToMergeTerminators - Return true if it is safe to merge these two
122/// terminator instructions together.
123///
124static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
125 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000126
Chris Lattner76dc2042005-08-03 00:19:45 +0000127 // It is not safe to merge these two switch instructions if they have a common
128 // successor, and if that successor has a PHI node, and if *that* PHI node has
129 // conflicting incoming values from the two switch blocks.
130 BasicBlock *SI1BB = SI1->getParent();
131 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000132 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000133
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000134 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
135 if (SI1Succs.count(*I))
136 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000137 isa<PHINode>(BBI); ++BBI) {
138 PHINode *PN = cast<PHINode>(BBI);
139 if (PN->getIncomingValueForBlock(SI1BB) !=
140 PN->getIncomingValueForBlock(SI2BB))
141 return false;
142 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000143
Chris Lattner76dc2042005-08-03 00:19:45 +0000144 return true;
145}
146
Manman Rend33f4ef2012-06-13 05:43:29 +0000147/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
148/// to merge these two terminator instructions together, where SI1 is an
149/// unconditional branch. PhiNodes will store all PHI nodes in common
150/// successors.
151///
152static bool isProfitableToFoldUnconditional(BranchInst *SI1,
153 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000154 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000155 SmallVectorImpl<PHINode*> &PhiNodes) {
156 if (SI1 == SI2) return false; // Can't merge with self!
157 assert(SI1->isUnconditional() && SI2->isConditional());
158
159 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000160 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000161 // 1> We have a constant incoming value for the conditional branch;
162 // 2> We have "Cond" as the incoming value for the unconditional branch;
163 // 3> SI2->getCondition() and Cond have same operands.
164 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
165 if (!Ci2) return false;
166 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
167 Cond->getOperand(1) == Ci2->getOperand(1)) &&
168 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
169 Cond->getOperand(1) == Ci2->getOperand(0)))
170 return false;
171
172 BasicBlock *SI1BB = SI1->getParent();
173 BasicBlock *SI2BB = SI2->getParent();
174 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000175 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
176 if (SI1Succs.count(*I))
177 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000178 isa<PHINode>(BBI); ++BBI) {
179 PHINode *PN = cast<PHINode>(BBI);
180 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000181 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000182 return false;
183 PhiNodes.push_back(PN);
184 }
185 return true;
186}
187
Chris Lattner76dc2042005-08-03 00:19:45 +0000188/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
189/// now be entries in it from the 'NewPred' block. The values that will be
190/// flowing into the PHI nodes will be the same as those coming in from
191/// ExistPred, an existing predecessor of Succ.
192static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
193 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000194 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000195
Chris Lattner80b03a12008-07-13 22:23:11 +0000196 PHINode *PN;
197 for (BasicBlock::iterator I = Succ->begin();
198 (PN = dyn_cast<PHINode>(I)); ++I)
199 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000200}
201
David Majnemer91142c42013-06-01 19:43:23 +0000202/// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000203/// given instruction, which is assumed to be safe to speculate. 1 means
204/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
Hal Finkela995f922014-07-10 14:41:31 +0000205static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
206 assert(isSafeToSpeculativelyExecute(I, DL) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000207 "Instruction is not safe to speculatively execute!");
208 switch (Operator::getOpcode(I)) {
209 default:
210 // In doubt, be conservative.
211 return UINT_MAX;
212 case Instruction::GetElementPtr:
213 // GEPs are cheap if all indices are constant.
214 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
215 return UINT_MAX;
216 return 1;
Louis Gerbarg1f54b822014-05-09 17:02:46 +0000217 case Instruction::ExtractValue:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000218 case Instruction::Load:
219 case Instruction::Add:
220 case Instruction::Sub:
221 case Instruction::And:
222 case Instruction::Or:
223 case Instruction::Xor:
224 case Instruction::Shl:
225 case Instruction::LShr:
226 case Instruction::AShr:
227 case Instruction::ICmp:
228 case Instruction::Trunc:
229 case Instruction::ZExt:
230 case Instruction::SExt:
Matt Arsenaultc8fc08c2014-05-30 18:34:43 +0000231 case Instruction::BitCast:
232 case Instruction::ExtractElement:
233 case Instruction::InsertElement:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000234 return 1; // These are all cheap.
235
236 case Instruction::Call:
237 case Instruction::Select:
238 return 2;
239 }
240}
241
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000242/// DominatesMergePoint - If we have a merge point of an "if condition" as
243/// accepted above, return true if the specified value dominates the block. We
244/// don't handle the true generality of domination here, just a special case
245/// which works well enough for us.
246///
247/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000248/// see if V (which must be an instruction) and its recursive operands
249/// that do not dominate BB have a combined cost lower than CostRemaining and
250/// are non-trapping. If both are true, the instruction is inserted into the
251/// set and true is returned.
252///
253/// The cost for most non-trapping instructions is defined as 1 except for
254/// Select whose cost is 2.
255///
256/// After this function returns, CostRemaining is decreased by the cost of
257/// V plus its non-dominating operands. If that cost is greater than
258/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000259static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000260 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000261 unsigned &CostRemaining,
262 const DataLayout *DL) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000263 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000264 if (!I) {
265 // Non-instructions all dominate instructions, but not all constantexprs
266 // can be executed unconditionally.
267 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
268 if (C->canTrap())
269 return false;
270 return true;
271 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000272 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000273
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000274 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000275 // the bottom of this block.
276 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000277
Chris Lattner0aa56562004-04-09 22:50:22 +0000278 // If this instruction is defined in a block that contains an unconditional
279 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000280 // statement". If not, it definitely dominates the region.
281 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000282 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000283 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000284
Chris Lattner9ac168d2010-12-14 07:41:39 +0000285 // If we aren't allowing aggressive promotion anymore, then don't consider
286 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000287 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000288
Peter Collingbournee3511e12011-04-29 18:47:31 +0000289 // If we have seen this instruction before, don't count it again.
290 if (AggressiveInsts->count(I)) return true;
291
Chris Lattner9ac168d2010-12-14 07:41:39 +0000292 // Okay, it looks like the instruction IS in the "condition". Check to
293 // see if it's a cheap instruction to unconditionally compute, and if it
294 // only uses stuff defined outside of the condition. If so, hoist it out.
Hal Finkela995f922014-07-10 14:41:31 +0000295 if (!isSafeToSpeculativelyExecute(I, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000296 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000297
Hal Finkela995f922014-07-10 14:41:31 +0000298 unsigned Cost = ComputeSpeculationCost(I, DL);
Chris Lattner0aa56562004-04-09 22:50:22 +0000299
Peter Collingbournee3511e12011-04-29 18:47:31 +0000300 if (Cost > CostRemaining)
301 return false;
302
303 CostRemaining -= Cost;
304
305 // Okay, we can only really hoist these out if their operands do
306 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000307 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Hal Finkela995f922014-07-10 14:41:31 +0000308 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000309 return false;
310 // Okay, it's safe to do this! Remember this instruction.
311 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000312 return true;
313}
Chris Lattner466a0492002-05-21 20:50:24 +0000314
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000315/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
316/// and PointerNullValue. Return NULL if value is not a constant int.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000317static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000318 // Normal constant int.
319 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000320 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000321 return CI;
322
323 // This is some kind of pointer constant. Turn it into a pointer-sized
324 // ConstantInt if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000325 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000326
327 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
328 if (isa<ConstantPointerNull>(V))
329 return ConstantInt::get(PtrTy, 0);
330
331 // IntToPtr const int.
332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
333 if (CE->getOpcode() == Instruction::IntToPtr)
334 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
335 // The constant is very likely to have the right type already.
336 if (CI->getType() == PtrTy)
337 return CI;
338 else
339 return cast<ConstantInt>
340 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
341 }
Craig Topperf40110f2014-04-25 05:29:35 +0000342 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000343}
344
Chris Lattner5a177e62010-12-13 04:26:26 +0000345/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
346/// collection of icmp eq/ne instructions that compare a value against a
347/// constant, return the value being compared, and stick the constant into the
348/// Values vector.
Chris Lattner11dafaa2010-12-13 03:30:12 +0000349static Value *
Chris Lattner5a177e62010-12-13 04:26:26 +0000350GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000351 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000352 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000353 if (!I) return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000354
Chris Lattnera442f242010-12-13 04:50:38 +0000355 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner5a177e62010-12-13 04:26:26 +0000356 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000357 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
Benjamin Kramer37172222013-07-04 14:22:02 +0000358 Value *RHSVal;
359 ConstantInt *RHSC;
360
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000361 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer37172222013-07-04 14:22:02 +0000362 // (x & ~2^x) == y --> x == y || x == y|2^x
363 // This undoes a transformation done by instcombine to fuse 2 compares.
364 if (match(ICI->getOperand(0),
365 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
366 APInt Not = ~RHSC->getValue();
367 if (Not.isPowerOf2()) {
368 Vals.push_back(C);
369 Vals.push_back(
370 ConstantInt::get(C->getContext(), C->getValue() | Not));
371 UsedICmps++;
372 return RHSVal;
373 }
374 }
375
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000376 UsedICmps++;
Chris Lattner5a177e62010-12-13 04:26:26 +0000377 Vals.push_back(C);
378 return I->getOperand(0);
379 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000380
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000381 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
382 // the set.
383 ConstantRange Span =
Chris Lattner6b8b4852010-12-18 20:22:49 +0000384 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +0000385
Benjamin Kramer37172222013-07-04 14:22:02 +0000386 // Shift the range if the compare is fed by an add. This is the range
387 // compare idiom as emitted by instcombine.
388 bool hasAdd =
389 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
390 if (hasAdd)
391 Span = Span.subtract(RHSC->getValue());
392
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000393 // If this is an and/!= check then we want to optimize "x ugt 2" into
394 // x != 0 && x != 1.
395 if (!isEQ)
396 Span = Span.inverse();
Andrew Trickf3cf1932012-08-29 21:46:36 +0000397
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000398 // If there are a ton of values, we don't want to make a ginormous switch.
Nick Lewycky219e6bc2012-01-19 18:19:42 +0000399 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
Craig Topperf40110f2014-04-25 05:29:35 +0000400 return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000401
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000402 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
403 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000404 UsedICmps++;
Benjamin Kramer37172222013-07-04 14:22:02 +0000405 return hasAdd ? RHSVal : I->getOperand(0);
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000406 }
Craig Topperf40110f2014-04-25 05:29:35 +0000407 return nullptr;
Chris Lattner9b1af512010-12-13 04:18:32 +0000408 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000409
Chris Lattnera442f242010-12-13 04:50:38 +0000410 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner5a177e62010-12-13 04:26:26 +0000411 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Craig Topperf40110f2014-04-25 05:29:35 +0000412 return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000413
Chris Lattnera442f242010-12-13 04:50:38 +0000414 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000415 unsigned UsedICmpsBeforeLHS = UsedICmps;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000416 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000417 isEQ, UsedICmps)) {
Chris Lattnera442f242010-12-13 04:50:38 +0000418 unsigned NumVals = Vals.size();
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000419 unsigned UsedICmpsBeforeRHS = UsedICmps;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000420 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000421 isEQ, UsedICmps)) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000422 if (LHS == RHS)
423 return LHS;
Chris Lattner79db3572010-12-13 07:41:29 +0000424 Vals.resize(NumVals);
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000425 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner5a177e62010-12-13 04:26:26 +0000426 }
Chris Lattnera442f242010-12-13 04:50:38 +0000427
428 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
429 // set it and return success.
Craig Topperf40110f2014-04-25 05:29:35 +0000430 if (Extra == nullptr || Extra == I->getOperand(1)) {
Chris Lattnera442f242010-12-13 04:50:38 +0000431 Extra = I->getOperand(1);
432 return LHS;
433 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000434
Chris Lattnera442f242010-12-13 04:50:38 +0000435 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000436 UsedICmps = UsedICmpsBeforeLHS;
Craig Topperf40110f2014-04-25 05:29:35 +0000437 return nullptr;
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000438 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000439
Chris Lattnera442f242010-12-13 04:50:38 +0000440 // If the LHS can't be folded in, but Extra is available and RHS can, try to
441 // use LHS as Extra.
Craig Topperf40110f2014-04-25 05:29:35 +0000442 if (Extra == nullptr || Extra == I->getOperand(0)) {
Chris Lattner79db3572010-12-13 07:41:29 +0000443 Value *OldExtra = Extra;
Chris Lattnera442f242010-12-13 04:50:38 +0000444 Extra = I->getOperand(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000445 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000446 isEQ, UsedICmps))
Chris Lattnera442f242010-12-13 04:50:38 +0000447 return RHS;
Chris Lattner79db3572010-12-13 07:41:29 +0000448 assert(Vals.size() == NumValsBeforeLHS);
449 Extra = OldExtra;
Chris Lattnera442f242010-12-13 04:50:38 +0000450 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000451
Craig Topperf40110f2014-04-25 05:29:35 +0000452 return nullptr;
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000453}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000454
Eli Friedmancb61afb2008-12-16 20:54:32 +0000455static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000456 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000457 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
458 Cond = dyn_cast<Instruction>(SI->getCondition());
459 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
460 if (BI->isConditional())
461 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000462 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
463 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000464 }
465
466 TI->eraseFromParent();
467 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
468}
469
Chris Lattner8e84c122008-11-27 23:25:44 +0000470/// isValueEqualityComparison - Return true if the specified terminator checks
471/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000472Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000473 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000474 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
475 // Do not permit merging of large switch instructions into their
476 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000477 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
478 pred_end(SI->getParent())) <= 128)
479 CV = SI->getCondition();
480 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000481 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000482 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000483 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000484 CV = ICI->getOperand(0);
485
486 // Unwrap any lossless ptrtoint cast.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000487 if (DL && CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000488 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
489 Value *Ptr = PTII->getPointerOperand();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000490 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000491 CV = Ptr;
492 }
493 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000494 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000495}
496
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000497/// GetValueEqualityComparisonCases - Given a value comparison instruction,
498/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000499BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000500GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000501 std::vector<ValueEqualityComparisonCase>
502 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000503 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000504 Cases.reserve(SI->getNumCases());
505 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
506 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
507 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000508 return SI->getDefaultDest();
509 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000510
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000511 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000512 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000513 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
514 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000515 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000516 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000517 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000518}
519
Eric Christopherb65acc62012-07-02 23:22:21 +0000520
521/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
522/// in the list that match the specified block.
523static void EliminateBlockCases(BasicBlock *BB,
524 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000525 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000526}
527
528/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
529/// well.
530static bool
531ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
532 std::vector<ValueEqualityComparisonCase > &C2) {
533 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
534
535 // Make V1 be smaller than V2.
536 if (V1->size() > V2->size())
537 std::swap(V1, V2);
538
539 if (V1->size() == 0) return false;
540 if (V1->size() == 1) {
541 // Just scan V2.
542 ConstantInt *TheVal = (*V1)[0].Value;
543 for (unsigned i = 0, e = V2->size(); i != e; ++i)
544 if (TheVal == (*V2)[i].Value)
545 return true;
546 }
547
548 // Otherwise, just sort both lists and compare element by element.
549 array_pod_sort(V1->begin(), V1->end());
550 array_pod_sort(V2->begin(), V2->end());
551 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
552 while (i1 != e1 && i2 != e2) {
553 if ((*V1)[i1].Value == (*V2)[i2].Value)
554 return true;
555 if ((*V1)[i1].Value < (*V2)[i2].Value)
556 ++i1;
557 else
558 ++i2;
559 }
560 return false;
561}
562
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000563/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
564/// terminator instruction and its block is known to only have a single
565/// predecessor block, check to see if that predecessor is also a value
566/// comparison with the same value, and if that comparison determines the
567/// outcome of this comparison. If so, simplify TI. This does a very limited
568/// form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000569bool SimplifyCFGOpt::
570SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000571 BasicBlock *Pred,
572 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000573 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
574 if (!PredVal) return false; // Not a value comparison in predecessor.
575
576 Value *ThisVal = isValueEqualityComparison(TI);
577 assert(ThisVal && "This isn't a value comparison!!");
578 if (ThisVal != PredVal) return false; // Different predicates.
579
Andrew Trick3051aa12012-08-29 21:46:38 +0000580 // TODO: Preserve branch weight metadata, similarly to how
581 // FoldValueComparisonIntoPredecessors preserves it.
582
Chris Lattner1cca9592005-02-24 06:17:52 +0000583 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000584 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000585 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
586 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000587 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000588
Chris Lattner1cca9592005-02-24 06:17:52 +0000589 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000590 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000591 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000592 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000593
594 // If TI's block is the default block from Pred's comparison, potentially
595 // simplify TI based on this knowledge.
596 if (PredDef == TI->getParent()) {
597 // If we are here, we know that the value is none of those cases listed in
598 // PredCases. If there are any cases in ThisCases that are in PredCases, we
599 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000600 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000601 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000602
Chris Lattner4088e2b2010-12-13 01:47:07 +0000603 if (isa<BranchInst>(TI)) {
604 // Okay, one of the successors of this condbr is dead. Convert it to a
605 // uncond br.
606 assert(ThisCases.size() == 1 && "Branch can only have one case!");
607 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000608 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000609 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000610
Chris Lattner4088e2b2010-12-13 01:47:07 +0000611 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000612 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000613
Chris Lattner4088e2b2010-12-13 01:47:07 +0000614 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
615 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000616
Chris Lattner4088e2b2010-12-13 01:47:07 +0000617 EraseTerminatorInstAndDCECond(TI);
618 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000619 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000620
Chris Lattner4088e2b2010-12-13 01:47:07 +0000621 SwitchInst *SI = cast<SwitchInst>(TI);
622 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000623 SmallPtrSet<Constant*, 16> DeadCases;
624 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
625 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000626
David Greene725c7c32010-01-05 01:26:52 +0000627 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000628 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000629
Manman Ren8691e522012-09-14 21:53:06 +0000630 // Collect branch weights into a vector.
631 SmallVector<uint32_t, 8> Weights;
632 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
633 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
634 if (HasWeight)
635 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
636 ++MD_i) {
637 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
638 assert(CI);
639 Weights.push_back(CI->getValue().getZExtValue());
640 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000641 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
642 --i;
643 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000644 if (HasWeight) {
645 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
646 Weights.pop_back();
647 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000648 i.getCaseSuccessor()->removePredecessor(TI->getParent());
649 SI->removeCase(i);
650 }
651 }
Manman Ren97c18762012-10-11 22:28:34 +0000652 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000653 SI->setMetadata(LLVMContext::MD_prof,
654 MDBuilder(SI->getParent()->getContext()).
655 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000656
657 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000658 return true;
659 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000660
Chris Lattner4088e2b2010-12-13 01:47:07 +0000661 // Otherwise, TI's block must correspond to some matched value. Find out
662 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000663 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000664 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000665 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
666 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000667 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000668 return false; // Cannot handle multiple values coming to this block.
669 TIV = PredCases[i].Value;
670 }
671 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000672
673 // Okay, we found the one constant that our value can be if we get into TI's
674 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000675 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000676 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
677 if (ThisCases[i].Value == TIV) {
678 TheRealDest = ThisCases[i].Dest;
679 break;
680 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000681
682 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000683 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000684
685 // Remove PHI node entries for dead edges.
686 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000687 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
688 if (*SI != CheckEdge)
689 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000690 else
Craig Topperf40110f2014-04-25 05:29:35 +0000691 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000692
693 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000694 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000695 (void) NI;
696
697 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
698 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
699
700 EraseTerminatorInstAndDCECond(TI);
701 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000702}
703
Dale Johannesen7f99d222009-03-12 21:01:11 +0000704namespace {
705 /// ConstantIntOrdering - This class implements a stable ordering of constant
706 /// integers that does not depend on their address. This is important for
707 /// applications that sort ConstantInt's to ensure uniqueness.
708 struct ConstantIntOrdering {
709 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
710 return LHS->getValue().ult(RHS->getValue());
711 }
712 };
713}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000714
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000715static int ConstantIntSortPredicate(ConstantInt *const *P1,
716 ConstantInt *const *P2) {
717 const ConstantInt *LHS = *P1;
718 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000719 if (LHS->getValue().ult(RHS->getValue()))
720 return 1;
721 if (LHS->getValue() == RHS->getValue())
722 return 0;
723 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000724}
725
Andrew Trick3051aa12012-08-29 21:46:38 +0000726static inline bool HasBranchWeights(const Instruction* I) {
727 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
728 if (ProfMD && ProfMD->getOperand(0))
729 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
730 return MDS->getString().equals("branch_weights");
731
732 return false;
733}
734
Manman Ren571d9e42012-09-11 17:43:35 +0000735/// Get Weights of a given TerminatorInst, the default weight is at the front
736/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
737/// metadata.
738static void GetBranchWeights(TerminatorInst *TI,
739 SmallVectorImpl<uint64_t> &Weights) {
740 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
741 assert(MD);
742 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000743 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000744 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000745 }
746
Manman Ren571d9e42012-09-11 17:43:35 +0000747 // If TI is a conditional eq, the default case is the false case,
748 // and the corresponding branch-weight data is at index 2. We swap the
749 // default weight to be the first entry.
750 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
751 assert(Weights.size() == 2);
752 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
753 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
754 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000755 }
756}
757
Manman Renf1cb16e2014-01-27 23:39:03 +0000758/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000759static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000760 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
761 if (Max > UINT_MAX) {
762 unsigned Offset = 32 - countLeadingZeros(Max);
763 for (uint64_t &I : Weights)
764 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000765 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000766}
767
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000768/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
769/// equality comparison instruction (either a switch or a branch on "X == c").
770/// See if any of the predecessors of the terminator block are value comparisons
771/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000772bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
773 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000774 BasicBlock *BB = TI->getParent();
775 Value *CV = isValueEqualityComparison(TI); // CondVal
776 assert(CV && "Not a comparison?");
777 bool Changed = false;
778
Chris Lattner6b39cb92008-02-18 07:42:56 +0000779 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000780 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000781 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000782
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000783 // See if the predecessor is a comparison with the same value.
784 TerminatorInst *PTI = Pred->getTerminator();
785 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
786
787 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
788 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000789 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000790 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
791
Eric Christopherb65acc62012-07-02 23:22:21 +0000792 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000793 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
794
795 // Based on whether the default edge from PTI goes to BB or not, fill in
796 // PredCases and PredDefault with the new switch cases we would like to
797 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000798 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000799
Andrew Trick3051aa12012-08-29 21:46:38 +0000800 // Update the branch weight metadata along the way
801 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000802 bool PredHasWeights = HasBranchWeights(PTI);
803 bool SuccHasWeights = HasBranchWeights(TI);
804
Manman Ren5e5049d2012-09-14 19:05:19 +0000805 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000806 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000807 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000808 if (Weights.size() != 1 + PredCases.size())
809 PredHasWeights = SuccHasWeights = false;
810 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000811 // If there are no predecessor weights but there are successor weights,
812 // populate Weights with 1, which will later be scaled to the sum of
813 // successor's weights
814 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000815
Manman Ren571d9e42012-09-11 17:43:35 +0000816 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000817 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000818 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000819 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000820 if (SuccWeights.size() != 1 + BBCases.size())
821 PredHasWeights = SuccHasWeights = false;
822 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000823 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000824
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000825 if (PredDefault == BB) {
826 // If this is the default destination from PTI, only the edges in TI
827 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000828 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
829 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
830 if (PredCases[i].Dest != BB)
831 PTIHandled.insert(PredCases[i].Value);
832 else {
833 // The default destination is BB, we don't need explicit targets.
834 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000835
Manman Ren571d9e42012-09-11 17:43:35 +0000836 if (PredHasWeights || SuccHasWeights) {
837 // Increase weight for the default case.
838 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000839 std::swap(Weights[i+1], Weights.back());
840 Weights.pop_back();
841 }
842
Eric Christopherb65acc62012-07-02 23:22:21 +0000843 PredCases.pop_back();
844 --i; --e;
845 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000846
Eric Christopherb65acc62012-07-02 23:22:21 +0000847 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000848 if (PredDefault != BBDefault) {
849 PredDefault->removePredecessor(Pred);
850 PredDefault = BBDefault;
851 NewSuccessors.push_back(BBDefault);
852 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000853
Manman Ren571d9e42012-09-11 17:43:35 +0000854 unsigned CasesFromPred = Weights.size();
855 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000856 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
857 if (!PTIHandled.count(BBCases[i].Value) &&
858 BBCases[i].Dest != BBDefault) {
859 PredCases.push_back(BBCases[i]);
860 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000861 if (SuccHasWeights || PredHasWeights) {
862 // The default weight is at index 0, so weight for the ith case
863 // should be at index i+1. Scale the cases from successor by
864 // PredDefaultWeight (Weights[0]).
865 Weights.push_back(Weights[0] * SuccWeights[i+1]);
866 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000867 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000868 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000869
Manman Ren571d9e42012-09-11 17:43:35 +0000870 if (SuccHasWeights || PredHasWeights) {
871 ValidTotalSuccWeight += SuccWeights[0];
872 // Scale the cases from predecessor by ValidTotalSuccWeight.
873 for (unsigned i = 1; i < CasesFromPred; ++i)
874 Weights[i] *= ValidTotalSuccWeight;
875 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
876 Weights[0] *= SuccWeights[0];
877 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000878 } else {
879 // If this is not the default destination from PSI, only the edges
880 // in SI that occur in PSI with a destination of BB will be
881 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000882 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000883 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000884 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
885 if (PredCases[i].Dest == BB) {
886 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000887
888 if (PredHasWeights || SuccHasWeights) {
889 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
890 std::swap(Weights[i+1], Weights.back());
891 Weights.pop_back();
892 }
893
Eric Christopherb65acc62012-07-02 23:22:21 +0000894 std::swap(PredCases[i], PredCases.back());
895 PredCases.pop_back();
896 --i; --e;
897 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000898
899 // Okay, now we know which constants were sent to BB from the
900 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000901 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
902 if (PTIHandled.count(BBCases[i].Value)) {
903 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000904 if (PredHasWeights || SuccHasWeights)
905 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000906 PredCases.push_back(BBCases[i]);
907 NewSuccessors.push_back(BBCases[i].Dest);
908 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
909 }
910
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000911 // If there are any constants vectored to BB that TI doesn't handle,
912 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000913 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000914 PTIHandled.begin(),
915 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000916 if (PredHasWeights || SuccHasWeights)
917 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000918 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000919 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000920 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000921 }
922
923 // Okay, at this point, we know which new successor Pred will get. Make
924 // sure we update the number of entries in the PHI nodes for these
925 // successors.
926 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
927 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
928
Devang Patel58380552011-05-18 20:53:17 +0000929 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000930 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000931 if (CV->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000932 assert(DL && "Cannot switch on pointer without DataLayout");
933 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000934 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000935 }
936
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000937 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000938 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
939 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000940 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +0000941 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
942 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000943
Andrew Trick3051aa12012-08-29 21:46:38 +0000944 if (PredHasWeights || SuccHasWeights) {
945 // Halve the weights if any of them cannot fit in an uint32_t
946 FitWeights(Weights);
947
948 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
949
950 NewSI->setMetadata(LLVMContext::MD_prof,
951 MDBuilder(BB->getContext()).
952 createBranchWeights(MDWeights));
953 }
954
Eli Friedmancb61afb2008-12-16 20:54:32 +0000955 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +0000956
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000957 // Okay, last check. If BB is still a successor of PSI, then we must
958 // have an infinite loop case. If so, add an infinitely looping block
959 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +0000960 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000961 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
962 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000963 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +0000964 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000965 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +0000966 InfLoopBlock = BasicBlock::Create(BB->getContext(),
967 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +0000968 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000969 }
970 NewSI->setSuccessor(i, InfLoopBlock);
971 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000972
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000973 Changed = true;
974 }
975 }
976 return Changed;
977}
978
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000979// isSafeToHoistInvoke - If we would need to insert a select that uses the
980// value of this invoke (comments in HoistThenElseCodeToIf explain why we
981// would need to do this), we can't hoist the invoke, as there is nowhere
982// to put the select in this case.
983static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
984 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000985 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000986 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000987 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000988 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
989 Value *BB1V = PN->getIncomingValueForBlock(BB1);
990 Value *BB2V = PN->getIncomingValueForBlock(BB2);
991 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
992 return false;
993 }
994 }
995 }
996 return true;
997}
998
Chris Lattnerd683bdd2005-08-03 17:59:45 +0000999/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +00001000/// BB2, hoist any common code in the two blocks up into the branch block. The
1001/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Hal Finkela995f922014-07-10 14:41:31 +00001002static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001003 // This does very trivial matching, with limited scanning, to find identical
1004 // instructions in the two blocks. In particular, we don't want to get into
1005 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1006 // such, we currently just scan for obviously identical instructions in an
1007 // identical order.
1008 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1009 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1010
Devang Patelf10e2872009-02-04 00:03:08 +00001011 BasicBlock::iterator BB1_Itr = BB1->begin();
1012 BasicBlock::iterator BB2_Itr = BB2->begin();
1013
1014 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001015 // Skip debug info if it is not identical.
1016 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1017 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1018 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1019 while (isa<DbgInfoIntrinsic>(I1))
1020 I1 = BB1_Itr++;
1021 while (isa<DbgInfoIntrinsic>(I2))
1022 I2 = BB2_Itr++;
1023 }
Devang Patele48ddf82011-04-07 00:30:15 +00001024 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001025 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001026 return false;
1027
Chris Lattner389cfac2004-11-30 00:29:14 +00001028 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001029
David Majnemerc82f27a2013-06-03 20:43:12 +00001030 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001031 do {
1032 // If we are hoisting the terminator instruction, don't move one (making a
1033 // broken BB), instead clone it, and remove BI.
1034 if (isa<TerminatorInst>(I1))
1035 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001036
Chris Lattner389cfac2004-11-30 00:29:14 +00001037 // For a normal instruction, we just move one to right before the branch,
1038 // then replace all uses of the other with the first. Finally, we remove
1039 // the now redundant second instruction.
1040 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1041 if (!I2->use_empty())
1042 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001043 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001044 unsigned KnownIDs[] = {
1045 LLVMContext::MD_tbaa,
1046 LLVMContext::MD_range,
1047 LLVMContext::MD_fpmath,
1048 LLVMContext::MD_invariant_load
1049 };
1050 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001051 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001052 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001053
Devang Patelf10e2872009-02-04 00:03:08 +00001054 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001055 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001056 // Skip debug info if it is not identical.
1057 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1058 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1059 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1060 while (isa<DbgInfoIntrinsic>(I1))
1061 I1 = BB1_Itr++;
1062 while (isa<DbgInfoIntrinsic>(I2))
1063 I2 = BB2_Itr++;
1064 }
Devang Patele48ddf82011-04-07 00:30:15 +00001065 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001066
1067 return true;
1068
1069HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001070 // It may not be possible to hoist an invoke.
1071 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001072 return Changed;
1073
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001074 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001075 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001076 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001077 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1078 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1079 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1080 if (BB1V == BB2V)
1081 continue;
1082
Hal Finkela995f922014-07-10 14:41:31 +00001083 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001084 return Changed;
Hal Finkela995f922014-07-10 14:41:31 +00001085 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001086 return Changed;
1087 }
1088 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001089
Chris Lattner389cfac2004-11-30 00:29:14 +00001090 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001091 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001092 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001093 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001094 I1->replaceAllUsesWith(NT);
1095 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001096 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001097 }
1098
Devang Patel1407fb42011-05-19 20:52:46 +00001099 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001100 // Hoisting one of the terminators from our successor is a great thing.
1101 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1102 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1103 // nodes, so we insert select instruction to compute the final result.
1104 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001105 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001106 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001107 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001108 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001109 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1110 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001111 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001112
Chris Lattner4088e2b2010-12-13 01:47:07 +00001113 // These values do not agree. Insert a select instruction before NT
1114 // that determines the right value.
1115 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001116 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001117 SI = cast<SelectInst>
1118 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1119 BB1V->getName()+"."+BB2V->getName()));
1120
Chris Lattner4088e2b2010-12-13 01:47:07 +00001121 // Make the PHI node use the select for all incoming values for BB1/BB2
1122 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1123 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1124 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001125 }
1126 }
1127
1128 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001129 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1130 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001131
Eli Friedmancb61afb2008-12-16 20:54:32 +00001132 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001133 return true;
1134}
1135
Manman Ren93ab6492012-09-20 22:37:36 +00001136/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1137/// check whether BBEnd has only two predecessors and the other predecessor
1138/// ends with an unconditional branch. If it is true, sink any common code
1139/// in the two predecessors to BBEnd.
1140static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1141 assert(BI1->isUnconditional());
1142 BasicBlock *BB1 = BI1->getParent();
1143 BasicBlock *BBEnd = BI1->getSuccessor(0);
1144
1145 // Check that BBEnd has two predecessors and the other predecessor ends with
1146 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001147 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1148 BasicBlock *Pred0 = *PI++;
1149 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001150 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001151 BasicBlock *Pred1 = *PI++;
1152 if (PI != PE) // More than two predecessors.
1153 return false;
1154 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001155 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1156 if (!BI2 || !BI2->isUnconditional())
1157 return false;
1158
1159 // Gather the PHI nodes in BBEnd.
1160 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
Craig Topperf40110f2014-04-25 05:29:35 +00001161 Instruction *FirstNonPhiInBBEnd = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001162 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1163 I != E; ++I) {
1164 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1165 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001166 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Manman Ren93ab6492012-09-20 22:37:36 +00001167 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1168 } else {
1169 FirstNonPhiInBBEnd = &*I;
1170 break;
1171 }
1172 }
1173 if (!FirstNonPhiInBBEnd)
1174 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001175
Manman Ren93ab6492012-09-20 22:37:36 +00001176
1177 // This does very trivial matching, with limited scanning, to find identical
1178 // instructions in the two blocks. We scan backward for obviously identical
1179 // instructions in an identical order.
1180 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1181 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1182 RE2 = BB2->getInstList().rend();
1183 // Skip debug info.
1184 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1185 if (RI1 == RE1)
1186 return false;
1187 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1188 if (RI2 == RE2)
1189 return false;
1190 // Skip the unconditional branches.
1191 ++RI1;
1192 ++RI2;
1193
1194 bool Changed = false;
1195 while (RI1 != RE1 && RI2 != RE2) {
1196 // Skip debug info.
1197 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1198 if (RI1 == RE1)
1199 return Changed;
1200 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1201 if (RI2 == RE2)
1202 return Changed;
1203
1204 Instruction *I1 = &*RI1, *I2 = &*RI2;
1205 // I1 and I2 should have a single use in the same PHI node, and they
1206 // perform the same operation.
1207 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1208 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1209 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1210 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1211 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1212 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1213 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1214 !I1->hasOneUse() || !I2->hasOneUse() ||
1215 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1216 MapValueFromBB1ToBB2[I1].first != I2)
1217 return Changed;
1218
1219 // Check whether we should swap the operands of ICmpInst.
1220 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1221 bool SwapOpnds = false;
1222 if (ICmp1 && ICmp2 &&
1223 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1224 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1225 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1226 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1227 ICmp2->swapOperands();
1228 SwapOpnds = true;
1229 }
1230 if (!I1->isSameOperationAs(I2)) {
1231 if (SwapOpnds)
1232 ICmp2->swapOperands();
1233 return Changed;
1234 }
1235
1236 // The operands should be either the same or they need to be generated
1237 // with a PHI node after sinking. We only handle the case where there is
1238 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001239 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001240 unsigned Op1Idx = 0;
1241 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1242 if (I1->getOperand(I) == I2->getOperand(I))
1243 continue;
1244 // Early exit if we have more-than one pair of different operands or
1245 // the different operand is already in MapValueFromBB1ToBB2.
1246 // Early exit if we need a PHI node to replace a constant.
1247 if (DifferentOp1 ||
1248 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1249 MapValueFromBB1ToBB2.end() ||
1250 isa<Constant>(I1->getOperand(I)) ||
1251 isa<Constant>(I2->getOperand(I))) {
1252 // If we can't sink the instructions, undo the swapping.
1253 if (SwapOpnds)
1254 ICmp2->swapOperands();
1255 return Changed;
1256 }
1257 DifferentOp1 = I1->getOperand(I);
1258 Op1Idx = I;
1259 DifferentOp2 = I2->getOperand(I);
1260 }
1261
1262 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1263 // remove (I1, I2) from MapValueFromBB1ToBB2.
1264 if (DifferentOp1) {
1265 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1266 DifferentOp1->getName() + ".sink",
1267 BBEnd->begin());
1268 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1269 // I1 should use NewPN instead of DifferentOp1.
1270 I1->setOperand(Op1Idx, NewPN);
1271 NewPN->addIncoming(DifferentOp1, BB1);
1272 NewPN->addIncoming(DifferentOp2, BB2);
1273 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1274 }
1275 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1276 MapValueFromBB1ToBB2.erase(I1);
1277
1278 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1279 DEBUG(dbgs() << " " << *I2 << "\n";);
1280 // We need to update RE1 and RE2 if we are going to sink the first
1281 // instruction in the basic block down.
1282 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1283 // Sink the instruction.
1284 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1285 if (!OldPN->use_empty())
1286 OldPN->replaceAllUsesWith(I1);
1287 OldPN->eraseFromParent();
1288
1289 if (!I2->use_empty())
1290 I2->replaceAllUsesWith(I1);
1291 I1->intersectOptionalDataWith(I2);
1292 I2->eraseFromParent();
1293
1294 if (UpdateRE1)
1295 RE1 = BB1->getInstList().rend();
1296 if (UpdateRE2)
1297 RE2 = BB2->getInstList().rend();
1298 FirstNonPhiInBBEnd = I1;
1299 NumSinkCommons++;
1300 Changed = true;
1301 }
1302 return Changed;
1303}
1304
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001305/// \brief Determine if we can hoist sink a sole store instruction out of a
1306/// conditional block.
1307///
1308/// We are looking for code like the following:
1309/// BrBB:
1310/// store i32 %add, i32* %arrayidx2
1311/// ... // No other stores or function calls (we could be calling a memory
1312/// ... // function).
1313/// %cmp = icmp ult %x, %y
1314/// br i1 %cmp, label %EndBB, label %ThenBB
1315/// ThenBB:
1316/// store i32 %add5, i32* %arrayidx2
1317/// br label EndBB
1318/// EndBB:
1319/// ...
1320/// We are going to transform this into:
1321/// BrBB:
1322/// store i32 %add, i32* %arrayidx2
1323/// ... //
1324/// %cmp = icmp ult %x, %y
1325/// %add.add5 = select i1 %cmp, i32 %add, %add5
1326/// store i32 %add.add5, i32* %arrayidx2
1327/// ...
1328///
1329/// \return The pointer to the value of the previous store if the store can be
1330/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001331static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1332 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001333 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1334 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001335 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001336
1337 // Volatile or atomic.
1338 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001339 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001340
1341 Value *StorePtr = StoreToHoist->getPointerOperand();
1342
1343 // Look for a store to the same pointer in BrBB.
1344 unsigned MaxNumInstToLookAt = 10;
1345 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1346 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1347 Instruction *CurI = &*RI;
1348
1349 // Could be calling an instruction that effects memory like free().
1350 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001351 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001352
1353 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1354 // Found the previous store make sure it stores to the same location.
1355 if (SI && SI->getPointerOperand() == StorePtr)
1356 // Found the previous store, return its value operand.
1357 return SI->getValueOperand();
1358 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001359 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001360 }
1361
Craig Topperf40110f2014-04-25 05:29:35 +00001362 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001363}
1364
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001365/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001366///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001367/// Note that this is a very risky transform currently. Speculating
1368/// instructions like this is most often not desirable. Instead, there is an MI
1369/// pass which can do it with full awareness of the resource constraints.
1370/// However, some cases are "obvious" and we should do directly. An example of
1371/// this is speculating a single, reasonably cheap instruction.
1372///
1373/// There is only one distinct advantage to flattening the CFG at the IR level:
1374/// it makes very common but simplistic optimizations such as are common in
1375/// instcombine and the DAG combiner more powerful by removing CFG edges and
1376/// modeling their effects with easier to reason about SSA value graphs.
1377///
1378///
1379/// An illustration of this transform is turning this IR:
1380/// \code
1381/// BB:
1382/// %cmp = icmp ult %x, %y
1383/// br i1 %cmp, label %EndBB, label %ThenBB
1384/// ThenBB:
1385/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001386/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001387/// EndBB:
1388/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1389/// ...
1390/// \endcode
1391///
1392/// Into this IR:
1393/// \code
1394/// BB:
1395/// %cmp = icmp ult %x, %y
1396/// %sub = sub %x, %y
1397/// %cond = select i1 %cmp, 0, %sub
1398/// ...
1399/// \endcode
1400///
1401/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001402static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1403 const DataLayout *DL) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001404 // Be conservative for now. FP select instruction can often be expensive.
1405 Value *BrCond = BI->getCondition();
1406 if (isa<FCmpInst>(BrCond))
1407 return false;
1408
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001409 BasicBlock *BB = BI->getParent();
1410 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1411
1412 // If ThenBB is actually on the false edge of the conditional branch, remember
1413 // to swap the select operands later.
1414 bool Invert = false;
1415 if (ThenBB != BI->getSuccessor(0)) {
1416 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1417 Invert = true;
1418 }
1419 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1420
Chandler Carruthceff2222013-01-25 05:40:09 +00001421 // Keep a count of how many times instructions are used within CondBB when
1422 // they are candidates for sinking into CondBB. Specifically:
1423 // - They are defined in BB, and
1424 // - They have no side effects, and
1425 // - All of their uses are in CondBB.
1426 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1427
Chandler Carruth7481ca82013-01-24 11:52:58 +00001428 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001429 Value *SpeculatedStoreValue = nullptr;
1430 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001431 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001432 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001433 BBI != BBE; ++BBI) {
1434 Instruction *I = BBI;
1435 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001436 if (isa<DbgInfoIntrinsic>(I))
1437 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001438
Chandler Carruth7481ca82013-01-24 11:52:58 +00001439 // Only speculatively execution a single instruction (not counting the
1440 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001441 ++SpeculationCost;
1442 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001443 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001444
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001445 // Don't hoist the instruction if it's unsafe or expensive.
Hal Finkela995f922014-07-10 14:41:31 +00001446 if (!isSafeToSpeculativelyExecute(I, DL) &&
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001447 !(HoistCondStores &&
1448 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1449 EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001450 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001451 if (!SpeculatedStoreValue &&
Hal Finkela995f922014-07-10 14:41:31 +00001452 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001453 return false;
1454
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001455 // Store the store speculation candidate.
1456 if (SpeculatedStoreValue)
1457 SpeculatedStore = cast<StoreInst>(I);
1458
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001459 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001460 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001461 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001462 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001463 i != e; ++i) {
1464 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001465 if (!OpI || OpI->getParent() != BB ||
1466 OpI->mayHaveSideEffects())
1467 continue; // Not a candidate for sinking.
1468
1469 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001470 }
1471 }
Evan Cheng89200c92008-06-07 08:52:29 +00001472
Chandler Carruthceff2222013-01-25 05:40:09 +00001473 // Consider any sink candidates which are only used in CondBB as costs for
1474 // speculation. Note, while we iterate over a DenseMap here, we are summing
1475 // and so iteration order isn't significant.
1476 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1477 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1478 I != E; ++I)
1479 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001480 ++SpeculationCost;
1481 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001482 return false;
1483 }
1484
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001485 // Check that the PHI nodes can be converted to selects.
1486 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001487 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001488 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001489 Value *OrigV = PN->getIncomingValueForBlock(BB);
1490 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001491
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001492 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001493 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001494 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001495 continue;
1496
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001497 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001498 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1499 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1500 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001501 continue; // Known safe and cheap.
1502
Hal Finkela995f922014-07-10 14:41:31 +00001503 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1504 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001505 return false;
Hal Finkela995f922014-07-10 14:41:31 +00001506 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1507 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001508 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
Chandler Carruth8a210052013-01-24 11:53:01 +00001509 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001510
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001511 // Account for the cost of an unfolded ConstantExpr which could end up
1512 // getting expanded into Instructions.
1513 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001514 // constant expression.
1515 ++SpeculationCost;
1516 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001517 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001518 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001519
1520 // If there are no PHIs to process, bail early. This helps ensure idempotence
1521 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001522 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001523 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001524
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001525 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001526 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001527
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001528 // Insert a select of the value of the speculated store.
1529 if (SpeculatedStoreValue) {
1530 IRBuilder<true, NoFolder> Builder(BI);
1531 Value *TrueV = SpeculatedStore->getValueOperand();
1532 Value *FalseV = SpeculatedStoreValue;
1533 if (Invert)
1534 std::swap(TrueV, FalseV);
1535 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1536 "." + FalseV->getName());
1537 SpeculatedStore->setOperand(0, S);
1538 }
1539
Chandler Carruth7481ca82013-01-24 11:52:58 +00001540 // Hoist the instructions.
1541 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001542 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001543
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001544 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001545 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001546 for (BasicBlock::iterator I = EndBB->begin();
1547 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1548 unsigned OrigI = PN->getBasicBlockIndex(BB);
1549 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1550 Value *OrigV = PN->getIncomingValue(OrigI);
1551 Value *ThenV = PN->getIncomingValue(ThenI);
1552
1553 // Skip PHIs which are trivial.
1554 if (OrigV == ThenV)
1555 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001556
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001557 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001558 // false value is the preexisting value. Swap them if the branch
1559 // destinations were inverted.
1560 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001561 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001562 std::swap(TrueV, FalseV);
1563 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1564 TrueV->getName() + "." + FalseV->getName());
1565 PN->setIncomingValue(OrigI, V);
1566 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001567 }
1568
Evan Cheng89553cc2008-06-12 21:15:59 +00001569 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001570 return true;
1571}
1572
Tom Stellarde1631dd2013-10-21 20:07:30 +00001573/// \returns True if this block contains a CallInst with the NoDuplicate
1574/// attribute.
1575static bool HasNoDuplicateCall(const BasicBlock *BB) {
1576 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1577 const CallInst *CI = dyn_cast<CallInst>(I);
1578 if (!CI)
1579 continue;
1580 if (CI->cannotDuplicate())
1581 return true;
1582 }
1583 return false;
1584}
1585
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001586/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1587/// across this block.
1588static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1589 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001590 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001591
Devang Patel84fceff2009-03-10 18:00:05 +00001592 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001593 if (isa<DbgInfoIntrinsic>(BBI))
1594 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001595 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001596 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001597
Dale Johannesened6f5a82009-03-12 23:18:09 +00001598 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001599 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001600 for (User *U : BBI->users()) {
1601 Instruction *UI = cast<Instruction>(U);
1602 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001603 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001604
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001605 // Looks ok, continue checking.
1606 }
Chris Lattner6c701062005-09-20 01:48:40 +00001607
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001608 return true;
1609}
1610
Chris Lattner748f9032005-09-19 23:49:37 +00001611/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1612/// that is defined in the same block as the branch and if any PHI entries are
1613/// constants, thread edges corresponding to that entry to be branches to their
1614/// ultimate destination.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001615static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001616 BasicBlock *BB = BI->getParent();
1617 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001618 // NOTE: we currently cannot transform this case if the PHI node is used
1619 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001620 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1621 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001622
Chris Lattner748f9032005-09-19 23:49:37 +00001623 // Degenerate case of a single entry PHI.
1624 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001625 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001626 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001627 }
1628
1629 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001630 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001631
Tom Stellarde1631dd2013-10-21 20:07:30 +00001632 if (HasNoDuplicateCall(BB)) return false;
1633
Chris Lattner748f9032005-09-19 23:49:37 +00001634 // Okay, this is a simple enough basic block. See if any phi values are
1635 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001636 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001637 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001638 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001639
Chris Lattner4088e2b2010-12-13 01:47:07 +00001640 // Okay, we now know that all edges from PredBB should be revectored to
1641 // branch to RealDest.
1642 BasicBlock *PredBB = PN->getIncomingBlock(i);
1643 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001644
Chris Lattner4088e2b2010-12-13 01:47:07 +00001645 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001646 // Skip if the predecessor's terminator is an indirect branch.
1647 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001648
Chris Lattner4088e2b2010-12-13 01:47:07 +00001649 // The dest block might have PHI nodes, other predecessors and other
1650 // difficult cases. Instead of being smart about this, just insert a new
1651 // block that jumps to the destination block, effectively splitting
1652 // the edge we are about to create.
1653 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1654 RealDest->getName()+".critedge",
1655 RealDest->getParent(), RealDest);
1656 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001657
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001658 // Update PHI nodes.
1659 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001660
1661 // BB may have instructions that are being threaded over. Clone these
1662 // instructions into EdgeBB. We know that there will be no uses of the
1663 // cloned instructions outside of EdgeBB.
1664 BasicBlock::iterator InsertPt = EdgeBB->begin();
1665 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1666 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1667 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1668 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1669 continue;
1670 }
1671 // Clone the instruction.
1672 Instruction *N = BBI->clone();
1673 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001674
Chris Lattner4088e2b2010-12-13 01:47:07 +00001675 // Update operands due to translation.
1676 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1677 i != e; ++i) {
1678 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1679 if (PI != TranslateMap.end())
1680 *i = PI->second;
1681 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001682
Chris Lattner4088e2b2010-12-13 01:47:07 +00001683 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001684 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001685 TranslateMap[BBI] = V;
1686 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001687 } else {
1688 // Insert the new instruction into its new home.
1689 EdgeBB->getInstList().insert(InsertPt, N);
1690 if (!BBI->use_empty())
1691 TranslateMap[BBI] = N;
1692 }
1693 }
1694
1695 // Loop over all of the edges from PredBB to BB, changing them to branch
1696 // to EdgeBB instead.
1697 TerminatorInst *PredBBTI = PredBB->getTerminator();
1698 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1699 if (PredBBTI->getSuccessor(i) == BB) {
1700 BB->removePredecessor(PredBB);
1701 PredBBTI->setSuccessor(i, EdgeBB);
1702 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001703
Chris Lattner4088e2b2010-12-13 01:47:07 +00001704 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001705 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001706 }
Chris Lattner748f9032005-09-19 23:49:37 +00001707
1708 return false;
1709}
1710
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001711/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1712/// PHI node, see if we can eliminate it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001713static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001714 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1715 // statement", which has a very simple dominance structure. Basically, we
1716 // are trying to find the condition that is being branched on, which
1717 // subsequently causes this merge to happen. We really want control
1718 // dependence information for this check, but simplifycfg can't keep it up
1719 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001720 BasicBlock *BB = PN->getParent();
1721 BasicBlock *IfTrue, *IfFalse;
1722 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001723 if (!IfCond ||
1724 // Don't bother if the branch will be constant folded trivially.
1725 isa<ConstantInt>(IfCond))
1726 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001727
Chris Lattner95adf8f12006-11-18 19:19:36 +00001728 // Okay, we found that we can merge this two-entry phi node into a select.
1729 // Doing so would require us to fold *all* two entry phi nodes in this block.
1730 // At some point this becomes non-profitable (particularly if the target
1731 // doesn't support cmov's). Only do this transformation if there are two or
1732 // fewer PHI nodes in this block.
1733 unsigned NumPhis = 0;
1734 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1735 if (NumPhis > 2)
1736 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001737
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001738 // Loop over the PHI's seeing if we can promote them all to select
1739 // instructions. While we are at it, keep track of the instructions
1740 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001741 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001742 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1743 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001744
Chris Lattner7499b452010-12-14 08:46:09 +00001745 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1746 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001747 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001748 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001749 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001750 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001751 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001752
Peter Collingbournee3511e12011-04-29 18:47:31 +00001753 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001754 MaxCostVal0, DL) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001755 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001756 MaxCostVal1, DL))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001757 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001758 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001759
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001760 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001761 // we ran out of PHIs then we simplified them all.
1762 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001763 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001764
Chris Lattner7499b452010-12-14 08:46:09 +00001765 // Don't fold i1 branches on PHIs which contain binary operators. These can
1766 // often be turned into switches and other things.
1767 if (PN->getType()->isIntegerTy(1) &&
1768 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1769 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1770 isa<BinaryOperator>(IfCond)))
1771 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001772
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001773 // If we all PHI nodes are promotable, check to make sure that all
1774 // instructions in the predecessor blocks can be promoted as well. If
1775 // not, we won't be able to get rid of the control flow, so it's not
1776 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001777 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001778 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1779 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1780 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001781 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001782 } else {
1783 DomBlock = *pred_begin(IfBlock1);
1784 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001785 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001786 // This is not an aggressive instruction that we can promote.
1787 // Because of this, we won't be able to get rid of the control
1788 // flow, so the xform is not worth it.
1789 return false;
1790 }
1791 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001792
Chris Lattner9ac168d2010-12-14 07:41:39 +00001793 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001794 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001795 } else {
1796 DomBlock = *pred_begin(IfBlock2);
1797 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001798 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001799 // This is not an aggressive instruction that we can promote.
1800 // Because of this, we won't be able to get rid of the control
1801 // flow, so the xform is not worth it.
1802 return false;
1803 }
1804 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001805
Chris Lattner9fd838d2010-12-14 07:23:10 +00001806 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001807 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001808
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001809 // If we can still promote the PHI nodes after this gauntlet of tests,
1810 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001811 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001812 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001813
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001814 // Move all 'aggressive' instructions, which are defined in the
1815 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001816 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001817 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001818 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001819 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001820 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001821 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001822 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001823 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001824
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001825 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1826 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001827 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1828 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001829
1830 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001831 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001832 PN->replaceAllUsesWith(NV);
1833 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001834 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001835 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001836
Chris Lattner335f0e42010-12-14 08:01:53 +00001837 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1838 // has been flattened. Change DomBlock to jump directly to our new block to
1839 // avoid other simplifycfg's kicking in on the diamond.
1840 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001841 Builder.SetInsertPoint(OldTI);
1842 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001843 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001844 return true;
1845}
Chris Lattner748f9032005-09-19 23:49:37 +00001846
Chris Lattner86bbf332008-04-24 00:01:19 +00001847/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1848/// to two returning blocks, try to merge them together into one return,
1849/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001850static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001851 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001852 assert(BI->isConditional() && "Must be a conditional branch");
1853 BasicBlock *TrueSucc = BI->getSuccessor(0);
1854 BasicBlock *FalseSucc = BI->getSuccessor(1);
1855 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1856 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001857
Chris Lattner86bbf332008-04-24 00:01:19 +00001858 // Check to ensure both blocks are empty (just a return) or optionally empty
1859 // with PHI nodes. If there are other instructions, merging would cause extra
1860 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001861 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001862 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001863 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001864 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001865
Devang Pateldd14e0f2011-05-18 21:33:11 +00001866 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001867 // Okay, we found a branch that is going to two return nodes. If
1868 // there is no return value for this function, just change the
1869 // branch into a return.
1870 if (FalseRet->getNumOperands() == 0) {
1871 TrueSucc->removePredecessor(BI->getParent());
1872 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001873 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001874 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001875 return true;
1876 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001877
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001878 // Otherwise, figure out what the true and false return values are
1879 // so we can insert a new select instruction.
1880 Value *TrueValue = TrueRet->getReturnValue();
1881 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001882
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001883 // Unwrap any PHI nodes in the return blocks.
1884 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1885 if (TVPN->getParent() == TrueSucc)
1886 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1887 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1888 if (FVPN->getParent() == FalseSucc)
1889 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001890
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001891 // In order for this transformation to be safe, we must be able to
1892 // unconditionally execute both operands to the return. This is
1893 // normally the case, but we could have a potentially-trapping
1894 // constant expression that prevents this transformation from being
1895 // safe.
1896 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1897 if (TCV->canTrap())
1898 return false;
1899 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1900 if (FCV->canTrap())
1901 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001902
Chris Lattner86bbf332008-04-24 00:01:19 +00001903 // Okay, we collected all the mapped values and checked them for sanity, and
1904 // defined to really do this transformation. First, update the CFG.
1905 TrueSucc->removePredecessor(BI->getParent());
1906 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001907
Chris Lattner86bbf332008-04-24 00:01:19 +00001908 // Insert select instructions where needed.
1909 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001910 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001911 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001912 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1913 } else if (isa<UndefValue>(TrueValue)) {
1914 TrueValue = FalseValue;
1915 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001916 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1917 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001918 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001919 }
1920
Andrew Trickf3cf1932012-08-29 21:46:36 +00001921 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001922 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1923
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00001924 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001925
David Greene725c7c32010-01-05 01:26:52 +00001926 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00001927 << "\n " << *BI << "NewRet = " << *RI
1928 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001929
Eli Friedmancb61afb2008-12-16 20:54:32 +00001930 EraseTerminatorInstAndDCECond(BI);
1931
Chris Lattner86bbf332008-04-24 00:01:19 +00001932 return true;
1933}
1934
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001935/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1936/// probabilities of the branch taking each edge. Fills in the two APInt
1937/// parameters and return true, or returns false if no or invalid metadata was
1938/// found.
1939static bool ExtractBranchMetadata(BranchInst *BI,
Manman Renbfb9d432012-09-15 00:39:57 +00001940 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001941 assert(BI->isConditional() &&
1942 "Looking for probabilities on unconditional branch?");
1943 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky398255e2011-12-27 18:27:22 +00001944 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001945 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1946 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky398255e2011-12-27 18:27:22 +00001947 if (!CITrue || !CIFalse) return false;
Manman Renbfb9d432012-09-15 00:39:57 +00001948 ProbTrue = CITrue->getValue().getZExtValue();
1949 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001950 return true;
1951}
1952
Manman Rend33f4ef2012-06-13 05:43:29 +00001953/// checkCSEInPredecessor - Return true if the given instruction is available
1954/// in its predecessor block. If yes, the instruction will be removed.
1955///
Benjamin Kramerabbfe692012-07-13 13:25:15 +00001956static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00001957 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1958 return false;
1959 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1960 Instruction *PBI = &*I;
1961 // Check whether Inst and PBI generate the same value.
1962 if (Inst->isIdenticalTo(PBI)) {
1963 Inst->replaceAllUsesWith(PBI);
1964 Inst->eraseFromParent();
1965 return true;
1966 }
1967 }
1968 return false;
1969}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00001970
Chris Lattner7d4cdae2011-04-11 23:24:57 +00001971/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1972/// predecessor branches to us and one of our successors, fold the block into
1973/// the predecessor and use logical operations to pick the right destination.
Hal Finkela995f922014-07-10 14:41:31 +00001974bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001975 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00001976
Craig Topperf40110f2014-04-25 05:29:35 +00001977 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00001978 if (BI->isConditional())
1979 Cond = dyn_cast<Instruction>(BI->getCondition());
1980 else {
1981 // For unconditional branch, check for a simple CFG pattern, where
1982 // BB has a single predecessor and BB's successor is also its predecessor's
1983 // successor. If such pattern exisits, check for CSE between BB and its
1984 // predecessor.
1985 if (BasicBlock *PB = BB->getSinglePredecessor())
1986 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1987 if (PBI->isConditional() &&
1988 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1989 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1990 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1991 I != E; ) {
1992 Instruction *Curr = I++;
1993 if (isa<CmpInst>(Curr)) {
1994 Cond = Curr;
1995 break;
1996 }
1997 // Quit if we can't remove this instruction.
1998 if (!checkCSEInPredecessor(Curr, PB))
1999 return false;
2000 }
2001 }
2002
Craig Topperf40110f2014-04-25 05:29:35 +00002003 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002004 return false;
2005 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002006
Craig Topperf40110f2014-04-25 05:29:35 +00002007 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2008 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002009 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002010
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002011 // Only allow this if the condition is a simple instruction that can be
2012 // executed unconditionally. It must be in the same block as the branch, and
2013 // must be at the front of the block.
Devang Patel916fdce2009-02-04 21:39:48 +00002014 BasicBlock::iterator FrontIt = BB->front();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002015
Devang Patel916fdce2009-02-04 21:39:48 +00002016 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002017 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00002018
Owen Anderson2cfe9132010-07-14 19:52:16 +00002019 // Allow a single instruction to be hoisted in addition to the compare
2020 // that feeds the branch. We later ensure that any values that _it_ uses
2021 // were also live in the predecessor, so that we don't unnecessarily create
2022 // register pressure or inhibit out-of-order execution.
Craig Topperf40110f2014-04-25 05:29:35 +00002023 Instruction *BonusInst = nullptr;
Owen Anderson2cfe9132010-07-14 19:52:16 +00002024 if (&*FrontIt != Cond &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002025 FrontIt->hasOneUse() && FrontIt->user_back() == Cond &&
Hal Finkela995f922014-07-10 14:41:31 +00002026 isSafeToSpeculativelyExecute(FrontIt, DL)) {
Owen Anderson2cfe9132010-07-14 19:52:16 +00002027 BonusInst = &*FrontIt;
2028 ++FrontIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002029
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002030 // Ignore dbg intrinsics.
2031 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Devang Patelbc3d8b22011-04-07 23:11:25 +00002032 }
2033
Owen Anderson2cfe9132010-07-14 19:52:16 +00002034 // Only a single bonus inst is allowed.
2035 if (&*FrontIt != Cond)
2036 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002037
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002038 // Make sure the instruction after the condition is the cond branch.
2039 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002040
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002041 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002042 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002043
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002044 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002045 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002046
2047 // Cond is known to be a compare or binary operator. Check to make sure that
2048 // neither operand is a potentially-trapping constant expression.
2049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2050 if (CE->canTrap())
2051 return false;
2052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2053 if (CE->canTrap())
2054 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002055
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002056 // Finally, don't infinitely unroll conditional loops.
2057 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002058 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002059 if (TrueDest == BB || FalseDest == BB)
2060 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002061
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002062 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2063 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002064 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002065
Chris Lattner80b03a12008-07-13 22:23:11 +00002066 // Check that we have two conditional branches. If there is a PHI node in
2067 // the common successor, verify that the same value flows in from both
2068 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002069 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002070 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002071 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002072 !SafeToMergeTerminators(BI, PBI)) ||
2073 (!BI->isConditional() &&
2074 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002075 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002076
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002077 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002078 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002079 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002080
Manman Rend33f4ef2012-06-13 05:43:29 +00002081 if (BI->isConditional()) {
2082 if (PBI->getSuccessor(0) == TrueDest)
2083 Opc = Instruction::Or;
2084 else if (PBI->getSuccessor(1) == FalseDest)
2085 Opc = Instruction::And;
2086 else if (PBI->getSuccessor(0) == FalseDest)
2087 Opc = Instruction::And, InvertPredCond = true;
2088 else if (PBI->getSuccessor(1) == TrueDest)
2089 Opc = Instruction::Or, InvertPredCond = true;
2090 else
2091 continue;
2092 } else {
2093 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2094 continue;
2095 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002096
Owen Anderson2cfe9132010-07-14 19:52:16 +00002097 // Ensure that any values used in the bonus instruction are also used
2098 // by the terminator of the predecessor. This means that those values
Andrew Trickf3cf1932012-08-29 21:46:36 +00002099 // must already have been resolved, so we won't be inhibiting the
Nadav Rotem53d32212013-11-12 22:37:16 +00002100 // out-of-order core by speculating them earlier. We also allow
2101 // instructions that are used by the terminator's condition because it
2102 // exposes more merging opportunities.
2103 bool UsedByBranch = (BonusInst && BonusInst->hasOneUse() &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002104 BonusInst->user_back() == Cond);
Nadav Rotem53d32212013-11-12 22:37:16 +00002105
2106 if (BonusInst && !UsedByBranch) {
Owen Anderson2cfe9132010-07-14 19:52:16 +00002107 // Collect the values used by the bonus inst
2108 SmallPtrSet<Value*, 4> UsedValues;
2109 for (Instruction::op_iterator OI = BonusInst->op_begin(),
2110 OE = BonusInst->op_end(); OI != OE; ++OI) {
Nick Lewyckye87d54c2011-12-26 20:37:40 +00002111 Value *V = *OI;
Nadav Rotem5ba1c6c2013-11-10 04:13:31 +00002112 if (!isa<Constant>(V) && !isa<Argument>(V))
Owen Anderson2cfe9132010-07-14 19:52:16 +00002113 UsedValues.insert(V);
2114 }
2115
2116 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2117 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002118
Owen Anderson2cfe9132010-07-14 19:52:16 +00002119 // Walk up to four levels back up the use-def chain of the predecessor's
2120 // terminator to see if all those values were used. The choice of four
2121 // levels is arbitrary, to provide a compile-time-cost bound.
2122 while (!Worklist.empty()) {
2123 std::pair<Value*, unsigned> Pair = Worklist.back();
2124 Worklist.pop_back();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002125
Owen Anderson2cfe9132010-07-14 19:52:16 +00002126 if (Pair.second >= 4) continue;
2127 UsedValues.erase(Pair.first);
2128 if (UsedValues.empty()) break;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002129
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002130 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Anderson2cfe9132010-07-14 19:52:16 +00002131 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2132 OI != OE; ++OI)
2133 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002134 }
Owen Anderson2cfe9132010-07-14 19:52:16 +00002135 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002136
Owen Anderson2cfe9132010-07-14 19:52:16 +00002137 if (!UsedValues.empty()) return false;
2138 }
Chris Lattner55eaae12008-07-13 21:20:19 +00002139
David Greene725c7c32010-01-05 01:26:52 +00002140 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002141 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002142
Chris Lattner55eaae12008-07-13 21:20:19 +00002143 // If we need to invert the condition in the pred block to match, do so now.
2144 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002145 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002146
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002147 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2148 CmpInst *CI = cast<CmpInst>(NewCond);
2149 CI->setPredicate(CI->getInversePredicate());
2150 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002151 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002152 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002153 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002154
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002155 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002156 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002157 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002158
Owen Anderson2cfe9132010-07-14 19:52:16 +00002159 // If we have a bonus inst, clone it into the predecessor block.
Craig Topperf40110f2014-04-25 05:29:35 +00002160 Instruction *NewBonus = nullptr;
Owen Anderson2cfe9132010-07-14 19:52:16 +00002161 if (BonusInst) {
2162 NewBonus = BonusInst->clone();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002163
2164 // If we moved a load, we cannot any longer claim any knowledge about
2165 // its potential value. The previous information might have been valid
2166 // only given the branch precondition.
2167 // For an analogous reason, we must also drop all the metadata whose
2168 // semantics we don't understand.
2169 NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg);
2170
Owen Anderson2cfe9132010-07-14 19:52:16 +00002171 PredBlock->getInstList().insert(PBI, NewBonus);
2172 NewBonus->takeName(BonusInst);
2173 BonusInst->setName(BonusInst->getName()+".old");
2174 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002175
Chris Lattner55eaae12008-07-13 21:20:19 +00002176 // Clone Cond into the predecessor basic block, and or/and the
2177 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002178 Instruction *New = Cond->clone();
Owen Anderson2cfe9132010-07-14 19:52:16 +00002179 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner55eaae12008-07-13 21:20:19 +00002180 PredBlock->getInstList().insert(PBI, New);
2181 New->takeName(Cond);
2182 Cond->setName(New->getName()+".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002183
Manman Rend33f4ef2012-06-13 05:43:29 +00002184 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002185 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002186 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002187 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002188 PBI->setCondition(NewCond);
2189
Manman Renbfb9d432012-09-15 00:39:57 +00002190 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2191 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2192 PredFalseWeight);
2193 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2194 SuccFalseWeight);
2195 SmallVector<uint64_t, 8> NewWeights;
2196
Manman Rend33f4ef2012-06-13 05:43:29 +00002197 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002198 if (PredHasWeights && SuccHasWeights) {
2199 // PBI: br i1 %x, BB, FalseDest
2200 // BI: br i1 %y, TrueDest, FalseDest
2201 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2202 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2203 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2204 // TrueWeight for PBI * FalseWeight for BI.
2205 // We assume that total weights of a BranchInst can fit into 32 bits.
2206 // Therefore, we will not have overflow using 64-bit arithmetic.
2207 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2208 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2209 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002210 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2211 PBI->setSuccessor(0, TrueDest);
2212 }
2213 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002214 if (PredHasWeights && SuccHasWeights) {
2215 // PBI: br i1 %x, TrueDest, BB
2216 // BI: br i1 %y, TrueDest, FalseDest
2217 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2218 // FalseWeight for PBI * TrueWeight for BI.
2219 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2220 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2221 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2222 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2223 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002224 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2225 PBI->setSuccessor(1, FalseDest);
2226 }
Manman Renbfb9d432012-09-15 00:39:57 +00002227 if (NewWeights.size() == 2) {
2228 // Halve the weights if any of them cannot fit in an uint32_t
2229 FitWeights(NewWeights);
2230
2231 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2232 PBI->setMetadata(LLVMContext::MD_prof,
2233 MDBuilder(BI->getContext()).
2234 createBranchWeights(MDWeights));
2235 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002236 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002237 } else {
2238 // Update PHI nodes in the common successors.
2239 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002240 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002241 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2242 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002243 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002244 if (PBI->getSuccessor(0) == TrueDest) {
2245 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2246 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2247 // is false: !PBI_Cond and BI_Value
2248 Instruction *NotCond =
2249 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2250 "not.cond"));
2251 MergedCond =
2252 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2253 NotCond, New,
2254 "and.cond"));
2255 if (PBI_C->isOne())
2256 MergedCond =
2257 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2258 PBI->getCondition(), MergedCond,
2259 "or.cond"));
2260 } else {
2261 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2262 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2263 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002264 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002265 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2266 PBI->getCondition(), New,
2267 "and.cond"));
2268 if (PBI_C->isOne()) {
2269 Instruction *NotCond =
2270 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2271 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002272 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002273 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2274 NotCond, MergedCond,
2275 "or.cond"));
2276 }
2277 }
2278 // Update PHI Node.
2279 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2280 MergedCond);
2281 }
2282 // Change PBI from Conditional to Unconditional.
2283 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2284 EraseTerminatorInstAndDCECond(PBI);
2285 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002286 }
Devang Pateld715ec82011-04-06 22:37:20 +00002287
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002288 // TODO: If BB is reachable from all paths through PredBlock, then we
2289 // could replace PBI's branch probabilities with BI's.
2290
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002291 // Copy any debug value intrinsics into the end of PredBlock.
2292 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2293 if (isa<DbgInfoIntrinsic>(*I))
2294 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002295
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002296 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002297 }
2298 return false;
2299}
2300
Chris Lattner9aada1d2008-07-13 21:53:26 +00002301/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2302/// predecessor of another block, this function tries to simplify it. We know
2303/// that PBI and BI are both conditional branches, and BI is in one of the
2304/// successor blocks of PBI - PBI branches to BI.
2305static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2306 assert(PBI->isConditional() && BI->isConditional());
2307 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002308
Chris Lattner9aada1d2008-07-13 21:53:26 +00002309 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002310 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002311 // this conditional branch redundant.
2312 if (PBI->getCondition() == BI->getCondition() &&
2313 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2314 // Okay, the outcome of this conditional branch is statically
2315 // knowable. If this block had a single pred, handle specially.
2316 if (BB->getSinglePredecessor()) {
2317 // Turn this into a branch on constant.
2318 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002319 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002320 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002321 return true; // Nuke the branch on constant.
2322 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002323
Chris Lattner9aada1d2008-07-13 21:53:26 +00002324 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2325 // in the constant and simplify the block result. Subsequent passes of
2326 // simplifycfg will thread the block.
2327 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002328 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002329 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002330 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002331 BI->getCondition()->getName() + ".pr",
2332 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002333 // Okay, we're going to insert the PHI node. Since PBI is not the only
2334 // predecessor, compute the PHI'd conditional value for all of the preds.
2335 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002336 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002337 BasicBlock *P = *PI;
2338 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002339 PBI != BI && PBI->isConditional() &&
2340 PBI->getCondition() == BI->getCondition() &&
2341 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2342 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002343 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002344 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002345 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002346 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002347 }
Gabor Greif8629f122010-07-12 10:59:23 +00002348 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002349
Chris Lattner9aada1d2008-07-13 21:53:26 +00002350 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002351 return true;
2352 }
2353 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002354
Chris Lattner9aada1d2008-07-13 21:53:26 +00002355 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002356 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002357 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002358 BasicBlock::iterator BBI = BB->begin();
2359 // Ignore dbg intrinsics.
2360 while (isa<DbgInfoIntrinsic>(BBI))
2361 ++BBI;
2362 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002363 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002364
Andrew Trickf3cf1932012-08-29 21:46:36 +00002365
Chris Lattnerc59945b2009-01-20 01:15:41 +00002366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2367 if (CE->canTrap())
2368 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002369
Chris Lattner834ab4e2008-07-13 22:04:41 +00002370 int PBIOp, BIOp;
2371 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2372 PBIOp = BIOp = 0;
2373 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2374 PBIOp = 0, BIOp = 1;
2375 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2376 PBIOp = 1, BIOp = 0;
2377 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2378 PBIOp = BIOp = 1;
2379 else
2380 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002381
Chris Lattner834ab4e2008-07-13 22:04:41 +00002382 // Check to make sure that the other destination of this branch
2383 // isn't BB itself. If so, this is an infinite loop that will
2384 // keep getting unwound.
2385 if (PBI->getSuccessor(PBIOp) == BB)
2386 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002387
2388 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002389 // insertion of a large number of select instructions. For targets
2390 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002391
Sanjay Patela932da82014-07-07 21:19:00 +00002392 // Also do not perform this transformation if any phi node in the common
2393 // destination block can trap when reached by BB or PBB (PR17073). In that
2394 // case, it would be unsafe to hoist the operation into a select instruction.
2395
2396 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002397 unsigned NumPhis = 0;
2398 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002399 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002400 if (NumPhis > 2) // Disable this xform.
2401 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002402
Sanjay Patela932da82014-07-07 21:19:00 +00002403 PHINode *PN = cast<PHINode>(II);
2404 Value *BIV = PN->getIncomingValueForBlock(BB);
2405 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2406 if (CE->canTrap())
2407 return false;
2408
2409 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2410 Value *PBIV = PN->getIncomingValue(PBBIdx);
2411 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2412 if (CE->canTrap())
2413 return false;
2414 }
2415
Chris Lattner834ab4e2008-07-13 22:04:41 +00002416 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002417 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002418
David Greene725c7c32010-01-05 01:26:52 +00002419 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002420 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002421
2422
Chris Lattner80b03a12008-07-13 22:23:11 +00002423 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2424 // branch in it, where one edge (OtherDest) goes back to itself but the other
2425 // exits. We don't *know* that the program avoids the infinite loop
2426 // (even though that seems likely). If we do this xform naively, we'll end up
2427 // recursively unpeeling the loop. Since we know that (after the xform is
2428 // done) that the block *is* infinite if reached, we just make it an obviously
2429 // infinite loop with no cond branch.
2430 if (OtherDest == BB) {
2431 // Insert it at the end of the function, because it's either code,
2432 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002433 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2434 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002435 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2436 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002437 }
2438
David Greene725c7c32010-01-05 01:26:52 +00002439 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002440
Chris Lattner834ab4e2008-07-13 22:04:41 +00002441 // BI may have other predecessors. Because of this, we leave
2442 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002443
Chris Lattner834ab4e2008-07-13 22:04:41 +00002444 // Make sure we get to CommonDest on True&True directions.
2445 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002446 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002447 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002448 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2449
Chris Lattner834ab4e2008-07-13 22:04:41 +00002450 Value *BICond = BI->getCondition();
2451 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002452 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2453
Chris Lattner834ab4e2008-07-13 22:04:41 +00002454 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002455 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002456
Chris Lattner834ab4e2008-07-13 22:04:41 +00002457 // Modify PBI to branch on the new condition to the new dests.
2458 PBI->setCondition(Cond);
2459 PBI->setSuccessor(0, CommonDest);
2460 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002461
Manman Ren2d4c10f2012-09-17 21:30:40 +00002462 // Update branch weight for PBI.
2463 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2464 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2465 PredFalseWeight);
2466 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2467 SuccFalseWeight);
2468 if (PredHasWeights && SuccHasWeights) {
2469 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2470 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2471 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2472 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2473 // The weight to CommonDest should be PredCommon * SuccTotal +
2474 // PredOther * SuccCommon.
2475 // The weight to OtherDest should be PredOther * SuccOther.
2476 SmallVector<uint64_t, 2> NewWeights;
2477 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2478 PredOther * SuccCommon);
2479 NewWeights.push_back(PredOther * SuccOther);
2480 // Halve the weights if any of them cannot fit in an uint32_t
2481 FitWeights(NewWeights);
2482
2483 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2484 PBI->setMetadata(LLVMContext::MD_prof,
2485 MDBuilder(BI->getContext()).
2486 createBranchWeights(MDWeights));
2487 }
2488
Chris Lattner834ab4e2008-07-13 22:04:41 +00002489 // OtherDest may have phi nodes. If so, add an entry from PBI's
2490 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002491 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002492
Chris Lattner834ab4e2008-07-13 22:04:41 +00002493 // We know that the CommonDest already had an edge from PBI to
2494 // it. If it has PHIs though, the PHIs may have different
2495 // entries for BB and PBI's BB. If so, insert a select to make
2496 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002497 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002498 for (BasicBlock::iterator II = CommonDest->begin();
2499 (PN = dyn_cast<PHINode>(II)); ++II) {
2500 Value *BIV = PN->getIncomingValueForBlock(BB);
2501 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2502 Value *PBIV = PN->getIncomingValue(PBBIdx);
2503 if (BIV != PBIV) {
2504 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002505 Value *NV = cast<SelectInst>
2506 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002507 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002508 }
2509 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002510
David Greene725c7c32010-01-05 01:26:52 +00002511 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2512 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002513
Chris Lattner834ab4e2008-07-13 22:04:41 +00002514 // This basic block is probably dead. We know it has at least
2515 // one fewer predecessor.
2516 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002517}
2518
Frits van Bommel8e158492011-01-11 12:52:11 +00002519// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2520// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2521// Takes care of updating the successors and removing the old terminator.
2522// Also makes sure not to introduce new successors by assuming that edges to
2523// non-successor TrueBBs and FalseBBs aren't reachable.
2524static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002525 BasicBlock *TrueBB, BasicBlock *FalseBB,
2526 uint32_t TrueWeight,
2527 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002528 // Remove any superfluous successor edges from the CFG.
2529 // First, figure out which successors to preserve.
2530 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2531 // successor.
2532 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002533 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002534
2535 // Then remove the rest.
2536 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2537 BasicBlock *Succ = OldTerm->getSuccessor(I);
2538 // Make sure only to keep exactly one copy of each edge.
2539 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002540 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002541 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002542 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002543 else
2544 Succ->removePredecessor(OldTerm->getParent());
2545 }
2546
Devang Patel2c2ea222011-05-18 18:43:31 +00002547 IRBuilder<> Builder(OldTerm);
2548 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2549
Frits van Bommel8e158492011-01-11 12:52:11 +00002550 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002551 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002552 if (TrueBB == FalseBB)
2553 // We were only looking for one successor, and it was present.
2554 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002555 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002556 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002557 // We found both of the successors we were looking for.
2558 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002559 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2560 if (TrueWeight != FalseWeight)
2561 NewBI->setMetadata(LLVMContext::MD_prof,
2562 MDBuilder(OldTerm->getContext()).
2563 createBranchWeights(TrueWeight, FalseWeight));
2564 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002565 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2566 // Neither of the selected blocks were successors, so this
2567 // terminator must be unreachable.
2568 new UnreachableInst(OldTerm->getContext(), OldTerm);
2569 } else {
2570 // One of the selected values was a successor, but the other wasn't.
2571 // Insert an unconditional branch to the one that was found;
2572 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002573 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002574 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002575 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002576 else
2577 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002578 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002579 }
2580
2581 EraseTerminatorInstAndDCECond(OldTerm);
2582 return true;
2583}
2584
Frits van Bommel8ae07992011-02-28 09:44:07 +00002585// SimplifySwitchOnSelect - Replaces
2586// (switch (select cond, X, Y)) on constant X, Y
2587// with a branch - conditional if X and Y lead to distinct BBs,
2588// unconditional otherwise.
2589static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2590 // Check for constant integer values in the select.
2591 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2592 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2593 if (!TrueVal || !FalseVal)
2594 return false;
2595
2596 // Find the relevant condition and destinations.
2597 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002598 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2599 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002600
Manman Ren774246a2012-09-17 22:28:55 +00002601 // Get weight for TrueBB and FalseBB.
2602 uint32_t TrueWeight = 0, FalseWeight = 0;
2603 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 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2609 getSuccessorIndex()];
2610 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2611 getSuccessorIndex()];
2612 }
2613 }
2614
Frits van Bommel8ae07992011-02-28 09:44:07 +00002615 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002616 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2617 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002618}
2619
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002620// SimplifyIndirectBrOnSelect - Replaces
2621// (indirectbr (select cond, blockaddress(@fn, BlockA),
2622// blockaddress(@fn, BlockB)))
2623// with
2624// (br cond, BlockA, BlockB).
2625static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2626 // Check that both operands of the select are block addresses.
2627 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2628 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2629 if (!TBA || !FBA)
2630 return false;
2631
2632 // Extract the actual blocks.
2633 BasicBlock *TrueBB = TBA->getBasicBlock();
2634 BasicBlock *FalseBB = FBA->getBasicBlock();
2635
Frits van Bommel8e158492011-01-11 12:52:11 +00002636 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002637 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2638 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002639}
2640
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002641/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2642/// instruction (a seteq/setne with a constant) as the only instruction in a
2643/// block that ends with an uncond branch. We are looking for a very specific
2644/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2645/// this case, we merge the first two "or's of icmp" into a switch, but then the
2646/// default value goes to an uncond block with a seteq in it, we get something
2647/// like:
2648///
2649/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2650/// DEFAULT:
2651/// %tmp = icmp eq i8 %A, 92
2652/// br label %end
2653/// end:
2654/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002655///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002656/// We prefer to split the edge to 'end' so that there is a true/false entry to
2657/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002658static bool TryToSimplifyUncondBranchWithICmpInIt(
2659 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002660 const DataLayout *DL) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002661 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002662
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002663 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2664 // complex.
2665 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2666
2667 Value *V = ICI->getOperand(0);
2668 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002669
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002670 // The pattern we're looking for is where our only predecessor is a switch on
2671 // 'V' and this block is the default case for the switch. In this case we can
2672 // fold the compared value into the switch to simplify things.
2673 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002674 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002675
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002676 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2677 if (SI->getCondition() != V)
2678 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002679
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002680 // If BB is reachable on a non-default case, then we simply know the value of
2681 // V in this block. Substitute it and constant fold the icmp instruction
2682 // away.
2683 if (SI->getDefaultDest() != BB) {
2684 ConstantInt *VVal = SI->findCaseDest(BB);
2685 assert(VVal && "Should have a unique destination value");
2686 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002687
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002688 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002689 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002690 ICI->eraseFromParent();
2691 }
2692 // BB is now empty, so it is likely to simplify away.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002693 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002694 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002695
Chris Lattner62cc76e2010-12-13 03:43:57 +00002696 // Ok, the block is reachable from the default dest. If the constant we're
2697 // comparing exists in one of the other edges, then we can constant fold ICI
2698 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002699 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002700 Value *V;
2701 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2702 V = ConstantInt::getFalse(BB->getContext());
2703 else
2704 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002705
Chris Lattner62cc76e2010-12-13 03:43:57 +00002706 ICI->replaceAllUsesWith(V);
2707 ICI->eraseFromParent();
2708 // BB is now empty, so it is likely to simplify away.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002709 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002710 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002711
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002712 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2713 // the block.
2714 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002715 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002716 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002717 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2718 return false;
2719
2720 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2721 // true in the PHI.
2722 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2723 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2724
2725 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2726 std::swap(DefaultCst, NewCst);
2727
2728 // Replace ICI (which is used by the PHI for the default value) with true or
2729 // false depending on if it is EQ or NE.
2730 ICI->replaceAllUsesWith(DefaultCst);
2731 ICI->eraseFromParent();
2732
2733 // Okay, the switch goes to this block on a default value. Add an edge from
2734 // the switch to the merge point on the compared value.
2735 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2736 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002737 SmallVector<uint64_t, 8> Weights;
2738 bool HasWeights = HasBranchWeights(SI);
2739 if (HasWeights) {
2740 GetBranchWeights(SI, Weights);
2741 if (Weights.size() == 1 + SI->getNumCases()) {
2742 // Split weight for default case to case for "Cst".
2743 Weights[0] = (Weights[0]+1) >> 1;
2744 Weights.push_back(Weights[0]);
2745
2746 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2747 SI->setMetadata(LLVMContext::MD_prof,
2748 MDBuilder(SI->getContext()).
2749 createBranchWeights(MDWeights));
2750 }
2751 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002752 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002753
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002754 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002755 Builder.SetInsertPoint(NewBB);
2756 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2757 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002758 PHIUse->addIncoming(NewCst, NewBB);
2759 return true;
2760}
2761
Chris Lattnera69c4432010-12-13 05:03:41 +00002762/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2763/// Check to see if it is branching on an or/and chain of icmp instructions, and
2764/// fold it into a switch instruction if so.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002765static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
Devang Patel7de6c4b2011-05-18 23:18:47 +00002766 IRBuilder<> &Builder) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002767 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002768 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002769
2770
Chris Lattnera69c4432010-12-13 05:03:41 +00002771 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2772 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2773 // 'setne's and'ed together, collect them.
Craig Topperf40110f2014-04-25 05:29:35 +00002774 Value *CompVal = nullptr;
Chris Lattnera69c4432010-12-13 05:03:41 +00002775 std::vector<ConstantInt*> Values;
2776 bool TrueWhenEqual = true;
Craig Topperf40110f2014-04-25 05:29:35 +00002777 Value *ExtraCase = nullptr;
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002778 unsigned UsedICmps = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002779
Chris Lattnera69c4432010-12-13 05:03:41 +00002780 if (Cond->getOpcode() == Instruction::Or) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002781 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002782 UsedICmps);
Chris Lattnera69c4432010-12-13 05:03:41 +00002783 } else if (Cond->getOpcode() == Instruction::And) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002784 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002785 UsedICmps);
Chris Lattnera69c4432010-12-13 05:03:41 +00002786 TrueWhenEqual = false;
2787 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002788
Chris Lattnera69c4432010-12-13 05:03:41 +00002789 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002790 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002791
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002792 // Avoid turning single icmps into a switch.
2793 if (UsedICmps <= 1)
2794 return false;
2795
Chris Lattnera69c4432010-12-13 05:03:41 +00002796 // There might be duplicate constants in the list, which the switch
2797 // instruction can't handle, remove them now.
2798 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2799 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002800
Chris Lattnera69c4432010-12-13 05:03:41 +00002801 // If Extra was used, we require at least two switch values to do the
2802 // transformation. A switch with one value is just an cond branch.
2803 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002804
Andrew Trick3051aa12012-08-29 21:46:38 +00002805 // TODO: Preserve branch weight metadata, similarly to how
2806 // FoldValueComparisonIntoPredecessors preserves it.
2807
Chris Lattnera69c4432010-12-13 05:03:41 +00002808 // Figure out which block is which destination.
2809 BasicBlock *DefaultBB = BI->getSuccessor(1);
2810 BasicBlock *EdgeBB = BI->getSuccessor(0);
2811 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002812
Chris Lattnera69c4432010-12-13 05:03:41 +00002813 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002814
Chris Lattnerd7beca32010-12-14 06:17:25 +00002815 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002816 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002817
Chris Lattnera69c4432010-12-13 05:03:41 +00002818 // If there are any extra values that couldn't be folded into the switch
2819 // then we evaluate them with an explicit branch first. Split the block
2820 // right before the condbr to handle it.
2821 if (ExtraCase) {
2822 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2823 // Remove the uncond branch added to the old block.
2824 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002825 Builder.SetInsertPoint(OldTI);
2826
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002827 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002828 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002829 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002830 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002831
Chris Lattnera69c4432010-12-13 05:03:41 +00002832 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002833
Chris Lattnercb570f82010-12-13 05:34:18 +00002834 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2835 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002836 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002837
Chris Lattnerd7beca32010-12-14 06:17:25 +00002838 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2839 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002840 BB = NewBB;
2841 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002842
2843 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002844 // Convert pointer to int before we switch.
2845 if (CompVal->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002846 assert(DL && "Cannot switch on pointer without DataLayout");
Devang Patel7de6c4b2011-05-18 23:18:47 +00002847 CompVal = Builder.CreatePtrToInt(CompVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002848 DL->getIntPtrType(CompVal->getType()),
Devang Patel7de6c4b2011-05-18 23:18:47 +00002849 "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002850 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002851
Chris Lattnera69c4432010-12-13 05:03:41 +00002852 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002853 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002854
Chris Lattnera69c4432010-12-13 05:03:41 +00002855 // Add all of the 'cases' to the switch instruction.
2856 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2857 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002858
Chris Lattnera69c4432010-12-13 05:03:41 +00002859 // We added edges from PI to the EdgeBB. As such, if there were any
2860 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2861 // the number of edges added.
2862 for (BasicBlock::iterator BBI = EdgeBB->begin();
2863 isa<PHINode>(BBI); ++BBI) {
2864 PHINode *PN = cast<PHINode>(BBI);
2865 Value *InVal = PN->getIncomingValueForBlock(BB);
2866 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2867 PN->addIncoming(InVal, BB);
2868 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002869
Chris Lattnera69c4432010-12-13 05:03:41 +00002870 // Erase the old branch instruction.
2871 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002872
Chris Lattnerd7beca32010-12-14 06:17:25 +00002873 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002874 return true;
2875}
2876
Duncan Sands29192d02011-09-05 12:57:57 +00002877bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2878 // If this is a trivial landing pad that just continues unwinding the caught
2879 // exception then zap the landing pad, turning its invokes into calls.
2880 BasicBlock *BB = RI->getParent();
2881 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2882 if (RI->getValue() != LPInst)
2883 // Not a landing pad, or the resume is not unwinding the exception that
2884 // caused control to branch here.
2885 return false;
2886
2887 // Check that there are no other instructions except for debug intrinsics.
2888 BasicBlock::iterator I = LPInst, E = RI;
2889 while (++I != E)
2890 if (!isa<DbgInfoIntrinsic>(I))
2891 return false;
2892
2893 // Turn all invokes that unwind here into calls and delete the basic block.
Bill Wendling9534d882013-03-11 20:53:00 +00002894 bool InvokeRequiresTableEntry = false;
2895 bool Changed = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002896 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2897 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Bill Wendling9534d882013-03-11 20:53:00 +00002898
2899 if (II->hasFnAttr(Attribute::UWTable)) {
2900 // Don't remove an `invoke' instruction if the ABI requires an entry into
2901 // the table.
2902 InvokeRequiresTableEntry = true;
2903 continue;
2904 }
2905
Duncan Sands29192d02011-09-05 12:57:57 +00002906 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
Bill Wendling9534d882013-03-11 20:53:00 +00002907
Duncan Sands29192d02011-09-05 12:57:57 +00002908 // Insert a call instruction before the invoke.
2909 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2910 Call->takeName(II);
2911 Call->setCallingConv(II->getCallingConv());
2912 Call->setAttributes(II->getAttributes());
2913 Call->setDebugLoc(II->getDebugLoc());
2914
2915 // Anything that used the value produced by the invoke instruction now uses
2916 // the value produced by the call instruction. Note that we do this even
2917 // for void functions and calls with no uses so that the callgraph edge is
2918 // updated.
2919 II->replaceAllUsesWith(Call);
2920 BB->removePredecessor(II->getParent());
2921
2922 // Insert a branch to the normal destination right before the invoke.
2923 BranchInst::Create(II->getNormalDest(), II);
2924
2925 // Finally, delete the invoke instruction!
2926 II->eraseFromParent();
Bill Wendling9534d882013-03-11 20:53:00 +00002927 Changed = true;
Duncan Sands29192d02011-09-05 12:57:57 +00002928 }
2929
Bill Wendling9534d882013-03-11 20:53:00 +00002930 if (!InvokeRequiresTableEntry)
2931 // The landingpad is now unreachable. Zap it.
2932 BB->eraseFromParent();
2933
2934 return Changed;
Duncan Sands29192d02011-09-05 12:57:57 +00002935}
2936
Devang Pateldd14e0f2011-05-18 21:33:11 +00002937bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002938 BasicBlock *BB = RI->getParent();
2939 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002940
Chris Lattner25c3af32010-12-13 06:25:44 +00002941 // Find predecessors that end with branches.
2942 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2943 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002944 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2945 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00002946 TerminatorInst *PTI = P->getTerminator();
2947 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2948 if (BI->isUnconditional())
2949 UncondBranchPreds.push_back(P);
2950 else
2951 CondBranchPreds.push_back(BI);
2952 }
2953 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002954
Chris Lattner25c3af32010-12-13 06:25:44 +00002955 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00002956 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002957 while (!UncondBranchPreds.empty()) {
2958 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2959 DEBUG(dbgs() << "FOLDING: " << *BB
2960 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00002961 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00002962 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002963
Chris Lattner25c3af32010-12-13 06:25:44 +00002964 // If we eliminated all predecessors of the block, delete the block now.
2965 if (pred_begin(BB) == pred_end(BB))
2966 // We know there are no successors, so just nuke the block.
2967 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002968
Chris Lattner25c3af32010-12-13 06:25:44 +00002969 return true;
2970 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002971
Chris Lattner25c3af32010-12-13 06:25:44 +00002972 // Check out all of the conditional branches going to this return
2973 // instruction. If any of them just select between returns, change the
2974 // branch itself into a select/return pair.
2975 while (!CondBranchPreds.empty()) {
2976 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002977
Chris Lattner25c3af32010-12-13 06:25:44 +00002978 // Check to see if the non-BB successor is also a return block.
2979 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2980 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00002981 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00002982 return true;
2983 }
2984 return false;
2985}
2986
Chris Lattner25c3af32010-12-13 06:25:44 +00002987bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2988 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002989
Chris Lattner25c3af32010-12-13 06:25:44 +00002990 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002991
Chris Lattner25c3af32010-12-13 06:25:44 +00002992 // If there are any instructions immediately before the unreachable that can
2993 // be removed, do so.
2994 while (UI != BB->begin()) {
2995 BasicBlock::iterator BBI = UI;
2996 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002997 // Do not delete instructions that can have side effects which might cause
2998 // the unreachable to not be reachable; specifically, calls and volatile
2999 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003000 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003001
3002 if (BBI->mayHaveSideEffects()) {
3003 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3004 if (SI->isVolatile())
3005 break;
3006 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3007 if (LI->isVolatile())
3008 break;
3009 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3010 if (RMWI->isVolatile())
3011 break;
3012 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3013 if (CXI->isVolatile())
3014 break;
3015 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3016 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003017 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003018 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003019 // Note that deleting LandingPad's here is in fact okay, although it
3020 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3021 // all the predecessors of this block will be the unwind edges of Invokes,
3022 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003023 }
3024
Eli Friedmanaac35b32011-03-09 00:48:33 +00003025 // Delete this instruction (any uses are guaranteed to be dead)
3026 if (!BBI->use_empty())
3027 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003028 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003029 Changed = true;
3030 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003031
Chris Lattner25c3af32010-12-13 06:25:44 +00003032 // If the unreachable instruction is the first in the block, take a gander
3033 // at all of the predecessors of this instruction, and simplify them.
3034 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003035
Chris Lattner25c3af32010-12-13 06:25:44 +00003036 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3037 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3038 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003039 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003040 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3041 if (BI->isUnconditional()) {
3042 if (BI->getSuccessor(0) == BB) {
3043 new UnreachableInst(TI->getContext(), TI);
3044 TI->eraseFromParent();
3045 Changed = true;
3046 }
3047 } else {
3048 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003049 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003050 EraseTerminatorInstAndDCECond(BI);
3051 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003052 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003053 EraseTerminatorInstAndDCECond(BI);
3054 Changed = true;
3055 }
3056 }
3057 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003058 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003059 i != e; ++i)
3060 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003061 BB->removePredecessor(SI->getParent());
3062 SI->removeCase(i);
3063 --i; --e;
3064 Changed = true;
3065 }
3066 // If the default value is unreachable, figure out the most popular
3067 // destination and make it the default.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003068 if (SI->getDefaultDest() == BB) {
Eli Friedmanc4414c62011-03-15 02:23:35 +00003069 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003070 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003071 i != e; ++i) {
Nick Lewyckye87d54c2011-12-26 20:37:40 +00003072 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003073 Popularity[i.getCaseSuccessor()];
Eli Friedmanc4414c62011-03-15 02:23:35 +00003074 if (entry.first == 0) {
3075 entry.first = 1;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003076 entry.second = i.getCaseIndex();
Eli Friedmanc4414c62011-03-15 02:23:35 +00003077 } else {
3078 entry.first++;
3079 }
3080 }
3081
Chris Lattner25c3af32010-12-13 06:25:44 +00003082 // Find the most popular block.
3083 unsigned MaxPop = 0;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003084 unsigned MaxIndex = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003085 BasicBlock *MaxBlock = nullptr;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003086 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner25c3af32010-12-13 06:25:44 +00003087 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00003088 if (I->second.first > MaxPop ||
Eli Friedmanc4414c62011-03-15 02:23:35 +00003089 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3090 MaxPop = I->second.first;
3091 MaxIndex = I->second.second;
Chris Lattner25c3af32010-12-13 06:25:44 +00003092 MaxBlock = I->first;
3093 }
3094 }
3095 if (MaxBlock) {
3096 // Make this the new default, allowing us to delete any explicit
3097 // edges to it.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003098 SI->setDefaultDest(MaxBlock);
Chris Lattner25c3af32010-12-13 06:25:44 +00003099 Changed = true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003100
Chris Lattner25c3af32010-12-13 06:25:44 +00003101 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3102 // it.
3103 if (isa<PHINode>(MaxBlock->begin()))
3104 for (unsigned i = 0; i != MaxPop-1; ++i)
3105 MaxBlock->removePredecessor(SI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003106
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003107 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003108 i != e; ++i)
3109 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003110 SI->removeCase(i);
3111 --i; --e;
3112 }
3113 }
3114 }
3115 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3116 if (II->getUnwindDest() == BB) {
3117 // Convert the invoke to a call instruction. This would be a good
3118 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003119 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003120 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003121
Chris Lattner25c3af32010-12-13 06:25:44 +00003122 // Insert the call now...
3123 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003124 Builder.SetInsertPoint(BI);
3125 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003126 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003127 CI->setCallingConv(II->getCallingConv());
3128 CI->setAttributes(II->getAttributes());
3129 // If the invoke produced a value, the call does now instead.
3130 II->replaceAllUsesWith(CI);
3131 delete II;
3132 Changed = true;
3133 }
3134 }
3135 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003136
Chris Lattner25c3af32010-12-13 06:25:44 +00003137 // If this block is now dead, remove it.
3138 if (pred_begin(BB) == pred_end(BB) &&
3139 BB != &BB->getParent()->getEntryBlock()) {
3140 // We know there are no successors, so just nuke the block.
3141 BB->eraseFromParent();
3142 return true;
3143 }
3144
3145 return Changed;
3146}
3147
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003148/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3149/// integer range comparison into a sub, an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003150static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003151 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003152
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003153 // Make sure all cases point to the same destination and gather the values.
3154 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003155 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003156 Cases.push_back(I.getCaseValue());
3157 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003158 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003159 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003160 return false;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003161 Cases.push_back(I.getCaseValue());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003162 }
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003163 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003164
3165 // Sort the case values, then check if they form a range we can transform.
3166 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3167 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3168 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3169 return false;
3170 }
3171
3172 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003173 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003174
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003175 Value *Sub = SI->getCondition();
3176 if (!Offset->isNullValue())
Devang Patel3015a542011-05-19 00:13:33 +00003177 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003178 Value *Cmp;
3179 // If NumCases overflowed, then all possible values jump to the successor.
3180 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3181 Cmp = ConstantInt::getTrue(SI->getContext());
3182 else
3183 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren56575552012-09-18 00:47:33 +00003184 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003185 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003186
Manman Ren56575552012-09-18 00:47:33 +00003187 // Update weight for the newly-created conditional branch.
3188 SmallVector<uint64_t, 8> Weights;
3189 bool HasWeights = HasBranchWeights(SI);
3190 if (HasWeights) {
3191 GetBranchWeights(SI, Weights);
3192 if (Weights.size() == 1 + SI->getNumCases()) {
3193 // Combine all weights for the cases to be the true weight of NewBI.
3194 // We assume that the sum of all weights for a Terminator can fit into 32
3195 // bits.
3196 uint32_t NewTrueWeight = 0;
3197 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3198 NewTrueWeight += (uint32_t)Weights[I];
3199 NewBI->setMetadata(LLVMContext::MD_prof,
3200 MDBuilder(SI->getContext()).
3201 createBranchWeights(NewTrueWeight,
3202 (uint32_t)Weights[0]));
3203 }
3204 }
3205
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003206 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003207 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003208 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003209 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003210 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3211 }
3212 SI->eraseFromParent();
3213
3214 return true;
3215}
Chris Lattner25c3af32010-12-13 06:25:44 +00003216
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003217/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3218/// and use it to remove dead cases.
3219static bool EliminateDeadSwitchCases(SwitchInst *SI) {
3220 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003221 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003222 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Jay Foada0653a32014-05-14 21:14:37 +00003223 computeKnownBits(Cond, KnownZero, KnownOne);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003224
3225 // Gather dead cases.
3226 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003227 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003228 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3229 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3230 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003231 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003232 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003233 }
3234 }
3235
Manman Ren56575552012-09-18 00:47:33 +00003236 SmallVector<uint64_t, 8> Weights;
3237 bool HasWeight = HasBranchWeights(SI);
3238 if (HasWeight) {
3239 GetBranchWeights(SI, Weights);
3240 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3241 }
3242
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003243 // Remove dead cases from the switch.
3244 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003245 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003246 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003247 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003248 if (HasWeight) {
3249 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3250 Weights.pop_back();
3251 }
3252
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003253 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003254 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003255 SI->removeCase(Case);
3256 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003257 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003258 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3259 SI->setMetadata(LLVMContext::MD_prof,
3260 MDBuilder(SI->getParent()->getContext()).
3261 createBranchWeights(MDWeights));
3262 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003263
3264 return !DeadCases.empty();
3265}
3266
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003267/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3268/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3269/// by an unconditional branch), look at the phi node for BB in the successor
3270/// block and see if the incoming value is equal to CaseValue. If so, return
3271/// the phi node, and set PhiIndex to BB's index in the phi node.
3272static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3273 BasicBlock *BB,
3274 int *PhiIndex) {
3275 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003276 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003277 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003278 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003279
3280 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3281 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003282 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003283
3284 BasicBlock *Succ = Branch->getSuccessor(0);
3285
3286 BasicBlock::iterator I = Succ->begin();
3287 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3288 int Idx = PHI->getBasicBlockIndex(BB);
3289 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3290
3291 Value *InValue = PHI->getIncomingValue(Idx);
3292 if (InValue != CaseValue) continue;
3293
3294 *PhiIndex = Idx;
3295 return PHI;
3296 }
3297
Craig Topperf40110f2014-04-25 05:29:35 +00003298 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003299}
3300
3301/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3302/// instruction to a phi node dominated by the switch, if that would mean that
3303/// some of the destination blocks of the switch can be folded away.
3304/// Returns true if a change is made.
3305static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3306 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3307 ForwardingNodesMap ForwardingNodes;
3308
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003309 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003310 ConstantInt *CaseValue = I.getCaseValue();
3311 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003312
3313 int PhiIndex;
3314 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3315 &PhiIndex);
3316 if (!PHI) continue;
3317
3318 ForwardingNodes[PHI].push_back(PhiIndex);
3319 }
3320
3321 bool Changed = false;
3322
3323 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3324 E = ForwardingNodes.end(); I != E; ++I) {
3325 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003326 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003327
3328 if (Indexes.size() < 2) continue;
3329
3330 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3331 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3332 Changed = true;
3333 }
3334
3335 return Changed;
3336}
3337
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003338/// ValidLookupTableConstant - Return true if the backend will be able to handle
3339/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003340static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003341 if (C->isThreadDependent())
3342 return false;
3343 if (C->isDLLImportDependent())
3344 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003345
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003346 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3347 return CE->isGEPWithNoNotionalOverIndexing();
3348
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003349 return isa<ConstantFP>(C) ||
3350 isa<ConstantInt>(C) ||
3351 isa<ConstantPointerNull>(C) ||
3352 isa<GlobalValue>(C) ||
3353 isa<UndefValue>(C);
3354}
3355
Hans Wennborg09acdb92012-10-31 15:14:39 +00003356/// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003357/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003358static Constant *LookupConstant(Value *V,
3359 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3360 if (Constant *C = dyn_cast<Constant>(V))
3361 return C;
3362 return ConstantPool.lookup(V);
3363}
3364
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003365/// ConstantFold - Try to fold instruction I into a constant. This works for
3366/// simple instructions such as binary operations where both operands are
3367/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003368/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003369static Constant *
3370ConstantFold(Instruction *I,
3371 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3372 const DataLayout *DL) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003373 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003374 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3375 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003376 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003377 if (A->isAllOnesValue())
3378 return LookupConstant(Select->getTrueValue(), ConstantPool);
3379 if (A->isNullValue())
3380 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003381 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003382 }
3383
Benjamin Kramer7c302602013-11-12 12:24:36 +00003384 SmallVector<Constant *, 4> COps;
3385 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3386 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3387 COps.push_back(A);
3388 else
Craig Topperf40110f2014-04-25 05:29:35 +00003389 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003390 }
3391
Benjamin Kramer7c302602013-11-12 12:24:36 +00003392 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3393 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3394 COps[1], DL);
3395
3396 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003397}
3398
3399/// GetCaseResults - Try to determine the resulting constant values in phi nodes
3400/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003401/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003402/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003403static bool
3404GetCaseResults(SwitchInst *SI,
3405 ConstantInt *CaseVal,
3406 BasicBlock *CaseDest,
3407 BasicBlock **CommonDest,
Benjamin Kramer7c302602013-11-12 12:24:36 +00003408 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3409 const DataLayout *DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003410 // The block from which we enter the common destination.
3411 BasicBlock *Pred = SI->getParent();
3412
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003413 // If CaseDest is empty except for some side-effect free instructions through
3414 // which we can constant-propagate the CaseVal, continue to its successor.
3415 SmallDenseMap<Value*, Constant*> ConstantPool;
3416 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3417 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3418 ++I) {
3419 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3420 // If the terminator is a simple branch, continue to the next block.
3421 if (T->getNumSuccessors() != 1)
3422 return false;
3423 Pred = CaseDest;
3424 CaseDest = T->getSuccessor(0);
3425 } else if (isa<DbgInfoIntrinsic>(I)) {
3426 // Skip debug intrinsic.
3427 continue;
Benjamin Kramer7c302602013-11-12 12:24:36 +00003428 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003429 // Instruction is side-effect free and constant.
3430 ConstantPool.insert(std::make_pair(I, C));
3431 } else {
3432 break;
3433 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003434 }
3435
3436 // If we did not have a CommonDest before, use the current one.
3437 if (!*CommonDest)
3438 *CommonDest = CaseDest;
3439 // If the destination isn't the common one, abort.
3440 if (CaseDest != *CommonDest)
3441 return false;
3442
3443 // Get the values for this case from phi nodes in the destination block.
3444 BasicBlock::iterator I = (*CommonDest)->begin();
3445 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3446 int Idx = PHI->getBasicBlockIndex(Pred);
3447 if (Idx == -1)
3448 continue;
3449
Hans Wennborg09acdb92012-10-31 15:14:39 +00003450 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3451 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003452 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003453 return false;
3454
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003455 // Note: If the constant comes from constant-propagating the case value
3456 // through the CaseDest basic block, it will be safe to remove the
3457 // instructions in that block. They cannot be used (except in the phi nodes
3458 // we visit) outside CaseDest, because that block does not dominate its
3459 // successor. If it did, we would not be in this phi node.
3460
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003461 // Be conservative about which kinds of constants we support.
3462 if (!ValidLookupTableConstant(ConstVal))
3463 return false;
3464
3465 Res.push_back(std::make_pair(PHI, ConstVal));
3466 }
3467
Hans Wennborgac114a32014-01-12 00:44:41 +00003468 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003469}
3470
Hans Wennborg776d7122012-09-26 09:34:53 +00003471namespace {
3472 /// SwitchLookupTable - This class represents a lookup table that can be used
3473 /// to replace a switch.
3474 class SwitchLookupTable {
3475 public:
3476 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3477 /// with the contents of Values, using DefaultValue to fill any holes in the
3478 /// table.
3479 SwitchLookupTable(Module &M,
3480 uint64_t TableSize,
3481 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003482 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003483 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003484 const DataLayout *DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003485
3486 /// BuildLookup - Build instructions with Builder to retrieve the value at
3487 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003488 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003489
Hans Wennborg39583b82012-09-26 09:44:49 +00003490 /// WouldFitInRegister - Return true if a table with TableSize elements of
3491 /// type ElementType would fit in a target-legal register.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003492 static bool WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003493 uint64_t TableSize,
3494 const Type *ElementType);
3495
Hans Wennborg776d7122012-09-26 09:34:53 +00003496 private:
3497 // Depending on the contents of the table, it can be represented in
3498 // different ways.
3499 enum {
3500 // For tables where each element contains the same value, we just have to
3501 // store that single value and return it for each lookup.
3502 SingleValueKind,
3503
Hans Wennborg39583b82012-09-26 09:44:49 +00003504 // For small tables with integer elements, we can pack them into a bitmap
3505 // that fits into a target-legal register. Values are retrieved by
3506 // shift and mask operations.
3507 BitMapKind,
3508
Hans Wennborg776d7122012-09-26 09:34:53 +00003509 // The table is stored as an array of values. Values are retrieved by load
3510 // instructions from the table.
3511 ArrayKind
3512 } Kind;
3513
3514 // For SingleValueKind, this is the single value.
3515 Constant *SingleValue;
3516
Hans Wennborg39583b82012-09-26 09:44:49 +00003517 // For BitMapKind, this is the bitmap.
3518 ConstantInt *BitMap;
3519 IntegerType *BitMapElementTy;
3520
Hans Wennborg776d7122012-09-26 09:34:53 +00003521 // For ArrayKind, this is the array.
3522 GlobalVariable *Array;
3523 };
3524}
3525
3526SwitchLookupTable::SwitchLookupTable(Module &M,
3527 uint64_t TableSize,
3528 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003529 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003530 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003531 const DataLayout *DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003532 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3533 Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003534 assert(Values.size() && "Can't build lookup table without values!");
3535 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003536
3537 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003538 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003539
Hans Wennborgac114a32014-01-12 00:44:41 +00003540 Type *ValueType = Values.begin()->second->getType();
3541
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003542 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003543 SmallVector<Constant*, 64> TableContents(TableSize);
3544 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3545 ConstantInt *CaseVal = Values[I].first;
3546 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003547 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003548
Hans Wennborg776d7122012-09-26 09:34:53 +00003549 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3550 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003551 TableContents[Idx] = CaseRes;
3552
Hans Wennborg776d7122012-09-26 09:34:53 +00003553 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003554 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003555 }
3556
3557 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003558 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003559 assert(DefaultValue &&
3560 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003561 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003562 for (uint64_t I = 0; I < TableSize; ++I) {
3563 if (!TableContents[I])
3564 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003565 }
3566
Hans Wennborg776d7122012-09-26 09:34:53 +00003567 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003568 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003569 }
3570
Hans Wennborg776d7122012-09-26 09:34:53 +00003571 // If each element in the table contains the same value, we only need to store
3572 // that single value.
3573 if (SingleValue) {
3574 Kind = SingleValueKind;
3575 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003576 }
3577
Hans Wennborg39583b82012-09-26 09:44:49 +00003578 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003579 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003580 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003581 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3582 for (uint64_t I = TableSize; I > 0; --I) {
3583 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003584 // Insert values into the bitmap. Undef values are set to zero.
3585 if (!isa<UndefValue>(TableContents[I - 1])) {
3586 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3587 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3588 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003589 }
3590 BitMap = ConstantInt::get(M.getContext(), TableInt);
3591 BitMapElementTy = IT;
3592 Kind = BitMapKind;
3593 ++NumBitMaps;
3594 return;
3595 }
3596
Hans Wennborg776d7122012-09-26 09:34:53 +00003597 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003598 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003599 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3600
Hans Wennborg776d7122012-09-26 09:34:53 +00003601 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3602 GlobalVariable::PrivateLinkage,
3603 Initializer,
3604 "switch.table");
3605 Array->setUnnamedAddr(true);
3606 Kind = ArrayKind;
3607}
3608
Manman Ren4d189fb2014-07-24 21:13:20 +00003609Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003610 switch (Kind) {
3611 case SingleValueKind:
3612 return SingleValue;
Hans Wennborg39583b82012-09-26 09:44:49 +00003613 case BitMapKind: {
3614 // Type of the bitmap (e.g. i59).
3615 IntegerType *MapTy = BitMap->getType();
3616
3617 // Cast Index to the same type as the bitmap.
3618 // Note: The Index is <= the number of elements in the table, so
3619 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003620 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003621
3622 // Multiply the shift amount by the element width.
3623 ShiftAmt = Builder.CreateMul(ShiftAmt,
3624 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3625 "switch.shiftamt");
3626
3627 // Shift down.
3628 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3629 "switch.downshift");
3630 // Mask off.
3631 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3632 "switch.masked");
3633 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003634 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003635 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003636 IntegerType *IT = cast<IntegerType>(Index->getType());
3637 uint64_t TableSize = Array->getInitializer()->getType()
3638 ->getArrayNumElements();
3639 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3640 Index = Builder.CreateZExt(Index,
3641 IntegerType::get(IT->getContext(),
3642 IT->getBitWidth() + 1),
3643 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003644
Hans Wennborg776d7122012-09-26 09:34:53 +00003645 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3646 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3647 "switch.gep");
3648 return Builder.CreateLoad(GEP, "switch.load");
3649 }
3650 }
3651 llvm_unreachable("Unknown lookup table kind!");
3652}
3653
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003654bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003655 uint64_t TableSize,
3656 const Type *ElementType) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003657 if (!DL)
Hans Wennborg39583b82012-09-26 09:44:49 +00003658 return false;
3659 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3660 if (!IT)
3661 return false;
3662 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3663 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003664
3665 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3666 if (TableSize >= UINT_MAX/IT->getBitWidth())
3667 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003668 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003669}
3670
Hans Wennborg776d7122012-09-26 09:34:53 +00003671/// ShouldBuildLookupTable - Determine whether a lookup table should be built
Hans Wennborg5cf30be2013-06-04 11:22:30 +00003672/// for this switch, based on the number of cases, size of the table and the
Hans Wennborg776d7122012-09-26 09:34:53 +00003673/// types of the results.
3674static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003675 uint64_t TableSize,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003676 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003677 const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003678 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003679 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3680 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003681
Chandler Carruth77d433d2012-11-30 09:26:25 +00003682 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003683 bool HasIllegalType = false;
Hans Wennborg39583b82012-09-26 09:44:49 +00003684 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3685 E = ResultTypes.end(); I != E; ++I) {
Evan Cheng65df8082012-11-30 02:02:42 +00003686 Type *Ty = I->second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003687
3688 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003689 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003690
3691 // Saturate this flag to false.
3692 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003693 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003694
3695 // If both flags saturate, we're done. NOTE: This *only* works with
3696 // saturating flags, and all flags have to saturate first due to the
3697 // non-deterministic behavior of iterating over a dense map.
3698 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003699 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003700 }
Evan Cheng65df8082012-11-30 02:02:42 +00003701
Chandler Carruth77d433d2012-11-30 09:26:25 +00003702 // If each table would fit in a register, we should build it anyway.
3703 if (AllTablesFitInRegister)
3704 return true;
3705
3706 // Don't build a table that doesn't fit in-register if it has illegal types.
3707 if (HasIllegalType)
3708 return false;
3709
3710 // The table density should be at least 40%. This is the same criterion as for
3711 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3712 // FIXME: Find the best cut-off.
3713 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003714}
3715
3716/// SwitchToLookupTable - If the switch is only used to initialize one or more
3717/// phi nodes in a common successor block with different constant values,
3718/// replace the switch with lookup tables.
3719static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003720 IRBuilder<> &Builder,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003721 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003722 const DataLayout* DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003723 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00003724
Hans Wennborgc3c8d952012-11-07 21:35:12 +00003725 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003726 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00003727 return false;
3728
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003729 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3730 // split off a dense part and build a lookup table for that.
3731
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003732 // FIXME: This creates arrays of GEPs to constant strings, which means each
3733 // GEP needs a runtime relocation in PIC code. We should just build one big
3734 // string and lookup indices into that.
3735
Hans Wennborg4744ac12014-01-15 05:00:27 +00003736 // Ignore switches with less than three cases. Lookup tables will not make them
3737 // faster, so we don't analyze them.
3738 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003739 return false;
3740
3741 // Figure out the corresponding result for each case value and phi node in the
3742 // common destination, as well as the the min and max case values.
3743 assert(SI->case_begin() != SI->case_end());
3744 SwitchInst::CaseIt CI = SI->case_begin();
3745 ConstantInt *MinCaseVal = CI.getCaseValue();
3746 ConstantInt *MaxCaseVal = CI.getCaseValue();
3747
Craig Topperf40110f2014-04-25 05:29:35 +00003748 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003749 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003750 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3751 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3752 SmallDenseMap<PHINode*, Type*> ResultTypes;
3753 SmallVector<PHINode*, 4> PHIs;
3754
3755 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3756 ConstantInt *CaseVal = CI.getCaseValue();
3757 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3758 MinCaseVal = CaseVal;
3759 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3760 MaxCaseVal = CaseVal;
3761
3762 // Resulting value at phi nodes for this case value.
3763 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3764 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003765 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003766 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003767 return false;
3768
3769 // Append the result from this case to the list for each phi.
3770 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3771 if (!ResultLists.count(I->first))
3772 PHIs.push_back(I->first);
3773 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3774 }
3775 }
3776
Hans Wennborgac114a32014-01-12 00:44:41 +00003777 // Keep track of the result types.
3778 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3779 PHINode *PHI = PHIs[I];
3780 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3781 }
3782
3783 uint64_t NumResults = ResultLists[PHIs[0]].size();
3784 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3785 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3786 bool TableHasHoles = (NumResults < TableSize);
3787
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003788 // If the table has holes, we need a constant result for the default case
3789 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003790 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003791 bool HasDefaultResults = false;
3792 if (TableHasHoles) {
Craig Topperf40110f2014-04-25 05:29:35 +00003793 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3794 &CommonDest, DefaultResultsList, DL);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003795 }
3796 bool NeedMask = (TableHasHoles && !HasDefaultResults);
3797 if (NeedMask) {
3798 // As an extra penalty for the validity test we require more cases.
3799 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
3800 return false;
3801 if (!(DL && DL->fitsInLegalInteger(TableSize)))
3802 return false;
3803 }
Hans Wennborgac114a32014-01-12 00:44:41 +00003804
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003805 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3806 PHINode *PHI = DefaultResultsList[I].first;
3807 Constant *Result = DefaultResultsList[I].second;
3808 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003809 }
3810
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003811 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003812 return false;
3813
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003814 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00003815 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003816 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3817 "switch.lookup",
3818 CommonDest->getParent(),
3819 CommonDest);
3820
Michael Gottesmanc024f322013-10-20 07:04:37 +00003821 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003822 Builder.SetInsertPoint(SI);
3823 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3824 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00003825
3826 // Compute the maximum table size representable by the integer type we are
3827 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003828 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00003829 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00003830 assert(MaxTableSize >= TableSize &&
3831 "It is impossible for a switch to have more entries than the max "
3832 "representable value of its input integer type's size.");
3833
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003834 // If we have a fully covered lookup table, unconditionally branch to the
3835 // lookup table BB. Otherwise, check if the condition value is within the case
3836 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3837 // destination.
Michael Gottesmanc024f322013-10-20 07:04:37 +00003838 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3839 if (GeneratingCoveredLookupTable) {
3840 Builder.CreateBr(LookupBB);
Manman Ren062f58d2014-08-02 23:41:54 +00003841 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
3842 // do not delete PHINodes here.
3843 SI->getDefaultDest()->removePredecessor(SI->getParent(),
3844 true/*DontDeleteUselessPHIs*/);
Michael Gottesmanc024f322013-10-20 07:04:37 +00003845 } else {
3846 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00003847 MinCaseVal->getType(), TableSize));
Michael Gottesmanc024f322013-10-20 07:04:37 +00003848 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3849 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003850
3851 // Populate the BB that does the lookups.
3852 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003853
3854 if (NeedMask) {
3855 // Before doing the lookup we do the hole check.
3856 // The LookupBB is therefore re-purposed to do the hole check
3857 // and we create a new LookupBB.
3858 BasicBlock *MaskBB = LookupBB;
3859 MaskBB->setName("switch.hole_check");
3860 LookupBB = BasicBlock::Create(Mod.getContext(),
3861 "switch.lookup",
3862 CommonDest->getParent(),
3863 CommonDest);
3864
3865 // Build bitmask; fill in a 1 bit for every case.
3866 APInt MaskInt(TableSize, 0);
3867 APInt One(TableSize, 1);
3868 const ResultListTy &ResultList = ResultLists[PHIs[0]];
3869 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3870 uint64_t Idx = (ResultList[I].first->getValue() -
3871 MinCaseVal->getValue()).getLimitedValue();
3872 MaskInt |= One << Idx;
3873 }
3874 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3875
3876 // Get the TableIndex'th bit of the bitmask.
3877 // If this bit is 0 (meaning hole) jump to the default destination,
3878 // else continue with table lookup.
3879 IntegerType *MapTy = TableMask->getType();
3880 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3881 "switch.maskindex");
3882 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3883 "switch.shifted");
3884 Value *LoBit = Builder.CreateTrunc(Shifted,
3885 Type::getInt1Ty(Mod.getContext()),
3886 "switch.lobit");
3887 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3888
3889 Builder.SetInsertPoint(LookupBB);
3890 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3891 }
3892
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003893 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00003894 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3895 PHINode *PHI = PHIs[I];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003896
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003897 // If using a bitmask, use any value to fill the lookup table holes.
3898 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Hans Wennborg776d7122012-09-26 09:34:53 +00003899 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003900 DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003901
Manman Ren4d189fb2014-07-24 21:13:20 +00003902 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003903
Hans Wennborgf744fa92012-09-19 14:24:21 +00003904 // If the result is used to return immediately from the function, we want to
3905 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003906 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3907 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00003908 Builder.CreateRet(Result);
3909 ReturnedEarly = true;
3910 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003911 }
3912
Hans Wennborgf744fa92012-09-19 14:24:21 +00003913 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003914 }
3915
3916 if (!ReturnedEarly)
3917 Builder.CreateBr(CommonDest);
3918
3919 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003920 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003921 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00003922
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003923 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00003924 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003925 Succ->removePredecessor(SI->getParent());
3926 }
3927 SI->eraseFromParent();
3928
3929 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003930 if (NeedMask)
3931 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003932 return true;
3933}
3934
Devang Patela7ec47d2011-05-18 20:35:38 +00003935bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003936 BasicBlock *BB = SI->getParent();
3937
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003938 if (isValueEqualityComparison(SI)) {
3939 // If we only have one predecessor, and if it is a branch on this value,
3940 // see if that predecessor totally determines the outcome of this switch.
3941 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3942 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003943 return SimplifyCFG(BB, TTI, DL) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00003944
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003945 Value *Cond = SI->getCondition();
3946 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3947 if (SimplifySwitchOnSelect(SI, Select))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003948 return SimplifyCFG(BB, TTI, DL) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00003949
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003950 // If the block only contains the switch, see if we can fold the block
3951 // away into any preds.
3952 BasicBlock::iterator BBI = BB->begin();
3953 // Ignore dbg intrinsics.
3954 while (isa<DbgInfoIntrinsic>(BBI))
3955 ++BBI;
3956 if (SI == &*BBI)
3957 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003958 return SimplifyCFG(BB, TTI, DL) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003959 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003960
3961 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003962 if (TurnSwitchRangeIntoICmp(SI, Builder))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003963 return SimplifyCFG(BB, TTI, DL) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003964
3965 // Remove unreachable cases.
3966 if (EliminateDeadSwitchCases(SI))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003967 return SimplifyCFG(BB, TTI, DL) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003968
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003969 if (ForwardSwitchConditionToPHI(SI))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003970 return SimplifyCFG(BB, TTI, DL) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003971
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003972 if (SwitchToLookupTable(SI, Builder, TTI, DL))
3973 return SimplifyCFG(BB, TTI, DL) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003974
Chris Lattner25c3af32010-12-13 06:25:44 +00003975 return false;
3976}
3977
3978bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3979 BasicBlock *BB = IBI->getParent();
3980 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003981
Chris Lattner25c3af32010-12-13 06:25:44 +00003982 // Eliminate redundant destinations.
3983 SmallPtrSet<Value *, 8> Succs;
3984 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3985 BasicBlock *Dest = IBI->getDestination(i);
3986 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3987 Dest->removePredecessor(BB);
3988 IBI->removeDestination(i);
3989 --i; --e;
3990 Changed = true;
3991 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003992 }
Chris Lattner25c3af32010-12-13 06:25:44 +00003993
3994 if (IBI->getNumDestinations() == 0) {
3995 // If the indirectbr has no successors, change it to unreachable.
3996 new UnreachableInst(IBI->getContext(), IBI);
3997 EraseTerminatorInstAndDCECond(IBI);
3998 return true;
3999 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004000
Chris Lattner25c3af32010-12-13 06:25:44 +00004001 if (IBI->getNumDestinations() == 1) {
4002 // If the indirectbr has one successor, change it to a direct branch.
4003 BranchInst::Create(IBI->getDestination(0), IBI);
4004 EraseTerminatorInstAndDCECond(IBI);
4005 return true;
4006 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004007
Chris Lattner25c3af32010-12-13 06:25:44 +00004008 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4009 if (SimplifyIndirectBrOnSelect(IBI, SI))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004010 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004011 }
4012 return Changed;
4013}
4014
Devang Patel767f6932011-05-18 18:28:48 +00004015bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004016 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004017
Manman Ren93ab6492012-09-20 22:37:36 +00004018 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4019 return true;
4020
Chris Lattner25c3af32010-12-13 06:25:44 +00004021 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004022 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004023 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4024 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4025 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004026
Chris Lattner25c3af32010-12-13 06:25:44 +00004027 // If the only instruction in the block is a seteq/setne comparison
4028 // against a constant, try to simplify the block.
4029 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4030 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4031 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4032 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004033 if (I->isTerminator() &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004034 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004035 return true;
4036 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004037
Manman Rend33f4ef2012-06-13 05:43:29 +00004038 // If this basic block is ONLY a compare and a branch, and if a predecessor
4039 // branches to us and our successor, fold the comparison into the
4040 // predecessor and use logical operations to update the incoming value
4041 // for PHI nodes in common successor.
Hal Finkela995f922014-07-10 14:41:31 +00004042 if (FoldBranchToCommonDest(BI, DL))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004043 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004044 return false;
4045}
4046
4047
Devang Patela7ec47d2011-05-18 20:35:38 +00004048bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004049 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004050
Chris Lattner25c3af32010-12-13 06:25:44 +00004051 // Conditional branch
4052 if (isValueEqualityComparison(BI)) {
4053 // If we only have one predecessor, and if it is a branch on this value,
4054 // see if that predecessor totally determines the outcome of this
4055 // switch.
4056 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004057 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004058 return SimplifyCFG(BB, TTI, DL) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004059
Chris Lattner25c3af32010-12-13 06:25:44 +00004060 // This block must be empty, except for the setcond inst, if it exists.
4061 // Ignore dbg intrinsics.
4062 BasicBlock::iterator I = BB->begin();
4063 // Ignore dbg intrinsics.
4064 while (isa<DbgInfoIntrinsic>(I))
4065 ++I;
4066 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004067 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004068 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004069 } else if (&*I == cast<Instruction>(BI->getCondition())){
4070 ++I;
4071 // Ignore dbg intrinsics.
4072 while (isa<DbgInfoIntrinsic>(I))
4073 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004074 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004075 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004076 }
4077 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004078
Chris Lattner25c3af32010-12-13 06:25:44 +00004079 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004080 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004081 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004082
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004083 // If this basic block is ONLY a compare and a branch, and if a predecessor
4084 // branches to us and one of our successors, fold the comparison into the
4085 // predecessor and use logical operations to pick the right destination.
Hal Finkela995f922014-07-10 14:41:31 +00004086 if (FoldBranchToCommonDest(BI, DL))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004087 return SimplifyCFG(BB, TTI, DL) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004088
Chris Lattner25c3af32010-12-13 06:25:44 +00004089 // We have a conditional branch to two blocks that are only reachable
4090 // from BI. We know that the condbr dominates the two blocks, so see if
4091 // there is any identical code in the "then" and "else" blocks. If so, we
4092 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004093 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4094 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Hal Finkela995f922014-07-10 14:41:31 +00004095 if (HoistThenElseCodeToIf(BI, DL))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004096 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004097 } else {
4098 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004099 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004100 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4101 if (Succ0TI->getNumSuccessors() == 1 &&
4102 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Hal Finkela995f922014-07-10 14:41:31 +00004103 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004104 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004105 }
Craig Topperf40110f2014-04-25 05:29:35 +00004106 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004107 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004108 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004109 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4110 if (Succ1TI->getNumSuccessors() == 1 &&
4111 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Hal Finkela995f922014-07-10 14:41:31 +00004112 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004113 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004114 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004115
Chris Lattner25c3af32010-12-13 06:25:44 +00004116 // If this is a branch on a phi node in the current block, thread control
4117 // through this block if any PHI node entries are constants.
4118 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4119 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004120 if (FoldCondBranchOnPHI(BI, DL))
4121 return SimplifyCFG(BB, TTI, DL) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004122
Chris Lattner25c3af32010-12-13 06:25:44 +00004123 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004124 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4125 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004126 if (PBI != BI && PBI->isConditional())
4127 if (SimplifyCondBranchToCondBranch(PBI, BI))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004128 return SimplifyCFG(BB, TTI, DL) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004129
4130 return false;
4131}
4132
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004133/// Check if passing a value to an instruction will cause undefined behavior.
4134static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4135 Constant *C = dyn_cast<Constant>(V);
4136 if (!C)
4137 return false;
4138
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004139 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004140 return false;
4141
4142 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004143 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004144 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004145
4146 // Now make sure that there are no instructions in between that can alter
4147 // control flow (eg. calls)
4148 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004149 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004150 return false;
4151
4152 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4153 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4154 if (GEP->getPointerOperand() == I)
4155 return passingValueIsAlwaysUndefined(V, GEP);
4156
4157 // Look through bitcasts.
4158 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4159 return passingValueIsAlwaysUndefined(V, BC);
4160
Benjamin Kramer0655b782011-08-26 02:25:55 +00004161 // Load from null is undefined.
4162 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004163 if (!LI->isVolatile())
4164 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004165
Benjamin Kramer0655b782011-08-26 02:25:55 +00004166 // Store to null is undefined.
4167 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004168 if (!SI->isVolatile())
4169 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004170 }
4171 return false;
4172}
4173
4174/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004175/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004176static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4177 for (BasicBlock::iterator i = BB->begin();
4178 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4179 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4180 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4181 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4182 IRBuilder<> Builder(T);
4183 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4184 BB->removePredecessor(PHI->getIncomingBlock(i));
4185 // Turn uncoditional branches into unreachables and remove the dead
4186 // destination from conditional branches.
4187 if (BI->isUnconditional())
4188 Builder.CreateUnreachable();
4189 else
4190 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4191 BI->getSuccessor(0));
4192 BI->eraseFromParent();
4193 return true;
4194 }
4195 // TODO: SwitchInst.
4196 }
4197
4198 return false;
4199}
4200
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004201bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004202 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004203
Chris Lattnerd7beca32010-12-14 06:17:25 +00004204 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004205 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004206
Dan Gohman4a63fad2010-08-14 00:29:42 +00004207 // Remove basic blocks that have no predecessors (except the entry block)...
4208 // or that just have themself as a predecessor. These are unreachable.
Chris Lattnerd7beca32010-12-14 06:17:25 +00004209 if ((pred_begin(BB) == pred_end(BB) &&
4210 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004211 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004212 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004213 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004214 return true;
4215 }
4216
Chris Lattner031340a2003-08-17 19:41:53 +00004217 // Check to see if we can constant propagate this terminator instruction
4218 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004219 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004220
Dan Gohman1a951062009-10-30 22:39:04 +00004221 // Check for and eliminate duplicate PHI nodes in this block.
4222 Changed |= EliminateDuplicatePHINodes(BB);
4223
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004224 // Check for and remove branches that will always cause undefined behavior.
4225 Changed |= removeUndefIntroducingPredecessor(BB);
4226
Chris Lattner2e3832d2010-12-13 05:10:48 +00004227 // Merge basic blocks into their predecessor if there is only one distinct
4228 // pred, and if there is only one distinct successor of the predecessor, and
4229 // if there are no PHI nodes.
4230 //
4231 if (MergeBlockIntoPredecessor(BB))
4232 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004233
Devang Patel15ad6762011-05-18 18:01:27 +00004234 IRBuilder<> Builder(BB);
4235
Dan Gohman20af5a02008-03-11 21:53:06 +00004236 // If there is a trivial two-entry PHI node in this basic block, and we can
4237 // eliminate it, do so now.
4238 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4239 if (PN->getNumIncomingValues() == 2)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004240 Changed |= FoldTwoEntryPHINode(PN, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004241
Devang Patela7ec47d2011-05-18 20:35:38 +00004242 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004243 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004244 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004245 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004246 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004247 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004248 }
4249 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004250 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004251 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4252 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004253 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004254 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004255 } else if (UnreachableInst *UI =
4256 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4257 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004258 } else if (IndirectBrInst *IBI =
4259 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4260 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004261 }
4262
Chris Lattner031340a2003-08-17 19:41:53 +00004263 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004264}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004265
4266/// SimplifyCFG - This function is used to do simplification of a CFG. For
4267/// example, it adjusts branches to branches to eliminate the extra hop, it
4268/// eliminates unreachable basic blocks, and does other "peephole" optimization
4269/// of the CFG. It returns true if a modification was made.
4270///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004271bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004272 const DataLayout *DL) {
4273 return SimplifyCFGOpt(TTI, DL).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004274}