blob: daa576cfbdc9fe5e2ef2c80a59439d71fc33ca54 [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"
Jingyue Wufc029672014-09-30 22:23:38 +000047#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000048#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000049#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000051using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000052using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "simplifycfg"
55
Peter Collingbourne616044a2011-04-29 18:47:38 +000056static cl::opt<unsigned>
57PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
59
Evan Chengd983eba2011-01-29 04:46:23 +000060static cl::opt<bool>
61DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
63
Manman Ren93ab6492012-09-20 22:37:36 +000064static cl::opt<bool>
65SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
67
Alp Tokercb402912014-01-24 17:20:08 +000068static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000071
Hans Wennborg39583b82012-09-26 09:44:49 +000072STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000073STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000074STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000075STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000076STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000077STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000078STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000079
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000080namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000081 // The first field contains the value that the switch produces when a certain
82 // case group is selected, and the second field is a vector containing the cases
83 // composing the case group.
84 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
85 SwitchCaseResultVectorTy;
86 // The first field contains the phi node that generates a result of the switch
87 // and the second field contains the value generated for a certain case in the switch
88 // for that PHI.
89 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
90
Eric Christopherb65acc62012-07-02 23:22:21 +000091 /// ValueEqualityComparisonCase - Represents a case of a switch.
92 struct ValueEqualityComparisonCase {
93 ConstantInt *Value;
94 BasicBlock *Dest;
95
96 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
97 : Value(Value), Dest(Dest) {}
98
99 bool operator<(ValueEqualityComparisonCase RHS) const {
100 // Comparing pointers is ok as we only rely on the order for uniquing.
101 return Value < RHS.Value;
102 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000103
104 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000105 };
106
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000107class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000108 const TargetTransformInfo &TTI;
Jingyue Wufc029672014-09-30 22:23:38 +0000109 unsigned BonusInstThreshold;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000110 const DataLayout *const DL;
Hal Finkel60db0582014-09-07 18:57:58 +0000111 AssumptionTracker *AT;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000112 Value *isValueEqualityComparison(TerminatorInst *TI);
113 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000114 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000115 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000116 BasicBlock *Pred,
117 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000118 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
119 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000120
Devang Pateldd14e0f2011-05-18 21:33:11 +0000121 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000122 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000123 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000124 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000125 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000126 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000127 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000128
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000129public:
Jingyue Wufc029672014-09-30 22:23:38 +0000130 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
131 const DataLayout *DL, AssumptionTracker *AT)
132 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133 bool run(BasicBlock *BB);
134};
135}
136
Chris Lattner76dc2042005-08-03 00:19:45 +0000137/// SafeToMergeTerminators - Return true if it is safe to merge these two
138/// terminator instructions together.
139///
140static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
141 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000142
Chris Lattner76dc2042005-08-03 00:19:45 +0000143 // It is not safe to merge these two switch instructions if they have a common
144 // successor, and if that successor has a PHI node, and if *that* PHI node has
145 // conflicting incoming values from the two switch blocks.
146 BasicBlock *SI1BB = SI1->getParent();
147 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000148 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000149
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000150 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
151 if (SI1Succs.count(*I))
152 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000153 isa<PHINode>(BBI); ++BBI) {
154 PHINode *PN = cast<PHINode>(BBI);
155 if (PN->getIncomingValueForBlock(SI1BB) !=
156 PN->getIncomingValueForBlock(SI2BB))
157 return false;
158 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000159
Chris Lattner76dc2042005-08-03 00:19:45 +0000160 return true;
161}
162
Manman Rend33f4ef2012-06-13 05:43:29 +0000163/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
164/// to merge these two terminator instructions together, where SI1 is an
165/// unconditional branch. PhiNodes will store all PHI nodes in common
166/// successors.
167///
168static bool isProfitableToFoldUnconditional(BranchInst *SI1,
169 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000170 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000171 SmallVectorImpl<PHINode*> &PhiNodes) {
172 if (SI1 == SI2) return false; // Can't merge with self!
173 assert(SI1->isUnconditional() && SI2->isConditional());
174
175 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000176 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000177 // 1> We have a constant incoming value for the conditional branch;
178 // 2> We have "Cond" as the incoming value for the unconditional branch;
179 // 3> SI2->getCondition() and Cond have same operands.
180 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
181 if (!Ci2) return false;
182 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
183 Cond->getOperand(1) == Ci2->getOperand(1)) &&
184 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
185 Cond->getOperand(1) == Ci2->getOperand(0)))
186 return false;
187
188 BasicBlock *SI1BB = SI1->getParent();
189 BasicBlock *SI2BB = SI2->getParent();
190 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000191 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
192 if (SI1Succs.count(*I))
193 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000194 isa<PHINode>(BBI); ++BBI) {
195 PHINode *PN = cast<PHINode>(BBI);
196 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000197 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000198 return false;
199 PhiNodes.push_back(PN);
200 }
201 return true;
202}
203
Chris Lattner76dc2042005-08-03 00:19:45 +0000204/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
205/// now be entries in it from the 'NewPred' block. The values that will be
206/// flowing into the PHI nodes will be the same as those coming in from
207/// ExistPred, an existing predecessor of Succ.
208static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
209 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000210 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000211
Chris Lattner80b03a12008-07-13 22:23:11 +0000212 PHINode *PN;
213 for (BasicBlock::iterator I = Succ->begin();
214 (PN = dyn_cast<PHINode>(I)); ++I)
215 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000216}
217
David Majnemer91142c42013-06-01 19:43:23 +0000218/// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000219/// given instruction, which is assumed to be safe to speculate. 1 means
220/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
Hal Finkela995f922014-07-10 14:41:31 +0000221static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
222 assert(isSafeToSpeculativelyExecute(I, DL) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000223 "Instruction is not safe to speculatively execute!");
224 switch (Operator::getOpcode(I)) {
225 default:
226 // In doubt, be conservative.
227 return UINT_MAX;
228 case Instruction::GetElementPtr:
229 // GEPs are cheap if all indices are constant.
230 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
231 return UINT_MAX;
232 return 1;
Louis Gerbarg1f54b822014-05-09 17:02:46 +0000233 case Instruction::ExtractValue:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000234 case Instruction::Load:
235 case Instruction::Add:
236 case Instruction::Sub:
237 case Instruction::And:
238 case Instruction::Or:
239 case Instruction::Xor:
240 case Instruction::Shl:
241 case Instruction::LShr:
242 case Instruction::AShr:
243 case Instruction::ICmp:
244 case Instruction::Trunc:
245 case Instruction::ZExt:
246 case Instruction::SExt:
Matt Arsenaultc8fc08c2014-05-30 18:34:43 +0000247 case Instruction::BitCast:
248 case Instruction::ExtractElement:
249 case Instruction::InsertElement:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000250 return 1; // These are all cheap.
251
252 case Instruction::Call:
253 case Instruction::Select:
254 return 2;
255 }
256}
257
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000258/// DominatesMergePoint - If we have a merge point of an "if condition" as
259/// accepted above, return true if the specified value dominates the block. We
260/// don't handle the true generality of domination here, just a special case
261/// which works well enough for us.
262///
263/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000264/// see if V (which must be an instruction) and its recursive operands
265/// that do not dominate BB have a combined cost lower than CostRemaining and
266/// are non-trapping. If both are true, the instruction is inserted into the
267/// set and true is returned.
268///
269/// The cost for most non-trapping instructions is defined as 1 except for
270/// Select whose cost is 2.
271///
272/// After this function returns, CostRemaining is decreased by the cost of
273/// V plus its non-dominating operands. If that cost is greater than
274/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000275static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000276 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000277 unsigned &CostRemaining,
278 const DataLayout *DL) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000279 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000280 if (!I) {
281 // Non-instructions all dominate instructions, but not all constantexprs
282 // can be executed unconditionally.
283 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
284 if (C->canTrap())
285 return false;
286 return true;
287 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000288 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000289
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000290 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000291 // the bottom of this block.
292 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000293
Chris Lattner0aa56562004-04-09 22:50:22 +0000294 // If this instruction is defined in a block that contains an unconditional
295 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000296 // statement". If not, it definitely dominates the region.
297 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000298 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000299 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000300
Chris Lattner9ac168d2010-12-14 07:41:39 +0000301 // If we aren't allowing aggressive promotion anymore, then don't consider
302 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000303 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000304
Peter Collingbournee3511e12011-04-29 18:47:31 +0000305 // If we have seen this instruction before, don't count it again.
306 if (AggressiveInsts->count(I)) return true;
307
Chris Lattner9ac168d2010-12-14 07:41:39 +0000308 // Okay, it looks like the instruction IS in the "condition". Check to
309 // see if it's a cheap instruction to unconditionally compute, and if it
310 // only uses stuff defined outside of the condition. If so, hoist it out.
Hal Finkela995f922014-07-10 14:41:31 +0000311 if (!isSafeToSpeculativelyExecute(I, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000312 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000313
Hal Finkela995f922014-07-10 14:41:31 +0000314 unsigned Cost = ComputeSpeculationCost(I, DL);
Chris Lattner0aa56562004-04-09 22:50:22 +0000315
Peter Collingbournee3511e12011-04-29 18:47:31 +0000316 if (Cost > CostRemaining)
317 return false;
318
319 CostRemaining -= Cost;
320
321 // Okay, we can only really hoist these out if their operands do
322 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000323 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Hal Finkela995f922014-07-10 14:41:31 +0000324 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000325 return false;
326 // Okay, it's safe to do this! Remember this instruction.
327 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000328 return true;
329}
Chris Lattner466a0492002-05-21 20:50:24 +0000330
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000331/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
332/// and PointerNullValue. Return NULL if value is not a constant int.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000333static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000334 // Normal constant int.
335 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000336 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000337 return CI;
338
339 // This is some kind of pointer constant. Turn it into a pointer-sized
340 // ConstantInt if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000341 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000342
343 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
344 if (isa<ConstantPointerNull>(V))
345 return ConstantInt::get(PtrTy, 0);
346
347 // IntToPtr const int.
348 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
349 if (CE->getOpcode() == Instruction::IntToPtr)
350 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
351 // The constant is very likely to have the right type already.
352 if (CI->getType() == PtrTy)
353 return CI;
354 else
355 return cast<ConstantInt>
356 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
357 }
Craig Topperf40110f2014-04-25 05:29:35 +0000358 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000359}
360
Mehdi Aminiffd01002014-11-20 22:40:25 +0000361namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000362
Mehdi Aminiffd01002014-11-20 22:40:25 +0000363/// Given a chain of or (||) or and (&&) comparison of a value against a
364/// constant, this will try to recover the information required for a switch
365/// structure.
366/// It will depth-first traverse the chain of comparison, seeking for patterns
367/// like %a == 12 or %a < 4 and combine them to produce a set of integer
368/// representing the different cases for the switch.
369/// Note that if the chain is composed of '||' it will build the set of elements
370/// that matches the comparisons (i.e. any of this value validate the chain)
371/// while for a chain of '&&' it will build the set elements that make the test
372/// fail.
373struct ConstantComparesGatherer {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000374
Mehdi Aminiffd01002014-11-20 22:40:25 +0000375 Value *CompValue; /// Value found for the switch comparison
376 Value *Extra; /// Extra clause to be checked before the switch
377 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
378 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000379
Mehdi Aminiffd01002014-11-20 22:40:25 +0000380 /// Construct and compute the result for the comparison instruction Cond
381 ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
382 : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
383 gather(Cond, DL);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000384 }
385
Mehdi Aminiffd01002014-11-20 22:40:25 +0000386 /// Prevent copy
387 ConstantComparesGatherer(const ConstantComparesGatherer &)
388 LLVM_DELETED_FUNCTION;
389 ConstantComparesGatherer &
390 operator=(const ConstantComparesGatherer &) LLVM_DELETED_FUNCTION;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000391
Mehdi Aminiffd01002014-11-20 22:40:25 +0000392private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000393
Mehdi Aminiffd01002014-11-20 22:40:25 +0000394 /// Try to set the current value used for the comparison, it succeeds only if
395 /// it wasn't set before or if the new value is the same as the old one
396 bool setValueOnce(Value *NewVal) {
397 if(CompValue && CompValue != NewVal) return false;
398 CompValue = NewVal;
399 return (CompValue != nullptr);
400 }
401
402 /// Try to match Instruction "I" as a comparison against a constant and
403 /// populates the array Vals with the set of values that match (or do not
404 /// match depending on isEQ).
405 /// Return false on failure. On success, the Value the comparison matched
406 /// against is placed in CompValue.
407 /// If CompValue is already set, the function is expected to fail if a match
408 /// is found but the value compared to is different.
409 bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
410 // If this is an icmp against a constant, handle this as one of the cases.
411 ICmpInst *ICI;
412 ConstantInt *C;
413 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
414 (C = GetConstantInt(I->getOperand(1), DL)))) {
415 return false;
416 }
417
418 Value *RHSVal;
419 ConstantInt *RHSC;
420
421 // Pattern match a special case
422 // (x & ~2^x) == y --> x == y || x == y|2^x
423 // This undoes a transformation done by instcombine to fuse 2 compares.
424 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
425 if (match(ICI->getOperand(0),
426 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
427 APInt Not = ~RHSC->getValue();
428 if (Not.isPowerOf2()) {
429 // If we already have a value for the switch, it has to match!
430 if(!setValueOnce(RHSVal))
431 return false;
432
433 Vals.push_back(C);
434 Vals.push_back(ConstantInt::get(C->getContext(),
435 C->getValue() | Not));
436 UsedICmps++;
437 return true;
438 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000439 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000440
441 // If we already have a value for the switch, it has to match!
442 if(!setValueOnce(ICI->getOperand(0)))
443 return false;
444
445 UsedICmps++;
446 Vals.push_back(C);
447 return ICI->getOperand(0);
448 }
449
450 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
451 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
452 C->getValue());
453
454 // Shift the range if the compare is fed by an add. This is the range
455 // compare idiom as emitted by instcombine.
456 Value *CandidateVal = I->getOperand(0);
457 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
458 Span = Span.subtract(RHSC->getValue());
459 CandidateVal = RHSVal;
460 }
461
462 // If this is an and/!= check, then we are looking to build the set of
463 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
464 // x != 0 && x != 1.
465 if (!isEQ)
466 Span = Span.inverse();
467
468 // If there are a ton of values, we don't want to make a ginormous switch.
469 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
470 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000471 }
472
473 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000474 if(!setValueOnce(CandidateVal))
475 return false;
476
477 // Add all values from the range to the set
478 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
479 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000480
481 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000482 return true;
483
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000484 }
485
Mehdi Aminiffd01002014-11-20 22:40:25 +0000486 /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
487 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
488 /// the value being compared, and stick the list constants into the Vals
489 /// vector.
490 /// One "Extra" case is allowed to differ from the other.
491 void gather(Value *V, const DataLayout *DL) {
492 Instruction *I = dyn_cast<Instruction>(V);
493 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000494
Mehdi Aminiffd01002014-11-20 22:40:25 +0000495 // Keep a stack (SmallVector for efficiency) for depth-first traversal
496 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000497
Mehdi Aminiffd01002014-11-20 22:40:25 +0000498 // Initialize
499 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000500
Mehdi Aminiffd01002014-11-20 22:40:25 +0000501 while(!DFT.empty()) {
502 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000503
Mehdi Aminiffd01002014-11-20 22:40:25 +0000504 if (Instruction *I = dyn_cast<Instruction>(V)) {
505 // If it is a || (or && depending on isEQ), process the operands.
506 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
507 DFT.push_back(I->getOperand(1));
508 DFT.push_back(I->getOperand(0));
509 continue;
510 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000511
Mehdi Aminiffd01002014-11-20 22:40:25 +0000512 // Try to match the current instruction
513 if (matchInstruction(I, DL, isEQ))
514 // Match succeed, continue the loop
515 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000516 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000517
Mehdi Aminiffd01002014-11-20 22:40:25 +0000518 // One element of the sequence of || (or &&) could not be match as a
519 // comparison against the same value as the others.
520 // We allow only one "Extra" case to be checked before the switch
521 if (!Extra) {
522 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000523 continue;
524 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000525 // Failed to parse a proper sequence, abort now
526 CompValue = nullptr;
527 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000528 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000529 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000530};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000531
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000532}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000533
Eli Friedmancb61afb2008-12-16 20:54:32 +0000534static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000535 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000536 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
537 Cond = dyn_cast<Instruction>(SI->getCondition());
538 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
539 if (BI->isConditional())
540 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000541 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
542 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000543 }
544
545 TI->eraseFromParent();
546 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
547}
548
Chris Lattner8e84c122008-11-27 23:25:44 +0000549/// isValueEqualityComparison - Return true if the specified terminator checks
550/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000551Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000552 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000553 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
554 // Do not permit merging of large switch instructions into their
555 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000556 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
557 pred_end(SI->getParent())) <= 128)
558 CV = SI->getCondition();
559 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000560 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000561 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000562 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000563 CV = ICI->getOperand(0);
564
565 // Unwrap any lossless ptrtoint cast.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000566 if (DL && CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000567 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
568 Value *Ptr = PTII->getPointerOperand();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000569 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000570 CV = Ptr;
571 }
572 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000573 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000574}
575
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000576/// GetValueEqualityComparisonCases - Given a value comparison instruction,
577/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000578BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000579GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000580 std::vector<ValueEqualityComparisonCase>
581 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000582 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000583 Cases.reserve(SI->getNumCases());
584 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
585 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
586 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000587 return SI->getDefaultDest();
588 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000589
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000590 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000591 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000592 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
593 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000594 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000595 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000596 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000597}
598
Eric Christopherb65acc62012-07-02 23:22:21 +0000599
600/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
601/// in the list that match the specified block.
602static void EliminateBlockCases(BasicBlock *BB,
603 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000604 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000605}
606
607/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
608/// well.
609static bool
610ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
611 std::vector<ValueEqualityComparisonCase > &C2) {
612 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
613
614 // Make V1 be smaller than V2.
615 if (V1->size() > V2->size())
616 std::swap(V1, V2);
617
618 if (V1->size() == 0) return false;
619 if (V1->size() == 1) {
620 // Just scan V2.
621 ConstantInt *TheVal = (*V1)[0].Value;
622 for (unsigned i = 0, e = V2->size(); i != e; ++i)
623 if (TheVal == (*V2)[i].Value)
624 return true;
625 }
626
627 // Otherwise, just sort both lists and compare element by element.
628 array_pod_sort(V1->begin(), V1->end());
629 array_pod_sort(V2->begin(), V2->end());
630 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
631 while (i1 != e1 && i2 != e2) {
632 if ((*V1)[i1].Value == (*V2)[i2].Value)
633 return true;
634 if ((*V1)[i1].Value < (*V2)[i2].Value)
635 ++i1;
636 else
637 ++i2;
638 }
639 return false;
640}
641
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000642/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
643/// terminator instruction and its block is known to only have a single
644/// predecessor block, check to see if that predecessor is also a value
645/// comparison with the same value, and if that comparison determines the
646/// outcome of this comparison. If so, simplify TI. This does a very limited
647/// form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000648bool SimplifyCFGOpt::
649SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000650 BasicBlock *Pred,
651 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000652 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
653 if (!PredVal) return false; // Not a value comparison in predecessor.
654
655 Value *ThisVal = isValueEqualityComparison(TI);
656 assert(ThisVal && "This isn't a value comparison!!");
657 if (ThisVal != PredVal) return false; // Different predicates.
658
Andrew Trick3051aa12012-08-29 21:46:38 +0000659 // TODO: Preserve branch weight metadata, similarly to how
660 // FoldValueComparisonIntoPredecessors preserves it.
661
Chris Lattner1cca9592005-02-24 06:17:52 +0000662 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000663 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000664 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
665 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000666 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000667
Chris Lattner1cca9592005-02-24 06:17:52 +0000668 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000669 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000670 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000671 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000672
673 // If TI's block is the default block from Pred's comparison, potentially
674 // simplify TI based on this knowledge.
675 if (PredDef == TI->getParent()) {
676 // If we are here, we know that the value is none of those cases listed in
677 // PredCases. If there are any cases in ThisCases that are in PredCases, we
678 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000679 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000680 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000681
Chris Lattner4088e2b2010-12-13 01:47:07 +0000682 if (isa<BranchInst>(TI)) {
683 // Okay, one of the successors of this condbr is dead. Convert it to a
684 // uncond br.
685 assert(ThisCases.size() == 1 && "Branch can only have one case!");
686 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000687 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000688 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000689
Chris Lattner4088e2b2010-12-13 01:47:07 +0000690 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000691 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000692
Chris Lattner4088e2b2010-12-13 01:47:07 +0000693 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
694 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000695
Chris Lattner4088e2b2010-12-13 01:47:07 +0000696 EraseTerminatorInstAndDCECond(TI);
697 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000698 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000699
Chris Lattner4088e2b2010-12-13 01:47:07 +0000700 SwitchInst *SI = cast<SwitchInst>(TI);
701 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000702 SmallPtrSet<Constant*, 16> DeadCases;
703 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
704 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000705
David Greene725c7c32010-01-05 01:26:52 +0000706 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000707 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000708
Manman Ren8691e522012-09-14 21:53:06 +0000709 // Collect branch weights into a vector.
710 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000711 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000712 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
713 if (HasWeight)
714 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
715 ++MD_i) {
716 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
717 assert(CI);
718 Weights.push_back(CI->getValue().getZExtValue());
719 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000720 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
721 --i;
722 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000723 if (HasWeight) {
724 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
725 Weights.pop_back();
726 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000727 i.getCaseSuccessor()->removePredecessor(TI->getParent());
728 SI->removeCase(i);
729 }
730 }
Manman Ren97c18762012-10-11 22:28:34 +0000731 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000732 SI->setMetadata(LLVMContext::MD_prof,
733 MDBuilder(SI->getParent()->getContext()).
734 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000735
736 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000737 return true;
738 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000739
Chris Lattner4088e2b2010-12-13 01:47:07 +0000740 // Otherwise, TI's block must correspond to some matched value. Find out
741 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000742 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000743 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000744 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
745 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000746 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000747 return false; // Cannot handle multiple values coming to this block.
748 TIV = PredCases[i].Value;
749 }
750 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000751
752 // Okay, we found the one constant that our value can be if we get into TI's
753 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000754 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000755 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
756 if (ThisCases[i].Value == TIV) {
757 TheRealDest = ThisCases[i].Dest;
758 break;
759 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000760
761 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000762 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000763
764 // Remove PHI node entries for dead edges.
765 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000766 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
767 if (*SI != CheckEdge)
768 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000769 else
Craig Topperf40110f2014-04-25 05:29:35 +0000770 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000771
772 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000773 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000774 (void) NI;
775
776 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
777 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
778
779 EraseTerminatorInstAndDCECond(TI);
780 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000781}
782
Dale Johannesen7f99d222009-03-12 21:01:11 +0000783namespace {
784 /// ConstantIntOrdering - This class implements a stable ordering of constant
785 /// integers that does not depend on their address. This is important for
786 /// applications that sort ConstantInt's to ensure uniqueness.
787 struct ConstantIntOrdering {
788 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
789 return LHS->getValue().ult(RHS->getValue());
790 }
791 };
792}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000793
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000794static int ConstantIntSortPredicate(ConstantInt *const *P1,
795 ConstantInt *const *P2) {
796 const ConstantInt *LHS = *P1;
797 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000798 if (LHS->getValue().ult(RHS->getValue()))
799 return 1;
800 if (LHS->getValue() == RHS->getValue())
801 return 0;
802 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000803}
804
Andrew Trick3051aa12012-08-29 21:46:38 +0000805static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000806 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000807 if (ProfMD && ProfMD->getOperand(0))
808 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
809 return MDS->getString().equals("branch_weights");
810
811 return false;
812}
813
Manman Ren571d9e42012-09-11 17:43:35 +0000814/// Get Weights of a given TerminatorInst, the default weight is at the front
815/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
816/// metadata.
817static void GetBranchWeights(TerminatorInst *TI,
818 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000819 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000820 assert(MD);
821 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000822 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000823 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000824 }
825
Manman Ren571d9e42012-09-11 17:43:35 +0000826 // If TI is a conditional eq, the default case is the false case,
827 // and the corresponding branch-weight data is at index 2. We swap the
828 // default weight to be the first entry.
829 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
830 assert(Weights.size() == 2);
831 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
832 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
833 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000834 }
835}
836
Manman Renf1cb16e2014-01-27 23:39:03 +0000837/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000838static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000839 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
840 if (Max > UINT_MAX) {
841 unsigned Offset = 32 - countLeadingZeros(Max);
842 for (uint64_t &I : Weights)
843 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000844 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000845}
846
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000847/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
848/// equality comparison instruction (either a switch or a branch on "X == c").
849/// See if any of the predecessors of the terminator block are value comparisons
850/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000851bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
852 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000853 BasicBlock *BB = TI->getParent();
854 Value *CV = isValueEqualityComparison(TI); // CondVal
855 assert(CV && "Not a comparison?");
856 bool Changed = false;
857
Chris Lattner6b39cb92008-02-18 07:42:56 +0000858 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000859 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000860 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000861
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000862 // See if the predecessor is a comparison with the same value.
863 TerminatorInst *PTI = Pred->getTerminator();
864 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
865
866 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
867 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000868 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000869 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
870
Eric Christopherb65acc62012-07-02 23:22:21 +0000871 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000872 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
873
874 // Based on whether the default edge from PTI goes to BB or not, fill in
875 // PredCases and PredDefault with the new switch cases we would like to
876 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000877 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000878
Andrew Trick3051aa12012-08-29 21:46:38 +0000879 // Update the branch weight metadata along the way
880 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000881 bool PredHasWeights = HasBranchWeights(PTI);
882 bool SuccHasWeights = HasBranchWeights(TI);
883
Manman Ren5e5049d2012-09-14 19:05:19 +0000884 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000885 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000886 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000887 if (Weights.size() != 1 + PredCases.size())
888 PredHasWeights = SuccHasWeights = false;
889 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000890 // If there are no predecessor weights but there are successor weights,
891 // populate Weights with 1, which will later be scaled to the sum of
892 // successor's weights
893 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000894
Manman Ren571d9e42012-09-11 17:43:35 +0000895 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000896 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000897 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000898 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000899 if (SuccWeights.size() != 1 + BBCases.size())
900 PredHasWeights = SuccHasWeights = false;
901 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000902 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000903
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000904 if (PredDefault == BB) {
905 // If this is the default destination from PTI, only the edges in TI
906 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000907 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
908 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
909 if (PredCases[i].Dest != BB)
910 PTIHandled.insert(PredCases[i].Value);
911 else {
912 // The default destination is BB, we don't need explicit targets.
913 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000914
Manman Ren571d9e42012-09-11 17:43:35 +0000915 if (PredHasWeights || SuccHasWeights) {
916 // Increase weight for the default case.
917 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000918 std::swap(Weights[i+1], Weights.back());
919 Weights.pop_back();
920 }
921
Eric Christopherb65acc62012-07-02 23:22:21 +0000922 PredCases.pop_back();
923 --i; --e;
924 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000925
Eric Christopherb65acc62012-07-02 23:22:21 +0000926 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000927 if (PredDefault != BBDefault) {
928 PredDefault->removePredecessor(Pred);
929 PredDefault = BBDefault;
930 NewSuccessors.push_back(BBDefault);
931 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000932
Manman Ren571d9e42012-09-11 17:43:35 +0000933 unsigned CasesFromPred = Weights.size();
934 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000935 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
936 if (!PTIHandled.count(BBCases[i].Value) &&
937 BBCases[i].Dest != BBDefault) {
938 PredCases.push_back(BBCases[i]);
939 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000940 if (SuccHasWeights || PredHasWeights) {
941 // The default weight is at index 0, so weight for the ith case
942 // should be at index i+1. Scale the cases from successor by
943 // PredDefaultWeight (Weights[0]).
944 Weights.push_back(Weights[0] * SuccWeights[i+1]);
945 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000946 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000947 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000948
Manman Ren571d9e42012-09-11 17:43:35 +0000949 if (SuccHasWeights || PredHasWeights) {
950 ValidTotalSuccWeight += SuccWeights[0];
951 // Scale the cases from predecessor by ValidTotalSuccWeight.
952 for (unsigned i = 1; i < CasesFromPred; ++i)
953 Weights[i] *= ValidTotalSuccWeight;
954 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
955 Weights[0] *= SuccWeights[0];
956 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000957 } else {
958 // If this is not the default destination from PSI, only the edges
959 // in SI that occur in PSI with a destination of BB will be
960 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000961 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000962 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000963 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
964 if (PredCases[i].Dest == BB) {
965 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000966
967 if (PredHasWeights || SuccHasWeights) {
968 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
969 std::swap(Weights[i+1], Weights.back());
970 Weights.pop_back();
971 }
972
Eric Christopherb65acc62012-07-02 23:22:21 +0000973 std::swap(PredCases[i], PredCases.back());
974 PredCases.pop_back();
975 --i; --e;
976 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000977
978 // Okay, now we know which constants were sent to BB from the
979 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000980 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
981 if (PTIHandled.count(BBCases[i].Value)) {
982 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000983 if (PredHasWeights || SuccHasWeights)
984 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000985 PredCases.push_back(BBCases[i]);
986 NewSuccessors.push_back(BBCases[i].Dest);
987 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
988 }
989
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000990 // If there are any constants vectored to BB that TI doesn't handle,
991 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000992 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000993 PTIHandled.begin(),
994 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000995 if (PredHasWeights || SuccHasWeights)
996 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000997 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000998 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000999 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001000 }
1001
1002 // Okay, at this point, we know which new successor Pred will get. Make
1003 // sure we update the number of entries in the PHI nodes for these
1004 // successors.
1005 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
1006 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
1007
Devang Patel58380552011-05-18 20:53:17 +00001008 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001009 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001010 if (CV->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001011 assert(DL && "Cannot switch on pointer without DataLayout");
1012 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001013 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001014 }
1015
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001016 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +00001017 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1018 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001019 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +00001020 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1021 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001022
Andrew Trick3051aa12012-08-29 21:46:38 +00001023 if (PredHasWeights || SuccHasWeights) {
1024 // Halve the weights if any of them cannot fit in an uint32_t
1025 FitWeights(Weights);
1026
1027 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1028
1029 NewSI->setMetadata(LLVMContext::MD_prof,
1030 MDBuilder(BB->getContext()).
1031 createBranchWeights(MDWeights));
1032 }
1033
Eli Friedmancb61afb2008-12-16 20:54:32 +00001034 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001035
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001036 // Okay, last check. If BB is still a successor of PSI, then we must
1037 // have an infinite loop case. If so, add an infinitely looping block
1038 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001039 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001040 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1041 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001042 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001043 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001044 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001045 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1046 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001047 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001048 }
1049 NewSI->setSuccessor(i, InfLoopBlock);
1050 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001051
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001052 Changed = true;
1053 }
1054 }
1055 return Changed;
1056}
1057
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001058// isSafeToHoistInvoke - If we would need to insert a select that uses the
1059// value of this invoke (comments in HoistThenElseCodeToIf explain why we
1060// would need to do this), we can't hoist the invoke, as there is nowhere
1061// to put the select in this case.
1062static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1063 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001064 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001065 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001066 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001067 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1068 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1069 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1070 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1071 return false;
1072 }
1073 }
1074 }
1075 return true;
1076}
1077
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001078static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1079
Chris Lattnerd683bdd2005-08-03 17:59:45 +00001080/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +00001081/// BB2, hoist any common code in the two blocks up into the branch block. The
1082/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Hal Finkela995f922014-07-10 14:41:31 +00001083static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001084 // This does very trivial matching, with limited scanning, to find identical
1085 // instructions in the two blocks. In particular, we don't want to get into
1086 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1087 // such, we currently just scan for obviously identical instructions in an
1088 // identical order.
1089 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1090 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1091
Devang Patelf10e2872009-02-04 00:03:08 +00001092 BasicBlock::iterator BB1_Itr = BB1->begin();
1093 BasicBlock::iterator BB2_Itr = BB2->begin();
1094
1095 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001096 // Skip debug info if it is not identical.
1097 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1098 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1099 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1100 while (isa<DbgInfoIntrinsic>(I1))
1101 I1 = BB1_Itr++;
1102 while (isa<DbgInfoIntrinsic>(I2))
1103 I2 = BB2_Itr++;
1104 }
Devang Patele48ddf82011-04-07 00:30:15 +00001105 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001106 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001107 return false;
1108
Chris Lattner389cfac2004-11-30 00:29:14 +00001109 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001110
David Majnemerc82f27a2013-06-03 20:43:12 +00001111 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001112 do {
1113 // If we are hoisting the terminator instruction, don't move one (making a
1114 // broken BB), instead clone it, and remove BI.
1115 if (isa<TerminatorInst>(I1))
1116 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001117
Chris Lattner389cfac2004-11-30 00:29:14 +00001118 // For a normal instruction, we just move one to right before the branch,
1119 // then replace all uses of the other with the first. Finally, we remove
1120 // the now redundant second instruction.
1121 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1122 if (!I2->use_empty())
1123 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001124 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001125 unsigned KnownIDs[] = {
1126 LLVMContext::MD_tbaa,
1127 LLVMContext::MD_range,
1128 LLVMContext::MD_fpmath,
Philip Reamesd92c2a72014-10-22 16:37:13 +00001129 LLVMContext::MD_invariant_load,
1130 LLVMContext::MD_nonnull
Rafael Espindolaea46c322014-08-15 15:46:38 +00001131 };
1132 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001133 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001134 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001135
Devang Patelf10e2872009-02-04 00:03:08 +00001136 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001137 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001138 // Skip debug info if it is not identical.
1139 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1140 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1141 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1142 while (isa<DbgInfoIntrinsic>(I1))
1143 I1 = BB1_Itr++;
1144 while (isa<DbgInfoIntrinsic>(I2))
1145 I2 = BB2_Itr++;
1146 }
Devang Patele48ddf82011-04-07 00:30:15 +00001147 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001148
1149 return true;
1150
1151HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001152 // It may not be possible to hoist an invoke.
1153 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001154 return Changed;
1155
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001156 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001157 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001158 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001159 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1160 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1161 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1162 if (BB1V == BB2V)
1163 continue;
1164
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001165 // Check for passingValueIsAlwaysUndefined here because we would rather
1166 // eliminate undefined control flow then converting it to a select.
1167 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1168 passingValueIsAlwaysUndefined(BB2V, PN))
1169 return Changed;
1170
Hal Finkela995f922014-07-10 14:41:31 +00001171 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001172 return Changed;
Hal Finkela995f922014-07-10 14:41:31 +00001173 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001174 return Changed;
1175 }
1176 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001177
Chris Lattner389cfac2004-11-30 00:29:14 +00001178 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001179 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001180 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001181 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001182 I1->replaceAllUsesWith(NT);
1183 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001184 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001185 }
1186
Devang Patel1407fb42011-05-19 20:52:46 +00001187 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001188 // Hoisting one of the terminators from our successor is a great thing.
1189 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1190 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1191 // nodes, so we insert select instruction to compute the final result.
1192 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001193 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001194 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001195 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001196 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001197 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1198 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001199 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001200
Chris Lattner4088e2b2010-12-13 01:47:07 +00001201 // These values do not agree. Insert a select instruction before NT
1202 // that determines the right value.
1203 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001204 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001205 SI = cast<SelectInst>
1206 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1207 BB1V->getName()+"."+BB2V->getName()));
1208
Chris Lattner4088e2b2010-12-13 01:47:07 +00001209 // Make the PHI node use the select for all incoming values for BB1/BB2
1210 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1211 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1212 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001213 }
1214 }
1215
1216 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001217 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1218 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001219
Eli Friedmancb61afb2008-12-16 20:54:32 +00001220 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001221 return true;
1222}
1223
Manman Ren93ab6492012-09-20 22:37:36 +00001224/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1225/// check whether BBEnd has only two predecessors and the other predecessor
1226/// ends with an unconditional branch. If it is true, sink any common code
1227/// in the two predecessors to BBEnd.
1228static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1229 assert(BI1->isUnconditional());
1230 BasicBlock *BB1 = BI1->getParent();
1231 BasicBlock *BBEnd = BI1->getSuccessor(0);
1232
1233 // Check that BBEnd has two predecessors and the other predecessor ends with
1234 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001235 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1236 BasicBlock *Pred0 = *PI++;
1237 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001238 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001239 BasicBlock *Pred1 = *PI++;
1240 if (PI != PE) // More than two predecessors.
1241 return false;
1242 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001243 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1244 if (!BI2 || !BI2->isUnconditional())
1245 return false;
1246
1247 // Gather the PHI nodes in BBEnd.
1248 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
Craig Topperf40110f2014-04-25 05:29:35 +00001249 Instruction *FirstNonPhiInBBEnd = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001250 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1251 I != E; ++I) {
1252 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1253 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001254 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Manman Ren93ab6492012-09-20 22:37:36 +00001255 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1256 } else {
1257 FirstNonPhiInBBEnd = &*I;
1258 break;
1259 }
1260 }
1261 if (!FirstNonPhiInBBEnd)
1262 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001263
Manman Ren93ab6492012-09-20 22:37:36 +00001264
1265 // This does very trivial matching, with limited scanning, to find identical
1266 // instructions in the two blocks. We scan backward for obviously identical
1267 // instructions in an identical order.
1268 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1269 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1270 RE2 = BB2->getInstList().rend();
1271 // Skip debug info.
1272 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1273 if (RI1 == RE1)
1274 return false;
1275 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1276 if (RI2 == RE2)
1277 return false;
1278 // Skip the unconditional branches.
1279 ++RI1;
1280 ++RI2;
1281
1282 bool Changed = false;
1283 while (RI1 != RE1 && RI2 != RE2) {
1284 // Skip debug info.
1285 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1286 if (RI1 == RE1)
1287 return Changed;
1288 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1289 if (RI2 == RE2)
1290 return Changed;
1291
1292 Instruction *I1 = &*RI1, *I2 = &*RI2;
1293 // I1 and I2 should have a single use in the same PHI node, and they
1294 // perform the same operation.
1295 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1296 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1297 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1298 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1299 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1300 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1301 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1302 !I1->hasOneUse() || !I2->hasOneUse() ||
1303 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1304 MapValueFromBB1ToBB2[I1].first != I2)
1305 return Changed;
1306
1307 // Check whether we should swap the operands of ICmpInst.
1308 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1309 bool SwapOpnds = false;
1310 if (ICmp1 && ICmp2 &&
1311 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1312 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1313 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1314 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1315 ICmp2->swapOperands();
1316 SwapOpnds = true;
1317 }
1318 if (!I1->isSameOperationAs(I2)) {
1319 if (SwapOpnds)
1320 ICmp2->swapOperands();
1321 return Changed;
1322 }
1323
1324 // The operands should be either the same or they need to be generated
1325 // with a PHI node after sinking. We only handle the case where there is
1326 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001327 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001328 unsigned Op1Idx = 0;
1329 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1330 if (I1->getOperand(I) == I2->getOperand(I))
1331 continue;
1332 // Early exit if we have more-than one pair of different operands or
1333 // the different operand is already in MapValueFromBB1ToBB2.
1334 // Early exit if we need a PHI node to replace a constant.
1335 if (DifferentOp1 ||
1336 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1337 MapValueFromBB1ToBB2.end() ||
1338 isa<Constant>(I1->getOperand(I)) ||
1339 isa<Constant>(I2->getOperand(I))) {
1340 // If we can't sink the instructions, undo the swapping.
1341 if (SwapOpnds)
1342 ICmp2->swapOperands();
1343 return Changed;
1344 }
1345 DifferentOp1 = I1->getOperand(I);
1346 Op1Idx = I;
1347 DifferentOp2 = I2->getOperand(I);
1348 }
1349
1350 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1351 // remove (I1, I2) from MapValueFromBB1ToBB2.
1352 if (DifferentOp1) {
1353 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1354 DifferentOp1->getName() + ".sink",
1355 BBEnd->begin());
1356 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1357 // I1 should use NewPN instead of DifferentOp1.
1358 I1->setOperand(Op1Idx, NewPN);
1359 NewPN->addIncoming(DifferentOp1, BB1);
1360 NewPN->addIncoming(DifferentOp2, BB2);
1361 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1362 }
1363 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1364 MapValueFromBB1ToBB2.erase(I1);
1365
1366 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1367 DEBUG(dbgs() << " " << *I2 << "\n";);
1368 // We need to update RE1 and RE2 if we are going to sink the first
1369 // instruction in the basic block down.
1370 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1371 // Sink the instruction.
1372 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1373 if (!OldPN->use_empty())
1374 OldPN->replaceAllUsesWith(I1);
1375 OldPN->eraseFromParent();
1376
1377 if (!I2->use_empty())
1378 I2->replaceAllUsesWith(I1);
1379 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001380 // TODO: Use combineMetadata here to preserve what metadata we can
1381 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001382 I2->eraseFromParent();
1383
1384 if (UpdateRE1)
1385 RE1 = BB1->getInstList().rend();
1386 if (UpdateRE2)
1387 RE2 = BB2->getInstList().rend();
1388 FirstNonPhiInBBEnd = I1;
1389 NumSinkCommons++;
1390 Changed = true;
1391 }
1392 return Changed;
1393}
1394
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001395/// \brief Determine if we can hoist sink a sole store instruction out of a
1396/// conditional block.
1397///
1398/// We are looking for code like the following:
1399/// BrBB:
1400/// store i32 %add, i32* %arrayidx2
1401/// ... // No other stores or function calls (we could be calling a memory
1402/// ... // function).
1403/// %cmp = icmp ult %x, %y
1404/// br i1 %cmp, label %EndBB, label %ThenBB
1405/// ThenBB:
1406/// store i32 %add5, i32* %arrayidx2
1407/// br label EndBB
1408/// EndBB:
1409/// ...
1410/// We are going to transform this into:
1411/// BrBB:
1412/// store i32 %add, i32* %arrayidx2
1413/// ... //
1414/// %cmp = icmp ult %x, %y
1415/// %add.add5 = select i1 %cmp, i32 %add, %add5
1416/// store i32 %add.add5, i32* %arrayidx2
1417/// ...
1418///
1419/// \return The pointer to the value of the previous store if the store can be
1420/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001421static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1422 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001423 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1424 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001425 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001426
1427 // Volatile or atomic.
1428 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001429 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001430
1431 Value *StorePtr = StoreToHoist->getPointerOperand();
1432
1433 // Look for a store to the same pointer in BrBB.
1434 unsigned MaxNumInstToLookAt = 10;
1435 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1436 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1437 Instruction *CurI = &*RI;
1438
1439 // Could be calling an instruction that effects memory like free().
1440 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001441 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001442
1443 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1444 // Found the previous store make sure it stores to the same location.
1445 if (SI && SI->getPointerOperand() == StorePtr)
1446 // Found the previous store, return its value operand.
1447 return SI->getValueOperand();
1448 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001449 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001450 }
1451
Craig Topperf40110f2014-04-25 05:29:35 +00001452 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001453}
1454
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001455/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001456///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001457/// Note that this is a very risky transform currently. Speculating
1458/// instructions like this is most often not desirable. Instead, there is an MI
1459/// pass which can do it with full awareness of the resource constraints.
1460/// However, some cases are "obvious" and we should do directly. An example of
1461/// this is speculating a single, reasonably cheap instruction.
1462///
1463/// There is only one distinct advantage to flattening the CFG at the IR level:
1464/// it makes very common but simplistic optimizations such as are common in
1465/// instcombine and the DAG combiner more powerful by removing CFG edges and
1466/// modeling their effects with easier to reason about SSA value graphs.
1467///
1468///
1469/// An illustration of this transform is turning this IR:
1470/// \code
1471/// BB:
1472/// %cmp = icmp ult %x, %y
1473/// br i1 %cmp, label %EndBB, label %ThenBB
1474/// ThenBB:
1475/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001476/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001477/// EndBB:
1478/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1479/// ...
1480/// \endcode
1481///
1482/// Into this IR:
1483/// \code
1484/// BB:
1485/// %cmp = icmp ult %x, %y
1486/// %sub = sub %x, %y
1487/// %cond = select i1 %cmp, 0, %sub
1488/// ...
1489/// \endcode
1490///
1491/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001492static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1493 const DataLayout *DL) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001494 // Be conservative for now. FP select instruction can often be expensive.
1495 Value *BrCond = BI->getCondition();
1496 if (isa<FCmpInst>(BrCond))
1497 return false;
1498
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001499 BasicBlock *BB = BI->getParent();
1500 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1501
1502 // If ThenBB is actually on the false edge of the conditional branch, remember
1503 // to swap the select operands later.
1504 bool Invert = false;
1505 if (ThenBB != BI->getSuccessor(0)) {
1506 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1507 Invert = true;
1508 }
1509 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1510
Chandler Carruthceff2222013-01-25 05:40:09 +00001511 // Keep a count of how many times instructions are used within CondBB when
1512 // they are candidates for sinking into CondBB. Specifically:
1513 // - They are defined in BB, and
1514 // - They have no side effects, and
1515 // - All of their uses are in CondBB.
1516 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1517
Chandler Carruth7481ca82013-01-24 11:52:58 +00001518 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001519 Value *SpeculatedStoreValue = nullptr;
1520 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001521 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001522 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001523 BBI != BBE; ++BBI) {
1524 Instruction *I = BBI;
1525 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001526 if (isa<DbgInfoIntrinsic>(I))
1527 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001528
Chandler Carruth7481ca82013-01-24 11:52:58 +00001529 // Only speculatively execution a single instruction (not counting the
1530 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001531 ++SpeculationCost;
1532 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001533 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001534
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001535 // Don't hoist the instruction if it's unsafe or expensive.
Hal Finkela995f922014-07-10 14:41:31 +00001536 if (!isSafeToSpeculativelyExecute(I, DL) &&
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001537 !(HoistCondStores &&
1538 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1539 EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001540 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001541 if (!SpeculatedStoreValue &&
Hal Finkela995f922014-07-10 14:41:31 +00001542 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001543 return false;
1544
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001545 // Store the store speculation candidate.
1546 if (SpeculatedStoreValue)
1547 SpeculatedStore = cast<StoreInst>(I);
1548
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001549 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001550 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001551 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001552 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001553 i != e; ++i) {
1554 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001555 if (!OpI || OpI->getParent() != BB ||
1556 OpI->mayHaveSideEffects())
1557 continue; // Not a candidate for sinking.
1558
1559 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001560 }
1561 }
Evan Cheng89200c92008-06-07 08:52:29 +00001562
Chandler Carruthceff2222013-01-25 05:40:09 +00001563 // Consider any sink candidates which are only used in CondBB as costs for
1564 // speculation. Note, while we iterate over a DenseMap here, we are summing
1565 // and so iteration order isn't significant.
1566 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1567 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1568 I != E; ++I)
1569 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001570 ++SpeculationCost;
1571 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001572 return false;
1573 }
1574
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001575 // Check that the PHI nodes can be converted to selects.
1576 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001577 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001578 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001579 Value *OrigV = PN->getIncomingValueForBlock(BB);
1580 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001581
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001582 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001583 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001584 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001585 continue;
1586
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001587 // Don't convert to selects if we could remove undefined behavior instead.
1588 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1589 passingValueIsAlwaysUndefined(ThenV, PN))
1590 return false;
1591
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001592 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001593 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1594 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1595 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001596 continue; // Known safe and cheap.
1597
Hal Finkela995f922014-07-10 14:41:31 +00001598 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1599 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001600 return false;
Hal Finkela995f922014-07-10 14:41:31 +00001601 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1602 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001603 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
Chandler Carruth8a210052013-01-24 11:53:01 +00001604 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001605
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001606 // Account for the cost of an unfolded ConstantExpr which could end up
1607 // getting expanded into Instructions.
1608 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001609 // constant expression.
1610 ++SpeculationCost;
1611 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001612 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001613 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001614
1615 // If there are no PHIs to process, bail early. This helps ensure idempotence
1616 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001617 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001618 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001619
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001620 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001621 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001622
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001623 // Insert a select of the value of the speculated store.
1624 if (SpeculatedStoreValue) {
1625 IRBuilder<true, NoFolder> Builder(BI);
1626 Value *TrueV = SpeculatedStore->getValueOperand();
1627 Value *FalseV = SpeculatedStoreValue;
1628 if (Invert)
1629 std::swap(TrueV, FalseV);
1630 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1631 "." + FalseV->getName());
1632 SpeculatedStore->setOperand(0, S);
1633 }
1634
Chandler Carruth7481ca82013-01-24 11:52:58 +00001635 // Hoist the instructions.
1636 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001637 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001638
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001639 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001640 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001641 for (BasicBlock::iterator I = EndBB->begin();
1642 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1643 unsigned OrigI = PN->getBasicBlockIndex(BB);
1644 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1645 Value *OrigV = PN->getIncomingValue(OrigI);
1646 Value *ThenV = PN->getIncomingValue(ThenI);
1647
1648 // Skip PHIs which are trivial.
1649 if (OrigV == ThenV)
1650 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001651
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001652 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001653 // false value is the preexisting value. Swap them if the branch
1654 // destinations were inverted.
1655 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001656 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001657 std::swap(TrueV, FalseV);
1658 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1659 TrueV->getName() + "." + FalseV->getName());
1660 PN->setIncomingValue(OrigI, V);
1661 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001662 }
1663
Evan Cheng89553cc2008-06-12 21:15:59 +00001664 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001665 return true;
1666}
1667
Tom Stellarde1631dd2013-10-21 20:07:30 +00001668/// \returns True if this block contains a CallInst with the NoDuplicate
1669/// attribute.
1670static bool HasNoDuplicateCall(const BasicBlock *BB) {
1671 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1672 const CallInst *CI = dyn_cast<CallInst>(I);
1673 if (!CI)
1674 continue;
1675 if (CI->cannotDuplicate())
1676 return true;
1677 }
1678 return false;
1679}
1680
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001681/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1682/// across this block.
1683static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1684 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001685 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001686
Devang Patel84fceff2009-03-10 18:00:05 +00001687 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001688 if (isa<DbgInfoIntrinsic>(BBI))
1689 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001690 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001691 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001692
Dale Johannesened6f5a82009-03-12 23:18:09 +00001693 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001694 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001695 for (User *U : BBI->users()) {
1696 Instruction *UI = cast<Instruction>(U);
1697 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001698 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001699
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001700 // Looks ok, continue checking.
1701 }
Chris Lattner6c701062005-09-20 01:48:40 +00001702
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001703 return true;
1704}
1705
Chris Lattner748f9032005-09-19 23:49:37 +00001706/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1707/// that is defined in the same block as the branch and if any PHI entries are
1708/// constants, thread edges corresponding to that entry to be branches to their
1709/// ultimate destination.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001710static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001711 BasicBlock *BB = BI->getParent();
1712 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001713 // NOTE: we currently cannot transform this case if the PHI node is used
1714 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001715 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1716 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001717
Chris Lattner748f9032005-09-19 23:49:37 +00001718 // Degenerate case of a single entry PHI.
1719 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001720 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001721 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001722 }
1723
1724 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001725 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001726
Tom Stellarde1631dd2013-10-21 20:07:30 +00001727 if (HasNoDuplicateCall(BB)) return false;
1728
Chris Lattner748f9032005-09-19 23:49:37 +00001729 // Okay, this is a simple enough basic block. See if any phi values are
1730 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001731 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001732 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001733 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001734
Chris Lattner4088e2b2010-12-13 01:47:07 +00001735 // Okay, we now know that all edges from PredBB should be revectored to
1736 // branch to RealDest.
1737 BasicBlock *PredBB = PN->getIncomingBlock(i);
1738 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001739
Chris Lattner4088e2b2010-12-13 01:47:07 +00001740 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001741 // Skip if the predecessor's terminator is an indirect branch.
1742 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001743
Chris Lattner4088e2b2010-12-13 01:47:07 +00001744 // The dest block might have PHI nodes, other predecessors and other
1745 // difficult cases. Instead of being smart about this, just insert a new
1746 // block that jumps to the destination block, effectively splitting
1747 // the edge we are about to create.
1748 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1749 RealDest->getName()+".critedge",
1750 RealDest->getParent(), RealDest);
1751 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001752
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001753 // Update PHI nodes.
1754 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001755
1756 // BB may have instructions that are being threaded over. Clone these
1757 // instructions into EdgeBB. We know that there will be no uses of the
1758 // cloned instructions outside of EdgeBB.
1759 BasicBlock::iterator InsertPt = EdgeBB->begin();
1760 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1761 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1762 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1763 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1764 continue;
1765 }
1766 // Clone the instruction.
1767 Instruction *N = BBI->clone();
1768 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001769
Chris Lattner4088e2b2010-12-13 01:47:07 +00001770 // Update operands due to translation.
1771 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1772 i != e; ++i) {
1773 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1774 if (PI != TranslateMap.end())
1775 *i = PI->second;
1776 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001777
Chris Lattner4088e2b2010-12-13 01:47:07 +00001778 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001779 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001780 TranslateMap[BBI] = V;
1781 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001782 } else {
1783 // Insert the new instruction into its new home.
1784 EdgeBB->getInstList().insert(InsertPt, N);
1785 if (!BBI->use_empty())
1786 TranslateMap[BBI] = N;
1787 }
1788 }
1789
1790 // Loop over all of the edges from PredBB to BB, changing them to branch
1791 // to EdgeBB instead.
1792 TerminatorInst *PredBBTI = PredBB->getTerminator();
1793 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1794 if (PredBBTI->getSuccessor(i) == BB) {
1795 BB->removePredecessor(PredBB);
1796 PredBBTI->setSuccessor(i, EdgeBB);
1797 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001798
Chris Lattner4088e2b2010-12-13 01:47:07 +00001799 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001800 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001801 }
Chris Lattner748f9032005-09-19 23:49:37 +00001802
1803 return false;
1804}
1805
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001806/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1807/// PHI node, see if we can eliminate it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001808static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001809 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1810 // statement", which has a very simple dominance structure. Basically, we
1811 // are trying to find the condition that is being branched on, which
1812 // subsequently causes this merge to happen. We really want control
1813 // dependence information for this check, but simplifycfg can't keep it up
1814 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001815 BasicBlock *BB = PN->getParent();
1816 BasicBlock *IfTrue, *IfFalse;
1817 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001818 if (!IfCond ||
1819 // Don't bother if the branch will be constant folded trivially.
1820 isa<ConstantInt>(IfCond))
1821 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001822
Chris Lattner95adf8f12006-11-18 19:19:36 +00001823 // Okay, we found that we can merge this two-entry phi node into a select.
1824 // Doing so would require us to fold *all* two entry phi nodes in this block.
1825 // At some point this becomes non-profitable (particularly if the target
1826 // doesn't support cmov's). Only do this transformation if there are two or
1827 // fewer PHI nodes in this block.
1828 unsigned NumPhis = 0;
1829 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1830 if (NumPhis > 2)
1831 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001832
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001833 // Loop over the PHI's seeing if we can promote them all to select
1834 // instructions. While we are at it, keep track of the instructions
1835 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001836 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001837 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1838 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001839
Chris Lattner7499b452010-12-14 08:46:09 +00001840 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1841 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001842 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001843 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001844 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001845 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001846 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001847
Peter Collingbournee3511e12011-04-29 18:47:31 +00001848 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001849 MaxCostVal0, DL) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001850 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001851 MaxCostVal1, DL))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001852 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001853 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001854
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001855 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001856 // we ran out of PHIs then we simplified them all.
1857 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001858 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001859
Chris Lattner7499b452010-12-14 08:46:09 +00001860 // Don't fold i1 branches on PHIs which contain binary operators. These can
1861 // often be turned into switches and other things.
1862 if (PN->getType()->isIntegerTy(1) &&
1863 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1864 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1865 isa<BinaryOperator>(IfCond)))
1866 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001867
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001868 // If we all PHI nodes are promotable, check to make sure that all
1869 // instructions in the predecessor blocks can be promoted as well. If
1870 // not, we won't be able to get rid of the control flow, so it's not
1871 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001872 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001873 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1874 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1875 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001876 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001877 } else {
1878 DomBlock = *pred_begin(IfBlock1);
1879 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001880 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001881 // This is not an aggressive instruction that we can promote.
1882 // Because of this, we won't be able to get rid of the control
1883 // flow, so the xform is not worth it.
1884 return false;
1885 }
1886 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001887
Chris Lattner9ac168d2010-12-14 07:41:39 +00001888 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001889 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001890 } else {
1891 DomBlock = *pred_begin(IfBlock2);
1892 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001893 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001894 // This is not an aggressive instruction that we can promote.
1895 // Because of this, we won't be able to get rid of the control
1896 // flow, so the xform is not worth it.
1897 return false;
1898 }
1899 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001900
Chris Lattner9fd838d2010-12-14 07:23:10 +00001901 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001902 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001903
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001904 // If we can still promote the PHI nodes after this gauntlet of tests,
1905 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001906 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001907 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001908
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001909 // Move all 'aggressive' instructions, which are defined in the
1910 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001911 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001912 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001913 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001914 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001915 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001916 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001917 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001918 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001919
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001920 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1921 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001922 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1923 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001924
1925 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001926 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001927 PN->replaceAllUsesWith(NV);
1928 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001929 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001930 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001931
Chris Lattner335f0e42010-12-14 08:01:53 +00001932 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1933 // has been flattened. Change DomBlock to jump directly to our new block to
1934 // avoid other simplifycfg's kicking in on the diamond.
1935 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001936 Builder.SetInsertPoint(OldTI);
1937 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001938 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001939 return true;
1940}
Chris Lattner748f9032005-09-19 23:49:37 +00001941
Chris Lattner86bbf332008-04-24 00:01:19 +00001942/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1943/// to two returning blocks, try to merge them together into one return,
1944/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001945static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001946 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001947 assert(BI->isConditional() && "Must be a conditional branch");
1948 BasicBlock *TrueSucc = BI->getSuccessor(0);
1949 BasicBlock *FalseSucc = BI->getSuccessor(1);
1950 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1951 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001952
Chris Lattner86bbf332008-04-24 00:01:19 +00001953 // Check to ensure both blocks are empty (just a return) or optionally empty
1954 // with PHI nodes. If there are other instructions, merging would cause extra
1955 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001956 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001957 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001958 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001959 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001960
Devang Pateldd14e0f2011-05-18 21:33:11 +00001961 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001962 // Okay, we found a branch that is going to two return nodes. If
1963 // there is no return value for this function, just change the
1964 // branch into a return.
1965 if (FalseRet->getNumOperands() == 0) {
1966 TrueSucc->removePredecessor(BI->getParent());
1967 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001968 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001969 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001970 return true;
1971 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001972
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001973 // Otherwise, figure out what the true and false return values are
1974 // so we can insert a new select instruction.
1975 Value *TrueValue = TrueRet->getReturnValue();
1976 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001977
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001978 // Unwrap any PHI nodes in the return blocks.
1979 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1980 if (TVPN->getParent() == TrueSucc)
1981 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1982 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1983 if (FVPN->getParent() == FalseSucc)
1984 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001985
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001986 // In order for this transformation to be safe, we must be able to
1987 // unconditionally execute both operands to the return. This is
1988 // normally the case, but we could have a potentially-trapping
1989 // constant expression that prevents this transformation from being
1990 // safe.
1991 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1992 if (TCV->canTrap())
1993 return false;
1994 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1995 if (FCV->canTrap())
1996 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001997
Chris Lattner86bbf332008-04-24 00:01:19 +00001998 // Okay, we collected all the mapped values and checked them for sanity, and
1999 // defined to really do this transformation. First, update the CFG.
2000 TrueSucc->removePredecessor(BI->getParent());
2001 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002002
Chris Lattner86bbf332008-04-24 00:01:19 +00002003 // Insert select instructions where needed.
2004 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002005 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002006 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002007 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2008 } else if (isa<UndefValue>(TrueValue)) {
2009 TrueValue = FalseValue;
2010 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00002011 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2012 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002013 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002014 }
2015
Andrew Trickf3cf1932012-08-29 21:46:36 +00002016 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002017 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2018
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002019 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002020
David Greene725c7c32010-01-05 01:26:52 +00002021 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002022 << "\n " << *BI << "NewRet = " << *RI
2023 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002024
Eli Friedmancb61afb2008-12-16 20:54:32 +00002025 EraseTerminatorInstAndDCECond(BI);
2026
Chris Lattner86bbf332008-04-24 00:01:19 +00002027 return true;
2028}
2029
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002030/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2031/// probabilities of the branch taking each edge. Fills in the two APInt
2032/// parameters and return true, or returns false if no or invalid metadata was
2033/// found.
2034static bool ExtractBranchMetadata(BranchInst *BI,
Manman Renbfb9d432012-09-15 00:39:57 +00002035 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002036 assert(BI->isConditional() &&
2037 "Looking for probabilities on unconditional branch?");
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002038 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky398255e2011-12-27 18:27:22 +00002039 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002040 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
2041 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky398255e2011-12-27 18:27:22 +00002042 if (!CITrue || !CIFalse) return false;
Manman Renbfb9d432012-09-15 00:39:57 +00002043 ProbTrue = CITrue->getValue().getZExtValue();
2044 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002045 return true;
2046}
2047
Manman Rend33f4ef2012-06-13 05:43:29 +00002048/// checkCSEInPredecessor - Return true if the given instruction is available
2049/// in its predecessor block. If yes, the instruction will be removed.
2050///
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002051static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002052 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2053 return false;
2054 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2055 Instruction *PBI = &*I;
2056 // Check whether Inst and PBI generate the same value.
2057 if (Inst->isIdenticalTo(PBI)) {
2058 Inst->replaceAllUsesWith(PBI);
2059 Inst->eraseFromParent();
2060 return true;
2061 }
2062 }
2063 return false;
2064}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002065
Chris Lattner7d4cdae2011-04-11 23:24:57 +00002066/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2067/// predecessor branches to us and one of our successors, fold the block into
2068/// the predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00002069bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2070 unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002071 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002072
Craig Topperf40110f2014-04-25 05:29:35 +00002073 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002074 if (BI->isConditional())
2075 Cond = dyn_cast<Instruction>(BI->getCondition());
2076 else {
2077 // For unconditional branch, check for a simple CFG pattern, where
2078 // BB has a single predecessor and BB's successor is also its predecessor's
2079 // successor. If such pattern exisits, check for CSE between BB and its
2080 // predecessor.
2081 if (BasicBlock *PB = BB->getSinglePredecessor())
2082 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2083 if (PBI->isConditional() &&
2084 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2085 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2086 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2087 I != E; ) {
2088 Instruction *Curr = I++;
2089 if (isa<CmpInst>(Curr)) {
2090 Cond = Curr;
2091 break;
2092 }
2093 // Quit if we can't remove this instruction.
2094 if (!checkCSEInPredecessor(Curr, PB))
2095 return false;
2096 }
2097 }
2098
Craig Topperf40110f2014-04-25 05:29:35 +00002099 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002100 return false;
2101 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002102
Craig Topperf40110f2014-04-25 05:29:35 +00002103 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2104 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002105 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002106
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002107 // Make sure the instruction after the condition is the cond branch.
2108 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002109
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002110 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002111 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002112
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002113 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002114 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002115
Jingyue Wufc029672014-09-30 22:23:38 +00002116 // Only allow this transformation if computing the condition doesn't involve
2117 // too many instructions and these involved instructions can be executed
2118 // unconditionally. We denote all involved instructions except the condition
2119 // as "bonus instructions", and only allow this transformation when the
2120 // number of the bonus instructions does not exceed a certain threshold.
2121 unsigned NumBonusInsts = 0;
2122 for (auto I = BB->begin(); Cond != I; ++I) {
2123 // Ignore dbg intrinsics.
2124 if (isa<DbgInfoIntrinsic>(I))
2125 continue;
2126 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2127 return false;
2128 // I has only one use and can be executed unconditionally.
2129 Instruction *User = dyn_cast<Instruction>(I->user_back());
2130 if (User == nullptr || User->getParent() != BB)
2131 return false;
2132 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2133 // to use any other instruction, User must be an instruction between next(I)
2134 // and Cond.
2135 ++NumBonusInsts;
2136 // Early exits once we reach the limit.
2137 if (NumBonusInsts > BonusInstThreshold)
2138 return false;
2139 }
2140
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002141 // Cond is known to be a compare or binary operator. Check to make sure that
2142 // neither operand is a potentially-trapping constant expression.
2143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2144 if (CE->canTrap())
2145 return false;
2146 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2147 if (CE->canTrap())
2148 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002149
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002150 // Finally, don't infinitely unroll conditional loops.
2151 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002152 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002153 if (TrueDest == BB || FalseDest == BB)
2154 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002155
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002156 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2157 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002158 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002159
Chris Lattner80b03a12008-07-13 22:23:11 +00002160 // Check that we have two conditional branches. If there is a PHI node in
2161 // the common successor, verify that the same value flows in from both
2162 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002163 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002164 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002165 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002166 !SafeToMergeTerminators(BI, PBI)) ||
2167 (!BI->isConditional() &&
2168 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002169 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002170
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002171 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002172 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002173 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002174
Manman Rend33f4ef2012-06-13 05:43:29 +00002175 if (BI->isConditional()) {
2176 if (PBI->getSuccessor(0) == TrueDest)
2177 Opc = Instruction::Or;
2178 else if (PBI->getSuccessor(1) == FalseDest)
2179 Opc = Instruction::And;
2180 else if (PBI->getSuccessor(0) == FalseDest)
2181 Opc = Instruction::And, InvertPredCond = true;
2182 else if (PBI->getSuccessor(1) == TrueDest)
2183 Opc = Instruction::Or, InvertPredCond = true;
2184 else
2185 continue;
2186 } else {
2187 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2188 continue;
2189 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002190
David Greene725c7c32010-01-05 01:26:52 +00002191 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002192 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002193
Chris Lattner55eaae12008-07-13 21:20:19 +00002194 // If we need to invert the condition in the pred block to match, do so now.
2195 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002196 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002197
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002198 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2199 CmpInst *CI = cast<CmpInst>(NewCond);
2200 CI->setPredicate(CI->getInversePredicate());
2201 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002202 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002203 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002204 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002205
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002206 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002207 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002208 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002209
Jingyue Wufc029672014-09-30 22:23:38 +00002210 // If we have bonus instructions, clone them into the predecessor block.
2211 // Note that there may be mutliple predecessor blocks, so we cannot move
2212 // bonus instructions to a predecessor block.
2213 ValueToValueMapTy VMap; // maps original values to cloned values
2214 // We already make sure Cond is the last instruction before BI. Therefore,
2215 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2216 // instructions.
2217 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2218 if (isa<DbgInfoIntrinsic>(BonusInst))
2219 continue;
2220 Instruction *NewBonusInst = BonusInst->clone();
2221 RemapInstruction(NewBonusInst, VMap,
2222 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2223 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002224
2225 // If we moved a load, we cannot any longer claim any knowledge about
2226 // its potential value. The previous information might have been valid
2227 // only given the branch precondition.
2228 // For an analogous reason, we must also drop all the metadata whose
2229 // semantics we don't understand.
Jingyue Wufc029672014-09-30 22:23:38 +00002230 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
Rafael Espindolaab73c492014-01-28 16:56:46 +00002231
Jingyue Wufc029672014-09-30 22:23:38 +00002232 PredBlock->getInstList().insert(PBI, NewBonusInst);
2233 NewBonusInst->takeName(BonusInst);
2234 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002235 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002236
Chris Lattner55eaae12008-07-13 21:20:19 +00002237 // Clone Cond into the predecessor basic block, and or/and the
2238 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002239 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002240 RemapInstruction(New, VMap,
2241 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002242 PredBlock->getInstList().insert(PBI, New);
2243 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002244 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002245
Manman Rend33f4ef2012-06-13 05:43:29 +00002246 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002247 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002248 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002249 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002250 PBI->setCondition(NewCond);
2251
Manman Renbfb9d432012-09-15 00:39:57 +00002252 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2253 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2254 PredFalseWeight);
2255 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2256 SuccFalseWeight);
2257 SmallVector<uint64_t, 8> NewWeights;
2258
Manman Rend33f4ef2012-06-13 05:43:29 +00002259 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002260 if (PredHasWeights && SuccHasWeights) {
2261 // PBI: br i1 %x, BB, FalseDest
2262 // BI: br i1 %y, TrueDest, FalseDest
2263 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2264 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2265 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2266 // TrueWeight for PBI * FalseWeight for BI.
2267 // We assume that total weights of a BranchInst can fit into 32 bits.
2268 // Therefore, we will not have overflow using 64-bit arithmetic.
2269 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2270 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2271 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002272 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2273 PBI->setSuccessor(0, TrueDest);
2274 }
2275 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002276 if (PredHasWeights && SuccHasWeights) {
2277 // PBI: br i1 %x, TrueDest, BB
2278 // BI: br i1 %y, TrueDest, FalseDest
2279 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2280 // FalseWeight for PBI * TrueWeight for BI.
2281 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2282 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2283 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2284 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2285 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002286 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2287 PBI->setSuccessor(1, FalseDest);
2288 }
Manman Renbfb9d432012-09-15 00:39:57 +00002289 if (NewWeights.size() == 2) {
2290 // Halve the weights if any of them cannot fit in an uint32_t
2291 FitWeights(NewWeights);
2292
2293 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2294 PBI->setMetadata(LLVMContext::MD_prof,
2295 MDBuilder(BI->getContext()).
2296 createBranchWeights(MDWeights));
2297 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002298 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002299 } else {
2300 // Update PHI nodes in the common successors.
2301 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002302 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002303 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2304 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002305 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002306 if (PBI->getSuccessor(0) == TrueDest) {
2307 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2308 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2309 // is false: !PBI_Cond and BI_Value
2310 Instruction *NotCond =
2311 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2312 "not.cond"));
2313 MergedCond =
2314 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2315 NotCond, New,
2316 "and.cond"));
2317 if (PBI_C->isOne())
2318 MergedCond =
2319 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2320 PBI->getCondition(), MergedCond,
2321 "or.cond"));
2322 } else {
2323 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2324 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2325 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002326 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002327 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2328 PBI->getCondition(), New,
2329 "and.cond"));
2330 if (PBI_C->isOne()) {
2331 Instruction *NotCond =
2332 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2333 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002334 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002335 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2336 NotCond, MergedCond,
2337 "or.cond"));
2338 }
2339 }
2340 // Update PHI Node.
2341 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2342 MergedCond);
2343 }
2344 // Change PBI from Conditional to Unconditional.
2345 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2346 EraseTerminatorInstAndDCECond(PBI);
2347 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002348 }
Devang Pateld715ec82011-04-06 22:37:20 +00002349
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002350 // TODO: If BB is reachable from all paths through PredBlock, then we
2351 // could replace PBI's branch probabilities with BI's.
2352
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002353 // Copy any debug value intrinsics into the end of PredBlock.
2354 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2355 if (isa<DbgInfoIntrinsic>(*I))
2356 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002357
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002358 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002359 }
2360 return false;
2361}
2362
Chris Lattner9aada1d2008-07-13 21:53:26 +00002363/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2364/// predecessor of another block, this function tries to simplify it. We know
2365/// that PBI and BI are both conditional branches, and BI is in one of the
2366/// successor blocks of PBI - PBI branches to BI.
2367static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2368 assert(PBI->isConditional() && BI->isConditional());
2369 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002370
Chris Lattner9aada1d2008-07-13 21:53:26 +00002371 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002372 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002373 // this conditional branch redundant.
2374 if (PBI->getCondition() == BI->getCondition() &&
2375 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2376 // Okay, the outcome of this conditional branch is statically
2377 // knowable. If this block had a single pred, handle specially.
2378 if (BB->getSinglePredecessor()) {
2379 // Turn this into a branch on constant.
2380 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002381 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002382 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002383 return true; // Nuke the branch on constant.
2384 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002385
Chris Lattner9aada1d2008-07-13 21:53:26 +00002386 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2387 // in the constant and simplify the block result. Subsequent passes of
2388 // simplifycfg will thread the block.
2389 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002390 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002391 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002392 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002393 BI->getCondition()->getName() + ".pr",
2394 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002395 // Okay, we're going to insert the PHI node. Since PBI is not the only
2396 // predecessor, compute the PHI'd conditional value for all of the preds.
2397 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002398 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002399 BasicBlock *P = *PI;
2400 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002401 PBI != BI && PBI->isConditional() &&
2402 PBI->getCondition() == BI->getCondition() &&
2403 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2404 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002405 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002406 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002407 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002408 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002409 }
Gabor Greif8629f122010-07-12 10:59:23 +00002410 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002411
Chris Lattner9aada1d2008-07-13 21:53:26 +00002412 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002413 return true;
2414 }
2415 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002416
Chris Lattner9aada1d2008-07-13 21:53:26 +00002417 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002418 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002419 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002420 BasicBlock::iterator BBI = BB->begin();
2421 // Ignore dbg intrinsics.
2422 while (isa<DbgInfoIntrinsic>(BBI))
2423 ++BBI;
2424 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002425 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002426
Andrew Trickf3cf1932012-08-29 21:46:36 +00002427
Chris Lattnerc59945b2009-01-20 01:15:41 +00002428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2429 if (CE->canTrap())
2430 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002431
Chris Lattner834ab4e2008-07-13 22:04:41 +00002432 int PBIOp, BIOp;
2433 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2434 PBIOp = BIOp = 0;
2435 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2436 PBIOp = 0, BIOp = 1;
2437 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2438 PBIOp = 1, BIOp = 0;
2439 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2440 PBIOp = BIOp = 1;
2441 else
2442 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002443
Chris Lattner834ab4e2008-07-13 22:04:41 +00002444 // Check to make sure that the other destination of this branch
2445 // isn't BB itself. If so, this is an infinite loop that will
2446 // keep getting unwound.
2447 if (PBI->getSuccessor(PBIOp) == BB)
2448 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002449
2450 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002451 // insertion of a large number of select instructions. For targets
2452 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002453
Sanjay Patela932da82014-07-07 21:19:00 +00002454 // Also do not perform this transformation if any phi node in the common
2455 // destination block can trap when reached by BB or PBB (PR17073). In that
2456 // case, it would be unsafe to hoist the operation into a select instruction.
2457
2458 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002459 unsigned NumPhis = 0;
2460 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002461 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002462 if (NumPhis > 2) // Disable this xform.
2463 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002464
Sanjay Patela932da82014-07-07 21:19:00 +00002465 PHINode *PN = cast<PHINode>(II);
2466 Value *BIV = PN->getIncomingValueForBlock(BB);
2467 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2468 if (CE->canTrap())
2469 return false;
2470
2471 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2472 Value *PBIV = PN->getIncomingValue(PBBIdx);
2473 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2474 if (CE->canTrap())
2475 return false;
2476 }
2477
Chris Lattner834ab4e2008-07-13 22:04:41 +00002478 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002479 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002480
David Greene725c7c32010-01-05 01:26:52 +00002481 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002482 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002483
2484
Chris Lattner80b03a12008-07-13 22:23:11 +00002485 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2486 // branch in it, where one edge (OtherDest) goes back to itself but the other
2487 // exits. We don't *know* that the program avoids the infinite loop
2488 // (even though that seems likely). If we do this xform naively, we'll end up
2489 // recursively unpeeling the loop. Since we know that (after the xform is
2490 // done) that the block *is* infinite if reached, we just make it an obviously
2491 // infinite loop with no cond branch.
2492 if (OtherDest == BB) {
2493 // Insert it at the end of the function, because it's either code,
2494 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002495 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2496 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002497 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2498 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002499 }
2500
David Greene725c7c32010-01-05 01:26:52 +00002501 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002502
Chris Lattner834ab4e2008-07-13 22:04:41 +00002503 // BI may have other predecessors. Because of this, we leave
2504 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002505
Chris Lattner834ab4e2008-07-13 22:04:41 +00002506 // Make sure we get to CommonDest on True&True directions.
2507 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002508 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002509 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002510 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2511
Chris Lattner834ab4e2008-07-13 22:04:41 +00002512 Value *BICond = BI->getCondition();
2513 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002514 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2515
Chris Lattner834ab4e2008-07-13 22:04:41 +00002516 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002517 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002518
Chris Lattner834ab4e2008-07-13 22:04:41 +00002519 // Modify PBI to branch on the new condition to the new dests.
2520 PBI->setCondition(Cond);
2521 PBI->setSuccessor(0, CommonDest);
2522 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002523
Manman Ren2d4c10f2012-09-17 21:30:40 +00002524 // Update branch weight for PBI.
2525 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2526 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2527 PredFalseWeight);
2528 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2529 SuccFalseWeight);
2530 if (PredHasWeights && SuccHasWeights) {
2531 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2532 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2533 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2534 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2535 // The weight to CommonDest should be PredCommon * SuccTotal +
2536 // PredOther * SuccCommon.
2537 // The weight to OtherDest should be PredOther * SuccOther.
2538 SmallVector<uint64_t, 2> NewWeights;
2539 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2540 PredOther * SuccCommon);
2541 NewWeights.push_back(PredOther * SuccOther);
2542 // Halve the weights if any of them cannot fit in an uint32_t
2543 FitWeights(NewWeights);
2544
2545 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2546 PBI->setMetadata(LLVMContext::MD_prof,
2547 MDBuilder(BI->getContext()).
2548 createBranchWeights(MDWeights));
2549 }
2550
Chris Lattner834ab4e2008-07-13 22:04:41 +00002551 // OtherDest may have phi nodes. If so, add an entry from PBI's
2552 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002553 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002554
Chris Lattner834ab4e2008-07-13 22:04:41 +00002555 // We know that the CommonDest already had an edge from PBI to
2556 // it. If it has PHIs though, the PHIs may have different
2557 // entries for BB and PBI's BB. If so, insert a select to make
2558 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002559 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002560 for (BasicBlock::iterator II = CommonDest->begin();
2561 (PN = dyn_cast<PHINode>(II)); ++II) {
2562 Value *BIV = PN->getIncomingValueForBlock(BB);
2563 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2564 Value *PBIV = PN->getIncomingValue(PBBIdx);
2565 if (BIV != PBIV) {
2566 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002567 Value *NV = cast<SelectInst>
2568 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002569 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002570 }
2571 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002572
David Greene725c7c32010-01-05 01:26:52 +00002573 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2574 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002575
Chris Lattner834ab4e2008-07-13 22:04:41 +00002576 // This basic block is probably dead. We know it has at least
2577 // one fewer predecessor.
2578 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002579}
2580
Frits van Bommel8e158492011-01-11 12:52:11 +00002581// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2582// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2583// Takes care of updating the successors and removing the old terminator.
2584// Also makes sure not to introduce new successors by assuming that edges to
2585// non-successor TrueBBs and FalseBBs aren't reachable.
2586static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002587 BasicBlock *TrueBB, BasicBlock *FalseBB,
2588 uint32_t TrueWeight,
2589 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002590 // Remove any superfluous successor edges from the CFG.
2591 // First, figure out which successors to preserve.
2592 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2593 // successor.
2594 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002595 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002596
2597 // Then remove the rest.
2598 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2599 BasicBlock *Succ = OldTerm->getSuccessor(I);
2600 // Make sure only to keep exactly one copy of each edge.
2601 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002602 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002603 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002604 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002605 else
2606 Succ->removePredecessor(OldTerm->getParent());
2607 }
2608
Devang Patel2c2ea222011-05-18 18:43:31 +00002609 IRBuilder<> Builder(OldTerm);
2610 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2611
Frits van Bommel8e158492011-01-11 12:52:11 +00002612 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002613 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002614 if (TrueBB == FalseBB)
2615 // We were only looking for one successor, and it was present.
2616 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002617 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002618 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002619 // We found both of the successors we were looking for.
2620 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002621 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2622 if (TrueWeight != FalseWeight)
2623 NewBI->setMetadata(LLVMContext::MD_prof,
2624 MDBuilder(OldTerm->getContext()).
2625 createBranchWeights(TrueWeight, FalseWeight));
2626 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002627 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2628 // Neither of the selected blocks were successors, so this
2629 // terminator must be unreachable.
2630 new UnreachableInst(OldTerm->getContext(), OldTerm);
2631 } else {
2632 // One of the selected values was a successor, but the other wasn't.
2633 // Insert an unconditional branch to the one that was found;
2634 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002635 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002636 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002637 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002638 else
2639 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002640 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002641 }
2642
2643 EraseTerminatorInstAndDCECond(OldTerm);
2644 return true;
2645}
2646
Frits van Bommel8ae07992011-02-28 09:44:07 +00002647// SimplifySwitchOnSelect - Replaces
2648// (switch (select cond, X, Y)) on constant X, Y
2649// with a branch - conditional if X and Y lead to distinct BBs,
2650// unconditional otherwise.
2651static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2652 // Check for constant integer values in the select.
2653 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2654 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2655 if (!TrueVal || !FalseVal)
2656 return false;
2657
2658 // Find the relevant condition and destinations.
2659 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002660 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2661 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002662
Manman Ren774246a2012-09-17 22:28:55 +00002663 // Get weight for TrueBB and FalseBB.
2664 uint32_t TrueWeight = 0, FalseWeight = 0;
2665 SmallVector<uint64_t, 8> Weights;
2666 bool HasWeights = HasBranchWeights(SI);
2667 if (HasWeights) {
2668 GetBranchWeights(SI, Weights);
2669 if (Weights.size() == 1 + SI->getNumCases()) {
2670 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2671 getSuccessorIndex()];
2672 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2673 getSuccessorIndex()];
2674 }
2675 }
2676
Frits van Bommel8ae07992011-02-28 09:44:07 +00002677 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002678 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2679 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002680}
2681
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002682// SimplifyIndirectBrOnSelect - Replaces
2683// (indirectbr (select cond, blockaddress(@fn, BlockA),
2684// blockaddress(@fn, BlockB)))
2685// with
2686// (br cond, BlockA, BlockB).
2687static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2688 // Check that both operands of the select are block addresses.
2689 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2690 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2691 if (!TBA || !FBA)
2692 return false;
2693
2694 // Extract the actual blocks.
2695 BasicBlock *TrueBB = TBA->getBasicBlock();
2696 BasicBlock *FalseBB = FBA->getBasicBlock();
2697
Frits van Bommel8e158492011-01-11 12:52:11 +00002698 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002699 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2700 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002701}
2702
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002703/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2704/// instruction (a seteq/setne with a constant) as the only instruction in a
2705/// block that ends with an uncond branch. We are looking for a very specific
2706/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2707/// this case, we merge the first two "or's of icmp" into a switch, but then the
2708/// default value goes to an uncond block with a seteq in it, we get something
2709/// like:
2710///
2711/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2712/// DEFAULT:
2713/// %tmp = icmp eq i8 %A, 92
2714/// br label %end
2715/// end:
2716/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002717///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002718/// We prefer to split the edge to 'end' so that there is a true/false entry to
2719/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002720static bool TryToSimplifyUncondBranchWithICmpInIt(
2721 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00002722 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002723 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002724
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002725 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2726 // complex.
2727 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2728
2729 Value *V = ICI->getOperand(0);
2730 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002731
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002732 // The pattern we're looking for is where our only predecessor is a switch on
2733 // 'V' and this block is the default case for the switch. In this case we can
2734 // fold the compared value into the switch to simplify things.
2735 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002736 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002737
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002738 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2739 if (SI->getCondition() != V)
2740 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002741
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002742 // If BB is reachable on a non-default case, then we simply know the value of
2743 // V in this block. Substitute it and constant fold the icmp instruction
2744 // away.
2745 if (SI->getDefaultDest() != BB) {
2746 ConstantInt *VVal = SI->findCaseDest(BB);
2747 assert(VVal && "Should have a unique destination value");
2748 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002749
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002750 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002751 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002752 ICI->eraseFromParent();
2753 }
2754 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002755 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002756 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002757
Chris Lattner62cc76e2010-12-13 03:43:57 +00002758 // Ok, the block is reachable from the default dest. If the constant we're
2759 // comparing exists in one of the other edges, then we can constant fold ICI
2760 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002761 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002762 Value *V;
2763 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2764 V = ConstantInt::getFalse(BB->getContext());
2765 else
2766 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002767
Chris Lattner62cc76e2010-12-13 03:43:57 +00002768 ICI->replaceAllUsesWith(V);
2769 ICI->eraseFromParent();
2770 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002771 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002772 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002773
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002774 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2775 // the block.
2776 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002777 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002778 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002779 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2780 return false;
2781
2782 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2783 // true in the PHI.
2784 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2785 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2786
2787 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2788 std::swap(DefaultCst, NewCst);
2789
2790 // Replace ICI (which is used by the PHI for the default value) with true or
2791 // false depending on if it is EQ or NE.
2792 ICI->replaceAllUsesWith(DefaultCst);
2793 ICI->eraseFromParent();
2794
2795 // Okay, the switch goes to this block on a default value. Add an edge from
2796 // the switch to the merge point on the compared value.
2797 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2798 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002799 SmallVector<uint64_t, 8> Weights;
2800 bool HasWeights = HasBranchWeights(SI);
2801 if (HasWeights) {
2802 GetBranchWeights(SI, Weights);
2803 if (Weights.size() == 1 + SI->getNumCases()) {
2804 // Split weight for default case to case for "Cst".
2805 Weights[0] = (Weights[0]+1) >> 1;
2806 Weights.push_back(Weights[0]);
2807
2808 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2809 SI->setMetadata(LLVMContext::MD_prof,
2810 MDBuilder(SI->getContext()).
2811 createBranchWeights(MDWeights));
2812 }
2813 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002814 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002815
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002816 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002817 Builder.SetInsertPoint(NewBB);
2818 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2819 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002820 PHIUse->addIncoming(NewCst, NewBB);
2821 return true;
2822}
2823
Chris Lattnera69c4432010-12-13 05:03:41 +00002824/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2825/// Check to see if it is branching on an or/and chain of icmp instructions, and
2826/// fold it into a switch instruction if so.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002827static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
Devang Patel7de6c4b2011-05-18 23:18:47 +00002828 IRBuilder<> &Builder) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002829 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002830 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002831
Chris Lattnera69c4432010-12-13 05:03:41 +00002832 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2833 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2834 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002835
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002836 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00002837 ConstantComparesGatherer ConstantCompare(Cond, DL);
2838 // Unpack the result
2839 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2840 Value *CompVal = ConstantCompare.CompValue;
2841 unsigned UsedICmps = ConstantCompare.UsedICmps;
2842 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002843
Chris Lattnera69c4432010-12-13 05:03:41 +00002844 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002845 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002846
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002847 // Avoid turning single icmps into a switch.
2848 if (UsedICmps <= 1)
2849 return false;
2850
Mehdi Aminiffd01002014-11-20 22:40:25 +00002851 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2852
Chris Lattnera69c4432010-12-13 05:03:41 +00002853 // There might be duplicate constants in the list, which the switch
2854 // instruction can't handle, remove them now.
2855 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2856 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002857
Chris Lattnera69c4432010-12-13 05:03:41 +00002858 // If Extra was used, we require at least two switch values to do the
2859 // transformation. A switch with one value is just an cond branch.
2860 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002861
Andrew Trick3051aa12012-08-29 21:46:38 +00002862 // TODO: Preserve branch weight metadata, similarly to how
2863 // FoldValueComparisonIntoPredecessors preserves it.
2864
Chris Lattnera69c4432010-12-13 05:03:41 +00002865 // Figure out which block is which destination.
2866 BasicBlock *DefaultBB = BI->getSuccessor(1);
2867 BasicBlock *EdgeBB = BI->getSuccessor(0);
2868 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002869
Chris Lattnera69c4432010-12-13 05:03:41 +00002870 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002871
Chris Lattnerd7beca32010-12-14 06:17:25 +00002872 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002873 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002874
Chris Lattnera69c4432010-12-13 05:03:41 +00002875 // If there are any extra values that couldn't be folded into the switch
2876 // then we evaluate them with an explicit branch first. Split the block
2877 // right before the condbr to handle it.
2878 if (ExtraCase) {
2879 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2880 // Remove the uncond branch added to the old block.
2881 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002882 Builder.SetInsertPoint(OldTI);
2883
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002884 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002885 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002886 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002887 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002888
Chris Lattnera69c4432010-12-13 05:03:41 +00002889 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002890
Chris Lattnercb570f82010-12-13 05:34:18 +00002891 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2892 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002893 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002894
Chris Lattnerd7beca32010-12-14 06:17:25 +00002895 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2896 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002897 BB = NewBB;
2898 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002899
2900 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002901 // Convert pointer to int before we switch.
2902 if (CompVal->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002903 assert(DL && "Cannot switch on pointer without DataLayout");
Devang Patel7de6c4b2011-05-18 23:18:47 +00002904 CompVal = Builder.CreatePtrToInt(CompVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002905 DL->getIntPtrType(CompVal->getType()),
Devang Patel7de6c4b2011-05-18 23:18:47 +00002906 "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002907 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002908
Chris Lattnera69c4432010-12-13 05:03:41 +00002909 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002910 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002911
Chris Lattnera69c4432010-12-13 05:03:41 +00002912 // Add all of the 'cases' to the switch instruction.
2913 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2914 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002915
Chris Lattnera69c4432010-12-13 05:03:41 +00002916 // We added edges from PI to the EdgeBB. As such, if there were any
2917 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2918 // the number of edges added.
2919 for (BasicBlock::iterator BBI = EdgeBB->begin();
2920 isa<PHINode>(BBI); ++BBI) {
2921 PHINode *PN = cast<PHINode>(BBI);
2922 Value *InVal = PN->getIncomingValueForBlock(BB);
2923 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2924 PN->addIncoming(InVal, BB);
2925 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002926
Chris Lattnera69c4432010-12-13 05:03:41 +00002927 // Erase the old branch instruction.
2928 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002929
Chris Lattnerd7beca32010-12-14 06:17:25 +00002930 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002931 return true;
2932}
2933
Duncan Sands29192d02011-09-05 12:57:57 +00002934bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2935 // If this is a trivial landing pad that just continues unwinding the caught
2936 // exception then zap the landing pad, turning its invokes into calls.
2937 BasicBlock *BB = RI->getParent();
2938 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2939 if (RI->getValue() != LPInst)
2940 // Not a landing pad, or the resume is not unwinding the exception that
2941 // caused control to branch here.
2942 return false;
2943
2944 // Check that there are no other instructions except for debug intrinsics.
2945 BasicBlock::iterator I = LPInst, E = RI;
2946 while (++I != E)
2947 if (!isa<DbgInfoIntrinsic>(I))
2948 return false;
2949
2950 // Turn all invokes that unwind here into calls and delete the basic block.
Bill Wendling9534d882013-03-11 20:53:00 +00002951 bool InvokeRequiresTableEntry = false;
2952 bool Changed = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002953 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2954 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Bill Wendling9534d882013-03-11 20:53:00 +00002955
2956 if (II->hasFnAttr(Attribute::UWTable)) {
2957 // Don't remove an `invoke' instruction if the ABI requires an entry into
2958 // the table.
2959 InvokeRequiresTableEntry = true;
2960 continue;
2961 }
2962
Duncan Sands29192d02011-09-05 12:57:57 +00002963 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
Bill Wendling9534d882013-03-11 20:53:00 +00002964
Duncan Sands29192d02011-09-05 12:57:57 +00002965 // Insert a call instruction before the invoke.
2966 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2967 Call->takeName(II);
2968 Call->setCallingConv(II->getCallingConv());
2969 Call->setAttributes(II->getAttributes());
2970 Call->setDebugLoc(II->getDebugLoc());
2971
2972 // Anything that used the value produced by the invoke instruction now uses
2973 // the value produced by the call instruction. Note that we do this even
2974 // for void functions and calls with no uses so that the callgraph edge is
2975 // updated.
2976 II->replaceAllUsesWith(Call);
2977 BB->removePredecessor(II->getParent());
2978
2979 // Insert a branch to the normal destination right before the invoke.
2980 BranchInst::Create(II->getNormalDest(), II);
2981
2982 // Finally, delete the invoke instruction!
2983 II->eraseFromParent();
Bill Wendling9534d882013-03-11 20:53:00 +00002984 Changed = true;
Duncan Sands29192d02011-09-05 12:57:57 +00002985 }
2986
Bill Wendling9534d882013-03-11 20:53:00 +00002987 if (!InvokeRequiresTableEntry)
2988 // The landingpad is now unreachable. Zap it.
2989 BB->eraseFromParent();
2990
2991 return Changed;
Duncan Sands29192d02011-09-05 12:57:57 +00002992}
2993
Devang Pateldd14e0f2011-05-18 21:33:11 +00002994bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002995 BasicBlock *BB = RI->getParent();
2996 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002997
Chris Lattner25c3af32010-12-13 06:25:44 +00002998 // Find predecessors that end with branches.
2999 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3000 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003001 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3002 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003003 TerminatorInst *PTI = P->getTerminator();
3004 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3005 if (BI->isUnconditional())
3006 UncondBranchPreds.push_back(P);
3007 else
3008 CondBranchPreds.push_back(BI);
3009 }
3010 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003011
Chris Lattner25c3af32010-12-13 06:25:44 +00003012 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003013 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003014 while (!UncondBranchPreds.empty()) {
3015 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3016 DEBUG(dbgs() << "FOLDING: " << *BB
3017 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003018 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003019 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003020
Chris Lattner25c3af32010-12-13 06:25:44 +00003021 // If we eliminated all predecessors of the block, delete the block now.
3022 if (pred_begin(BB) == pred_end(BB))
3023 // We know there are no successors, so just nuke the block.
3024 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003025
Chris Lattner25c3af32010-12-13 06:25:44 +00003026 return true;
3027 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003028
Chris Lattner25c3af32010-12-13 06:25:44 +00003029 // Check out all of the conditional branches going to this return
3030 // instruction. If any of them just select between returns, change the
3031 // branch itself into a select/return pair.
3032 while (!CondBranchPreds.empty()) {
3033 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003034
Chris Lattner25c3af32010-12-13 06:25:44 +00003035 // Check to see if the non-BB successor is also a return block.
3036 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3037 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003038 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003039 return true;
3040 }
3041 return false;
3042}
3043
Chris Lattner25c3af32010-12-13 06:25:44 +00003044bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3045 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003046
Chris Lattner25c3af32010-12-13 06:25:44 +00003047 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003048
Chris Lattner25c3af32010-12-13 06:25:44 +00003049 // If there are any instructions immediately before the unreachable that can
3050 // be removed, do so.
3051 while (UI != BB->begin()) {
3052 BasicBlock::iterator BBI = UI;
3053 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003054 // Do not delete instructions that can have side effects which might cause
3055 // the unreachable to not be reachable; specifically, calls and volatile
3056 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003057 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003058
3059 if (BBI->mayHaveSideEffects()) {
3060 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3061 if (SI->isVolatile())
3062 break;
3063 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3064 if (LI->isVolatile())
3065 break;
3066 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3067 if (RMWI->isVolatile())
3068 break;
3069 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3070 if (CXI->isVolatile())
3071 break;
3072 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3073 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003074 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003075 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003076 // Note that deleting LandingPad's here is in fact okay, although it
3077 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3078 // all the predecessors of this block will be the unwind edges of Invokes,
3079 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003080 }
3081
Eli Friedmanaac35b32011-03-09 00:48:33 +00003082 // Delete this instruction (any uses are guaranteed to be dead)
3083 if (!BBI->use_empty())
3084 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003085 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003086 Changed = true;
3087 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003088
Chris Lattner25c3af32010-12-13 06:25:44 +00003089 // If the unreachable instruction is the first in the block, take a gander
3090 // at all of the predecessors of this instruction, and simplify them.
3091 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003092
Chris Lattner25c3af32010-12-13 06:25:44 +00003093 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3094 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3095 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003096 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003097 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3098 if (BI->isUnconditional()) {
3099 if (BI->getSuccessor(0) == BB) {
3100 new UnreachableInst(TI->getContext(), TI);
3101 TI->eraseFromParent();
3102 Changed = true;
3103 }
3104 } else {
3105 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003106 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003107 EraseTerminatorInstAndDCECond(BI);
3108 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003109 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003110 EraseTerminatorInstAndDCECond(BI);
3111 Changed = true;
3112 }
3113 }
3114 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003115 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003116 i != e; ++i)
3117 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003118 BB->removePredecessor(SI->getParent());
3119 SI->removeCase(i);
3120 --i; --e;
3121 Changed = true;
3122 }
3123 // If the default value is unreachable, figure out the most popular
3124 // destination and make it the default.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003125 if (SI->getDefaultDest() == BB) {
Eli Friedmanc4414c62011-03-15 02:23:35 +00003126 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003127 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003128 i != e; ++i) {
Nick Lewyckye87d54c2011-12-26 20:37:40 +00003129 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003130 Popularity[i.getCaseSuccessor()];
Eli Friedmanc4414c62011-03-15 02:23:35 +00003131 if (entry.first == 0) {
3132 entry.first = 1;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003133 entry.second = i.getCaseIndex();
Eli Friedmanc4414c62011-03-15 02:23:35 +00003134 } else {
3135 entry.first++;
3136 }
3137 }
3138
Chris Lattner25c3af32010-12-13 06:25:44 +00003139 // Find the most popular block.
3140 unsigned MaxPop = 0;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003141 unsigned MaxIndex = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003142 BasicBlock *MaxBlock = nullptr;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003143 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner25c3af32010-12-13 06:25:44 +00003144 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00003145 if (I->second.first > MaxPop ||
Eli Friedmanc4414c62011-03-15 02:23:35 +00003146 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3147 MaxPop = I->second.first;
3148 MaxIndex = I->second.second;
Chris Lattner25c3af32010-12-13 06:25:44 +00003149 MaxBlock = I->first;
3150 }
3151 }
3152 if (MaxBlock) {
3153 // Make this the new default, allowing us to delete any explicit
3154 // edges to it.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003155 SI->setDefaultDest(MaxBlock);
Chris Lattner25c3af32010-12-13 06:25:44 +00003156 Changed = true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003157
Chris Lattner25c3af32010-12-13 06:25:44 +00003158 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3159 // it.
3160 if (isa<PHINode>(MaxBlock->begin()))
3161 for (unsigned i = 0; i != MaxPop-1; ++i)
3162 MaxBlock->removePredecessor(SI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003163
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003164 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003165 i != e; ++i)
3166 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003167 SI->removeCase(i);
3168 --i; --e;
3169 }
3170 }
3171 }
3172 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3173 if (II->getUnwindDest() == BB) {
3174 // Convert the invoke to a call instruction. This would be a good
3175 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003176 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003177 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003178
Chris Lattner25c3af32010-12-13 06:25:44 +00003179 // Insert the call now...
3180 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003181 Builder.SetInsertPoint(BI);
3182 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003183 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003184 CI->setCallingConv(II->getCallingConv());
3185 CI->setAttributes(II->getAttributes());
3186 // If the invoke produced a value, the call does now instead.
3187 II->replaceAllUsesWith(CI);
3188 delete II;
3189 Changed = true;
3190 }
3191 }
3192 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003193
Chris Lattner25c3af32010-12-13 06:25:44 +00003194 // If this block is now dead, remove it.
3195 if (pred_begin(BB) == pred_end(BB) &&
3196 BB != &BB->getParent()->getEntryBlock()) {
3197 // We know there are no successors, so just nuke the block.
3198 BB->eraseFromParent();
3199 return true;
3200 }
3201
3202 return Changed;
3203}
3204
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003205/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3206/// integer range comparison into a sub, an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003207static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003208 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003209
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003210 // Make sure all cases point to the same destination and gather the values.
3211 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003212 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003213 Cases.push_back(I.getCaseValue());
3214 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003215 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003216 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003217 return false;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003218 Cases.push_back(I.getCaseValue());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003219 }
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003220 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003221
3222 // Sort the case values, then check if they form a range we can transform.
3223 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3224 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3225 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3226 return false;
3227 }
3228
3229 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003230 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003231
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003232 Value *Sub = SI->getCondition();
3233 if (!Offset->isNullValue())
Devang Patel3015a542011-05-19 00:13:33 +00003234 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003235 Value *Cmp;
3236 // If NumCases overflowed, then all possible values jump to the successor.
3237 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3238 Cmp = ConstantInt::getTrue(SI->getContext());
3239 else
3240 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren56575552012-09-18 00:47:33 +00003241 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003242 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003243
Manman Ren56575552012-09-18 00:47:33 +00003244 // Update weight for the newly-created conditional branch.
3245 SmallVector<uint64_t, 8> Weights;
3246 bool HasWeights = HasBranchWeights(SI);
3247 if (HasWeights) {
3248 GetBranchWeights(SI, Weights);
3249 if (Weights.size() == 1 + SI->getNumCases()) {
3250 // Combine all weights for the cases to be the true weight of NewBI.
3251 // We assume that the sum of all weights for a Terminator can fit into 32
3252 // bits.
3253 uint32_t NewTrueWeight = 0;
3254 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3255 NewTrueWeight += (uint32_t)Weights[I];
3256 NewBI->setMetadata(LLVMContext::MD_prof,
3257 MDBuilder(SI->getContext()).
3258 createBranchWeights(NewTrueWeight,
3259 (uint32_t)Weights[0]));
3260 }
3261 }
3262
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003263 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003264 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003265 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003266 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003267 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3268 }
3269 SI->eraseFromParent();
3270
3271 return true;
3272}
Chris Lattner25c3af32010-12-13 06:25:44 +00003273
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003274/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3275/// and use it to remove dead cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003276static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3277 AssumptionTracker *AT) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003278 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003279 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003280 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003281 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003282
3283 // Gather dead cases.
3284 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003285 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003286 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3287 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3288 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003289 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003290 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003291 }
3292 }
3293
Manman Ren56575552012-09-18 00:47:33 +00003294 SmallVector<uint64_t, 8> Weights;
3295 bool HasWeight = HasBranchWeights(SI);
3296 if (HasWeight) {
3297 GetBranchWeights(SI, Weights);
3298 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3299 }
3300
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003301 // Remove dead cases from the switch.
3302 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003303 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003304 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003305 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003306 if (HasWeight) {
3307 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3308 Weights.pop_back();
3309 }
3310
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003311 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003312 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003313 SI->removeCase(Case);
3314 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003315 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003316 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3317 SI->setMetadata(LLVMContext::MD_prof,
3318 MDBuilder(SI->getParent()->getContext()).
3319 createBranchWeights(MDWeights));
3320 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003321
3322 return !DeadCases.empty();
3323}
3324
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003325/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3326/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3327/// by an unconditional branch), look at the phi node for BB in the successor
3328/// block and see if the incoming value is equal to CaseValue. If so, return
3329/// the phi node, and set PhiIndex to BB's index in the phi node.
3330static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3331 BasicBlock *BB,
3332 int *PhiIndex) {
3333 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003334 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003335 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003336 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003337
3338 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3339 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003340 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003341
3342 BasicBlock *Succ = Branch->getSuccessor(0);
3343
3344 BasicBlock::iterator I = Succ->begin();
3345 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3346 int Idx = PHI->getBasicBlockIndex(BB);
3347 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3348
3349 Value *InValue = PHI->getIncomingValue(Idx);
3350 if (InValue != CaseValue) continue;
3351
3352 *PhiIndex = Idx;
3353 return PHI;
3354 }
3355
Craig Topperf40110f2014-04-25 05:29:35 +00003356 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003357}
3358
3359/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3360/// instruction to a phi node dominated by the switch, if that would mean that
3361/// some of the destination blocks of the switch can be folded away.
3362/// Returns true if a change is made.
3363static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3364 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3365 ForwardingNodesMap ForwardingNodes;
3366
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003367 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003368 ConstantInt *CaseValue = I.getCaseValue();
3369 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003370
3371 int PhiIndex;
3372 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3373 &PhiIndex);
3374 if (!PHI) continue;
3375
3376 ForwardingNodes[PHI].push_back(PhiIndex);
3377 }
3378
3379 bool Changed = false;
3380
3381 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3382 E = ForwardingNodes.end(); I != E; ++I) {
3383 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003384 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003385
3386 if (Indexes.size() < 2) continue;
3387
3388 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3389 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3390 Changed = true;
3391 }
3392
3393 return Changed;
3394}
3395
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003396/// ValidLookupTableConstant - Return true if the backend will be able to handle
3397/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003398static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003399 if (C->isThreadDependent())
3400 return false;
3401 if (C->isDLLImportDependent())
3402 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003403
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3405 return CE->isGEPWithNoNotionalOverIndexing();
3406
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003407 return isa<ConstantFP>(C) ||
3408 isa<ConstantInt>(C) ||
3409 isa<ConstantPointerNull>(C) ||
3410 isa<GlobalValue>(C) ||
3411 isa<UndefValue>(C);
3412}
3413
Hans Wennborg09acdb92012-10-31 15:14:39 +00003414/// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003415/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003416static Constant *LookupConstant(Value *V,
3417 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3418 if (Constant *C = dyn_cast<Constant>(V))
3419 return C;
3420 return ConstantPool.lookup(V);
3421}
3422
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003423/// ConstantFold - Try to fold instruction I into a constant. This works for
3424/// simple instructions such as binary operations where both operands are
3425/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003426/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003427static Constant *
3428ConstantFold(Instruction *I,
3429 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3430 const DataLayout *DL) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003431 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003432 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3433 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003434 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003435 if (A->isAllOnesValue())
3436 return LookupConstant(Select->getTrueValue(), ConstantPool);
3437 if (A->isNullValue())
3438 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003439 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003440 }
3441
Benjamin Kramer7c302602013-11-12 12:24:36 +00003442 SmallVector<Constant *, 4> COps;
3443 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3444 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3445 COps.push_back(A);
3446 else
Craig Topperf40110f2014-04-25 05:29:35 +00003447 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003448 }
3449
Benjamin Kramer7c302602013-11-12 12:24:36 +00003450 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3451 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3452 COps[1], DL);
3453
3454 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003455}
3456
3457/// GetCaseResults - Try to determine the resulting constant values in phi nodes
3458/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003459/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003460/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003461static bool
3462GetCaseResults(SwitchInst *SI,
3463 ConstantInt *CaseVal,
3464 BasicBlock *CaseDest,
3465 BasicBlock **CommonDest,
Benjamin Kramer7c302602013-11-12 12:24:36 +00003466 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3467 const DataLayout *DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003468 // The block from which we enter the common destination.
3469 BasicBlock *Pred = SI->getParent();
3470
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003471 // If CaseDest is empty except for some side-effect free instructions through
3472 // which we can constant-propagate the CaseVal, continue to its successor.
3473 SmallDenseMap<Value*, Constant*> ConstantPool;
3474 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3475 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3476 ++I) {
3477 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3478 // If the terminator is a simple branch, continue to the next block.
3479 if (T->getNumSuccessors() != 1)
3480 return false;
3481 Pred = CaseDest;
3482 CaseDest = T->getSuccessor(0);
3483 } else if (isa<DbgInfoIntrinsic>(I)) {
3484 // Skip debug intrinsic.
3485 continue;
Benjamin Kramer7c302602013-11-12 12:24:36 +00003486 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003487 // Instruction is side-effect free and constant.
3488 ConstantPool.insert(std::make_pair(I, C));
3489 } else {
3490 break;
3491 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003492 }
3493
3494 // If we did not have a CommonDest before, use the current one.
3495 if (!*CommonDest)
3496 *CommonDest = CaseDest;
3497 // If the destination isn't the common one, abort.
3498 if (CaseDest != *CommonDest)
3499 return false;
3500
3501 // Get the values for this case from phi nodes in the destination block.
3502 BasicBlock::iterator I = (*CommonDest)->begin();
3503 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3504 int Idx = PHI->getBasicBlockIndex(Pred);
3505 if (Idx == -1)
3506 continue;
3507
Hans Wennborg09acdb92012-10-31 15:14:39 +00003508 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3509 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003510 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003511 return false;
3512
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003513 // Note: If the constant comes from constant-propagating the case value
3514 // through the CaseDest basic block, it will be safe to remove the
3515 // instructions in that block. They cannot be used (except in the phi nodes
3516 // we visit) outside CaseDest, because that block does not dominate its
3517 // successor. If it did, we would not be in this phi node.
3518
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003519 // Be conservative about which kinds of constants we support.
3520 if (!ValidLookupTableConstant(ConstVal))
3521 return false;
3522
3523 Res.push_back(std::make_pair(PHI, ConstVal));
3524 }
3525
Hans Wennborgac114a32014-01-12 00:44:41 +00003526 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003527}
3528
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003529// MapCaseToResult - Helper function used to
3530// add CaseVal to the list of cases that generate Result.
3531static void MapCaseToResult(ConstantInt *CaseVal,
3532 SwitchCaseResultVectorTy &UniqueResults,
3533 Constant *Result) {
3534 for (auto &I : UniqueResults) {
3535 if (I.first == Result) {
3536 I.second.push_back(CaseVal);
3537 return;
3538 }
3539 }
3540 UniqueResults.push_back(std::make_pair(Result,
3541 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3542}
3543
3544// InitializeUniqueCases - Helper function that initializes a map containing
3545// results for the PHI node of the common destination block for a switch
3546// instruction. Returns false if multiple PHI nodes have been found or if
3547// there is not a common destination block for the switch.
3548static bool InitializeUniqueCases(
3549 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3550 BasicBlock *&CommonDest,
3551 SwitchCaseResultVectorTy &UniqueResults,
3552 Constant *&DefaultResult) {
3553 for (auto &I : SI->cases()) {
3554 ConstantInt *CaseVal = I.getCaseValue();
3555
3556 // Resulting value at phi nodes for this case value.
3557 SwitchCaseResultsTy Results;
3558 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3559 DL))
3560 return false;
3561
3562 // Only one value per case is permitted
3563 if (Results.size() > 1)
3564 return false;
3565 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3566
3567 // Check the PHI consistency.
3568 if (!PHI)
3569 PHI = Results[0].first;
3570 else if (PHI != Results[0].first)
3571 return false;
3572 }
3573 // Find the default result value.
3574 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3575 BasicBlock *DefaultDest = SI->getDefaultDest();
3576 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3577 DL);
3578 // If the default value is not found abort unless the default destination
3579 // is unreachable.
3580 DefaultResult =
3581 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3582 if ((!DefaultResult &&
3583 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3584 return false;
3585
3586 return true;
3587}
3588
3589// ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3590// transform a switch with only two cases (or two cases + default)
3591// that produces a result into a value select.
3592// Example:
3593// switch (a) {
3594// case 10: %0 = icmp eq i32 %a, 10
3595// return 10; %1 = select i1 %0, i32 10, i32 4
3596// case 20: ----> %2 = icmp eq i32 %a, 20
3597// return 2; %3 = select i1 %2, i32 2, i32 %1
3598// default:
3599// return 4;
3600// }
3601static Value *
3602ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3603 Constant *DefaultResult, Value *Condition,
3604 IRBuilder<> &Builder) {
3605 assert(ResultVector.size() == 2 &&
3606 "We should have exactly two unique results at this point");
3607 // If we are selecting between only two cases transform into a simple
3608 // select or a two-way select if default is possible.
3609 if (ResultVector[0].second.size() == 1 &&
3610 ResultVector[1].second.size() == 1) {
3611 ConstantInt *const FirstCase = ResultVector[0].second[0];
3612 ConstantInt *const SecondCase = ResultVector[1].second[0];
3613
3614 bool DefaultCanTrigger = DefaultResult;
3615 Value *SelectValue = ResultVector[1].first;
3616 if (DefaultCanTrigger) {
3617 Value *const ValueCompare =
3618 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3619 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3620 DefaultResult, "switch.select");
3621 }
3622 Value *const ValueCompare =
3623 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3624 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3625 "switch.select");
3626 }
3627
3628 return nullptr;
3629}
3630
3631// RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3632// instruction that has been converted into a select, fixing up PHI nodes and
3633// basic blocks.
3634static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3635 Value *SelectValue,
3636 IRBuilder<> &Builder) {
3637 BasicBlock *SelectBB = SI->getParent();
3638 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3639 PHI->removeIncomingValue(SelectBB);
3640 PHI->addIncoming(SelectValue, SelectBB);
3641
3642 Builder.CreateBr(PHI->getParent());
3643
3644 // Remove the switch.
3645 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3646 BasicBlock *Succ = SI->getSuccessor(i);
3647
3648 if (Succ == PHI->getParent())
3649 continue;
3650 Succ->removePredecessor(SelectBB);
3651 }
3652 SI->eraseFromParent();
3653}
3654
3655/// SwitchToSelect - If the switch is only used to initialize one or more
3656/// phi nodes in a common successor block with only two different
3657/// constant values, replace the switch with select.
3658static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3659 const DataLayout *DL, AssumptionTracker *AT) {
3660 Value *const Cond = SI->getCondition();
3661 PHINode *PHI = nullptr;
3662 BasicBlock *CommonDest = nullptr;
3663 Constant *DefaultResult;
3664 SwitchCaseResultVectorTy UniqueResults;
3665 // Collect all the cases that will deliver the same value from the switch.
3666 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3667 DefaultResult))
3668 return false;
3669 // Selects choose between maximum two values.
3670 if (UniqueResults.size() != 2)
3671 return false;
3672 assert(PHI != nullptr && "PHI for value select not found");
3673
3674 Builder.SetInsertPoint(SI);
3675 Value *SelectValue = ConvertTwoCaseSwitch(
3676 UniqueResults,
3677 DefaultResult, Cond, Builder);
3678 if (SelectValue) {
3679 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3680 return true;
3681 }
3682 // The switch couldn't be converted into a select.
3683 return false;
3684}
3685
Hans Wennborg776d7122012-09-26 09:34:53 +00003686namespace {
3687 /// SwitchLookupTable - This class represents a lookup table that can be used
3688 /// to replace a switch.
3689 class SwitchLookupTable {
3690 public:
3691 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3692 /// with the contents of Values, using DefaultValue to fill any holes in the
3693 /// table.
3694 SwitchLookupTable(Module &M,
3695 uint64_t TableSize,
3696 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003697 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003698 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003699 const DataLayout *DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003700
3701 /// BuildLookup - Build instructions with Builder to retrieve the value at
3702 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003703 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003704
Hans Wennborg39583b82012-09-26 09:44:49 +00003705 /// WouldFitInRegister - Return true if a table with TableSize elements of
3706 /// type ElementType would fit in a target-legal register.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003707 static bool WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003708 uint64_t TableSize,
3709 const Type *ElementType);
3710
Hans Wennborg776d7122012-09-26 09:34:53 +00003711 private:
3712 // Depending on the contents of the table, it can be represented in
3713 // different ways.
3714 enum {
3715 // For tables where each element contains the same value, we just have to
3716 // store that single value and return it for each lookup.
3717 SingleValueKind,
3718
Erik Eckstein105374f2014-11-17 09:13:57 +00003719 // For tables where there is a linear relationship between table index
3720 // and values. We calculate the result with a simple multiplication
3721 // and addition instead of a table lookup.
3722 LinearMapKind,
3723
Hans Wennborg39583b82012-09-26 09:44:49 +00003724 // For small tables with integer elements, we can pack them into a bitmap
3725 // that fits into a target-legal register. Values are retrieved by
3726 // shift and mask operations.
3727 BitMapKind,
3728
Hans Wennborg776d7122012-09-26 09:34:53 +00003729 // The table is stored as an array of values. Values are retrieved by load
3730 // instructions from the table.
3731 ArrayKind
3732 } Kind;
3733
3734 // For SingleValueKind, this is the single value.
3735 Constant *SingleValue;
3736
Hans Wennborg39583b82012-09-26 09:44:49 +00003737 // For BitMapKind, this is the bitmap.
3738 ConstantInt *BitMap;
3739 IntegerType *BitMapElementTy;
3740
Erik Eckstein105374f2014-11-17 09:13:57 +00003741 // For LinearMapKind, these are the constants used to derive the value.
3742 ConstantInt *LinearOffset;
3743 ConstantInt *LinearMultiplier;
3744
Hans Wennborg776d7122012-09-26 09:34:53 +00003745 // For ArrayKind, this is the array.
3746 GlobalVariable *Array;
3747 };
3748}
3749
3750SwitchLookupTable::SwitchLookupTable(Module &M,
3751 uint64_t TableSize,
3752 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003753 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003754 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003755 const DataLayout *DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003756 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003757 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003758 assert(Values.size() && "Can't build lookup table without values!");
3759 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003760
3761 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003762 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003763
Hans Wennborgac114a32014-01-12 00:44:41 +00003764 Type *ValueType = Values.begin()->second->getType();
3765
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003766 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003767 SmallVector<Constant*, 64> TableContents(TableSize);
3768 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3769 ConstantInt *CaseVal = Values[I].first;
3770 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003771 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003772
Hans Wennborg776d7122012-09-26 09:34:53 +00003773 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3774 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003775 TableContents[Idx] = CaseRes;
3776
Hans Wennborg776d7122012-09-26 09:34:53 +00003777 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003778 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003779 }
3780
3781 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003782 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003783 assert(DefaultValue &&
3784 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003785 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003786 for (uint64_t I = 0; I < TableSize; ++I) {
3787 if (!TableContents[I])
3788 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003789 }
3790
Hans Wennborg776d7122012-09-26 09:34:53 +00003791 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003792 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003793 }
3794
Hans Wennborg776d7122012-09-26 09:34:53 +00003795 // If each element in the table contains the same value, we only need to store
3796 // that single value.
3797 if (SingleValue) {
3798 Kind = SingleValueKind;
3799 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003800 }
3801
Erik Eckstein105374f2014-11-17 09:13:57 +00003802 // Check if we can derive the value with a linear transformation from the
3803 // table index.
3804 if (isa<IntegerType>(ValueType)) {
3805 bool LinearMappingPossible = true;
3806 APInt PrevVal;
3807 APInt DistToPrev;
3808 assert(TableSize >= 2 && "Should be a SingleValue table.");
3809 // Check if there is the same distance between two consecutive values.
3810 for (uint64_t I = 0; I < TableSize; ++I) {
3811 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3812 if (!ConstVal) {
3813 // This is an undef. We could deal with it, but undefs in lookup tables
3814 // are very seldom. It's probably not worth the additional complexity.
3815 LinearMappingPossible = false;
3816 break;
3817 }
3818 APInt Val = ConstVal->getValue();
3819 if (I != 0) {
3820 APInt Dist = Val - PrevVal;
3821 if (I == 1) {
3822 DistToPrev = Dist;
3823 } else if (Dist != DistToPrev) {
3824 LinearMappingPossible = false;
3825 break;
3826 }
3827 }
3828 PrevVal = Val;
3829 }
3830 if (LinearMappingPossible) {
3831 LinearOffset = cast<ConstantInt>(TableContents[0]);
3832 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3833 Kind = LinearMapKind;
3834 ++NumLinearMaps;
3835 return;
3836 }
3837 }
3838
Hans Wennborg39583b82012-09-26 09:44:49 +00003839 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003840 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003841 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003842 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3843 for (uint64_t I = TableSize; I > 0; --I) {
3844 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003845 // Insert values into the bitmap. Undef values are set to zero.
3846 if (!isa<UndefValue>(TableContents[I - 1])) {
3847 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3848 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3849 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003850 }
3851 BitMap = ConstantInt::get(M.getContext(), TableInt);
3852 BitMapElementTy = IT;
3853 Kind = BitMapKind;
3854 ++NumBitMaps;
3855 return;
3856 }
3857
Hans Wennborg776d7122012-09-26 09:34:53 +00003858 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003859 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003860 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3861
Hans Wennborg776d7122012-09-26 09:34:53 +00003862 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3863 GlobalVariable::PrivateLinkage,
3864 Initializer,
3865 "switch.table");
3866 Array->setUnnamedAddr(true);
3867 Kind = ArrayKind;
3868}
3869
Manman Ren4d189fb2014-07-24 21:13:20 +00003870Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003871 switch (Kind) {
3872 case SingleValueKind:
3873 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00003874 case LinearMapKind: {
3875 // Derive the result value from the input value.
3876 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3877 false, "switch.idx.cast");
3878 if (!LinearMultiplier->isOne())
3879 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3880 if (!LinearOffset->isZero())
3881 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3882 return Result;
3883 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003884 case BitMapKind: {
3885 // Type of the bitmap (e.g. i59).
3886 IntegerType *MapTy = BitMap->getType();
3887
3888 // Cast Index to the same type as the bitmap.
3889 // Note: The Index is <= the number of elements in the table, so
3890 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003891 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003892
3893 // Multiply the shift amount by the element width.
3894 ShiftAmt = Builder.CreateMul(ShiftAmt,
3895 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3896 "switch.shiftamt");
3897
3898 // Shift down.
3899 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3900 "switch.downshift");
3901 // Mask off.
3902 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3903 "switch.masked");
3904 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003905 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003906 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003907 IntegerType *IT = cast<IntegerType>(Index->getType());
3908 uint64_t TableSize = Array->getInitializer()->getType()
3909 ->getArrayNumElements();
3910 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3911 Index = Builder.CreateZExt(Index,
3912 IntegerType::get(IT->getContext(),
3913 IT->getBitWidth() + 1),
3914 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003915
Hans Wennborg776d7122012-09-26 09:34:53 +00003916 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3917 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3918 "switch.gep");
3919 return Builder.CreateLoad(GEP, "switch.load");
3920 }
3921 }
3922 llvm_unreachable("Unknown lookup table kind!");
3923}
3924
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003925bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003926 uint64_t TableSize,
3927 const Type *ElementType) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003928 if (!DL)
Hans Wennborg39583b82012-09-26 09:44:49 +00003929 return false;
3930 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3931 if (!IT)
3932 return false;
3933 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3934 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003935
3936 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3937 if (TableSize >= UINT_MAX/IT->getBitWidth())
3938 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003939 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003940}
3941
Hans Wennborg776d7122012-09-26 09:34:53 +00003942/// ShouldBuildLookupTable - Determine whether a lookup table should be built
Hans Wennborg5cf30be2013-06-04 11:22:30 +00003943/// for this switch, based on the number of cases, size of the table and the
Hans Wennborg776d7122012-09-26 09:34:53 +00003944/// types of the results.
3945static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003946 uint64_t TableSize,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003947 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003948 const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003949 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003950 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3951 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003952
Chandler Carruth77d433d2012-11-30 09:26:25 +00003953 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003954 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00003955 for (const auto &I : ResultTypes) {
3956 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003957
3958 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003959 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003960
3961 // Saturate this flag to false.
3962 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003963 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003964
3965 // If both flags saturate, we're done. NOTE: This *only* works with
3966 // saturating flags, and all flags have to saturate first due to the
3967 // non-deterministic behavior of iterating over a dense map.
3968 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003969 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003970 }
Evan Cheng65df8082012-11-30 02:02:42 +00003971
Chandler Carruth77d433d2012-11-30 09:26:25 +00003972 // If each table would fit in a register, we should build it anyway.
3973 if (AllTablesFitInRegister)
3974 return true;
3975
3976 // Don't build a table that doesn't fit in-register if it has illegal types.
3977 if (HasIllegalType)
3978 return false;
3979
3980 // The table density should be at least 40%. This is the same criterion as for
3981 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3982 // FIXME: Find the best cut-off.
3983 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003984}
3985
Erik Eckstein0d86c762014-11-27 15:13:14 +00003986/// Try to reuse the switch table index compare. Following pattern:
3987/// \code
3988/// if (idx < tablesize)
3989/// r = table[idx]; // table does not contain default_value
3990/// else
3991/// r = default_value;
3992/// if (r != default_value)
3993/// ...
3994/// \endcode
3995/// Is optimized to:
3996/// \code
3997/// cond = idx < tablesize;
3998/// if (cond)
3999/// r = table[idx];
4000/// else
4001/// r = default_value;
4002/// if (cond)
4003/// ...
4004/// \endcode
4005/// Jump threading will then eliminate the second if(cond).
4006static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4007 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4008 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4009
4010 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4011 if (!CmpInst)
4012 return;
4013
4014 // We require that the compare is in the same block as the phi so that jump
4015 // threading can do its work afterwards.
4016 if (CmpInst->getParent() != PhiBlock)
4017 return;
4018
4019 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4020 if (!CmpOp1)
4021 return;
4022
4023 Value *RangeCmp = RangeCheckBranch->getCondition();
4024 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4025 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4026
4027 // Check if the compare with the default value is constant true or false.
4028 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4029 DefaultValue, CmpOp1, true);
4030 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4031 return;
4032
4033 // Check if the compare with the case values is distinct from the default
4034 // compare result.
4035 for (auto ValuePair : Values) {
4036 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4037 ValuePair.second, CmpOp1, true);
4038 if (!CaseConst || CaseConst == DefaultConst)
4039 return;
4040 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4041 "Expect true or false as compare result.");
4042 }
4043
4044 // Check if the branch instruction dominates the phi node. It's a simple
4045 // dominance check, but sufficient for our needs.
4046 // Although this check is invariant in the calling loops, it's better to do it
4047 // at this late stage. Practically we do it at most once for a switch.
4048 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4049 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4050 BasicBlock *Pred = *PI;
4051 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4052 return;
4053 }
4054
4055 if (DefaultConst == FalseConst) {
4056 // The compare yields the same result. We can replace it.
4057 CmpInst->replaceAllUsesWith(RangeCmp);
4058 ++NumTableCmpReuses;
4059 } else {
4060 // The compare yields the same result, just inverted. We can replace it.
4061 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4062 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4063 RangeCheckBranch);
4064 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4065 ++NumTableCmpReuses;
4066 }
4067}
4068
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004069/// SwitchToLookupTable - If the switch is only used to initialize one or more
4070/// phi nodes in a common successor block with different constant values,
4071/// replace the switch with lookup tables.
4072static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00004073 IRBuilder<> &Builder,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004074 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004075 const DataLayout* DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004076 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004077
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004078 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004079 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004080 return false;
4081
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004082 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4083 // split off a dense part and build a lookup table for that.
4084
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004085 // FIXME: This creates arrays of GEPs to constant strings, which means each
4086 // GEP needs a runtime relocation in PIC code. We should just build one big
4087 // string and lookup indices into that.
4088
Hans Wennborg4744ac12014-01-15 05:00:27 +00004089 // Ignore switches with less than three cases. Lookup tables will not make them
4090 // faster, so we don't analyze them.
4091 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004092 return false;
4093
4094 // Figure out the corresponding result for each case value and phi node in the
4095 // common destination, as well as the the min and max case values.
4096 assert(SI->case_begin() != SI->case_end());
4097 SwitchInst::CaseIt CI = SI->case_begin();
4098 ConstantInt *MinCaseVal = CI.getCaseValue();
4099 ConstantInt *MaxCaseVal = CI.getCaseValue();
4100
Craig Topperf40110f2014-04-25 05:29:35 +00004101 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004102 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004103 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4104 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4105 SmallDenseMap<PHINode*, Type*> ResultTypes;
4106 SmallVector<PHINode*, 4> PHIs;
4107
4108 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4109 ConstantInt *CaseVal = CI.getCaseValue();
4110 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4111 MinCaseVal = CaseVal;
4112 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4113 MaxCaseVal = CaseVal;
4114
4115 // Resulting value at phi nodes for this case value.
4116 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4117 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004118 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004119 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004120 return false;
4121
4122 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004123 for (const auto &I : Results) {
4124 PHINode *PHI = I.first;
4125 Constant *Value = I.second;
4126 if (!ResultLists.count(PHI))
4127 PHIs.push_back(PHI);
4128 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004129 }
4130 }
4131
Hans Wennborgac114a32014-01-12 00:44:41 +00004132 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004133 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004134 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4135 }
4136
4137 uint64_t NumResults = ResultLists[PHIs[0]].size();
4138 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4139 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4140 bool TableHasHoles = (NumResults < TableSize);
4141
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004142 // If the table has holes, we need a constant result for the default case
4143 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004144 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004145 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Craig Topperf40110f2014-04-25 05:29:35 +00004146 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004147
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004148 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4149 if (NeedMask) {
4150 // As an extra penalty for the validity test we require more cases.
4151 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4152 return false;
4153 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4154 return false;
4155 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004156
Hans Wennborga6a11a92014-11-18 02:37:11 +00004157 for (const auto &I : DefaultResultsList) {
4158 PHINode *PHI = I.first;
4159 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004160 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004161 }
4162
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004163 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004164 return false;
4165
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004166 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004167 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004168 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4169 "switch.lookup",
4170 CommonDest->getParent(),
4171 CommonDest);
4172
Michael Gottesmanc024f322013-10-20 07:04:37 +00004173 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004174 Builder.SetInsertPoint(SI);
4175 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4176 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004177
4178 // Compute the maximum table size representable by the integer type we are
4179 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004180 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004181 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004182 assert(MaxTableSize >= TableSize &&
4183 "It is impossible for a switch to have more entries than the max "
4184 "representable value of its input integer type's size.");
4185
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004186 // If we have a fully covered lookup table, unconditionally branch to the
4187 // lookup table BB. Otherwise, check if the condition value is within the case
4188 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
4189 // destination.
Erik Eckstein0d86c762014-11-27 15:13:14 +00004190 BranchInst *RangeCheckBranch = nullptr;
4191
Michael Gottesmanc024f322013-10-20 07:04:37 +00004192 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
4193 if (GeneratingCoveredLookupTable) {
4194 Builder.CreateBr(LookupBB);
Manman Ren062f58d2014-08-02 23:41:54 +00004195 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4196 // do not delete PHINodes here.
4197 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4198 true/*DontDeleteUselessPHIs*/);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004199 } else {
4200 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004201 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004202 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004203 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004204
4205 // Populate the BB that does the lookups.
4206 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004207
4208 if (NeedMask) {
4209 // Before doing the lookup we do the hole check.
4210 // The LookupBB is therefore re-purposed to do the hole check
4211 // and we create a new LookupBB.
4212 BasicBlock *MaskBB = LookupBB;
4213 MaskBB->setName("switch.hole_check");
4214 LookupBB = BasicBlock::Create(Mod.getContext(),
4215 "switch.lookup",
4216 CommonDest->getParent(),
4217 CommonDest);
4218
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004219 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4220 // unnecessary illegal types.
4221 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4222 APInt MaskInt(TableSizePowOf2, 0);
4223 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004224 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004225 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4226 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4227 uint64_t Idx = (ResultList[I].first->getValue() -
4228 MinCaseVal->getValue()).getLimitedValue();
4229 MaskInt |= One << Idx;
4230 }
4231 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4232
4233 // Get the TableIndex'th bit of the bitmask.
4234 // If this bit is 0 (meaning hole) jump to the default destination,
4235 // else continue with table lookup.
4236 IntegerType *MapTy = TableMask->getType();
4237 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4238 "switch.maskindex");
4239 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4240 "switch.shifted");
4241 Value *LoBit = Builder.CreateTrunc(Shifted,
4242 Type::getInt1Ty(Mod.getContext()),
4243 "switch.lobit");
4244 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4245
4246 Builder.SetInsertPoint(LookupBB);
4247 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4248 }
4249
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004250 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004251 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4252 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004253 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004254
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004255 // If using a bitmask, use any value to fill the lookup table holes.
4256 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004257 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004258
Manman Ren4d189fb2014-07-24 21:13:20 +00004259 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004260
Hans Wennborgf744fa92012-09-19 14:24:21 +00004261 // If the result is used to return immediately from the function, we want to
4262 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004263 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4264 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004265 Builder.CreateRet(Result);
4266 ReturnedEarly = true;
4267 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004268 }
4269
Erik Eckstein0d86c762014-11-27 15:13:14 +00004270 // Do a small peephole optimization: re-use the switch table compare if
4271 // possible.
4272 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4273 BasicBlock *PhiBlock = PHI->getParent();
4274 // Search for compare instructions which use the phi.
4275 for (auto *User : PHI->users()) {
4276 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4277 }
4278 }
4279
Hans Wennborgf744fa92012-09-19 14:24:21 +00004280 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004281 }
4282
4283 if (!ReturnedEarly)
4284 Builder.CreateBr(CommonDest);
4285
4286 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004287 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004288 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004289
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004290 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004291 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004292 Succ->removePredecessor(SI->getParent());
4293 }
4294 SI->eraseFromParent();
4295
4296 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004297 if (NeedMask)
4298 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004299 return true;
4300}
4301
Devang Patela7ec47d2011-05-18 20:35:38 +00004302bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004303 BasicBlock *BB = SI->getParent();
4304
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004305 if (isValueEqualityComparison(SI)) {
4306 // If we only have one predecessor, and if it is a branch on this value,
4307 // see if that predecessor totally determines the outcome of this switch.
4308 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4309 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004310 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004311
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004312 Value *Cond = SI->getCondition();
4313 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4314 if (SimplifySwitchOnSelect(SI, Select))
Jingyue Wufc029672014-09-30 22:23:38 +00004315 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004316
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004317 // If the block only contains the switch, see if we can fold the block
4318 // away into any preds.
4319 BasicBlock::iterator BBI = BB->begin();
4320 // Ignore dbg intrinsics.
4321 while (isa<DbgInfoIntrinsic>(BBI))
4322 ++BBI;
4323 if (SI == &*BBI)
4324 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004325 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004326 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004327
4328 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004329 if (TurnSwitchRangeIntoICmp(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004330 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004331
4332 // Remove unreachable cases.
Hal Finkel60db0582014-09-07 18:57:58 +00004333 if (EliminateDeadSwitchCases(SI, DL, AT))
Jingyue Wufc029672014-09-30 22:23:38 +00004334 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004335
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004336 if (SwitchToSelect(SI, Builder, DL, AT))
4337 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4338
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004339 if (ForwardSwitchConditionToPHI(SI))
Jingyue Wufc029672014-09-30 22:23:38 +00004340 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004341
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004342 if (SwitchToLookupTable(SI, Builder, TTI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004343 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004344
Chris Lattner25c3af32010-12-13 06:25:44 +00004345 return false;
4346}
4347
4348bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4349 BasicBlock *BB = IBI->getParent();
4350 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004351
Chris Lattner25c3af32010-12-13 06:25:44 +00004352 // Eliminate redundant destinations.
4353 SmallPtrSet<Value *, 8> Succs;
4354 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4355 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004356 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004357 Dest->removePredecessor(BB);
4358 IBI->removeDestination(i);
4359 --i; --e;
4360 Changed = true;
4361 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004362 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004363
4364 if (IBI->getNumDestinations() == 0) {
4365 // If the indirectbr has no successors, change it to unreachable.
4366 new UnreachableInst(IBI->getContext(), IBI);
4367 EraseTerminatorInstAndDCECond(IBI);
4368 return true;
4369 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004370
Chris Lattner25c3af32010-12-13 06:25:44 +00004371 if (IBI->getNumDestinations() == 1) {
4372 // If the indirectbr has one successor, change it to a direct branch.
4373 BranchInst::Create(IBI->getDestination(0), IBI);
4374 EraseTerminatorInstAndDCECond(IBI);
4375 return true;
4376 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004377
Chris Lattner25c3af32010-12-13 06:25:44 +00004378 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4379 if (SimplifyIndirectBrOnSelect(IBI, SI))
Jingyue Wufc029672014-09-30 22:23:38 +00004380 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004381 }
4382 return Changed;
4383}
4384
Devang Patel767f6932011-05-18 18:28:48 +00004385bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004386 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004387
Manman Ren93ab6492012-09-20 22:37:36 +00004388 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4389 return true;
4390
Chris Lattner25c3af32010-12-13 06:25:44 +00004391 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004392 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004393 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4394 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4395 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004396
Chris Lattner25c3af32010-12-13 06:25:44 +00004397 // If the only instruction in the block is a seteq/setne comparison
4398 // against a constant, try to simplify the block.
4399 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4400 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4401 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4402 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004403 if (I->isTerminator() &&
Jingyue Wufc029672014-09-30 22:23:38 +00004404 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4405 BonusInstThreshold, DL, AT))
Chris Lattner25c3af32010-12-13 06:25:44 +00004406 return true;
4407 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004408
Manman Rend33f4ef2012-06-13 05:43:29 +00004409 // If this basic block is ONLY a compare and a branch, and if a predecessor
4410 // branches to us and our successor, fold the comparison into the
4411 // predecessor and use logical operations to update the incoming value
4412 // for PHI nodes in common successor.
Jingyue Wufc029672014-09-30 22:23:38 +00004413 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4414 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004415 return false;
4416}
4417
4418
Devang Patela7ec47d2011-05-18 20:35:38 +00004419bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004420 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004421
Chris Lattner25c3af32010-12-13 06:25:44 +00004422 // Conditional branch
4423 if (isValueEqualityComparison(BI)) {
4424 // If we only have one predecessor, and if it is a branch on this value,
4425 // see if that predecessor totally determines the outcome of this
4426 // switch.
4427 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004428 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004429 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004430
Chris Lattner25c3af32010-12-13 06:25:44 +00004431 // This block must be empty, except for the setcond inst, if it exists.
4432 // Ignore dbg intrinsics.
4433 BasicBlock::iterator I = BB->begin();
4434 // Ignore dbg intrinsics.
4435 while (isa<DbgInfoIntrinsic>(I))
4436 ++I;
4437 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004438 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004439 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004440 } else if (&*I == cast<Instruction>(BI->getCondition())){
4441 ++I;
4442 // Ignore dbg intrinsics.
4443 while (isa<DbgInfoIntrinsic>(I))
4444 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004445 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004446 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004447 }
4448 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004449
Chris Lattner25c3af32010-12-13 06:25:44 +00004450 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004451 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004452 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004453
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004454 // If this basic block is ONLY a compare and a branch, and if a predecessor
4455 // branches to us and one of our successors, fold the comparison into the
4456 // predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00004457 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4458 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004459
Chris Lattner25c3af32010-12-13 06:25:44 +00004460 // We have a conditional branch to two blocks that are only reachable
4461 // from BI. We know that the condbr dominates the two blocks, so see if
4462 // there is any identical code in the "then" and "else" blocks. If so, we
4463 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004464 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4465 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Hal Finkela995f922014-07-10 14:41:31 +00004466 if (HoistThenElseCodeToIf(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004467 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004468 } else {
4469 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004470 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004471 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4472 if (Succ0TI->getNumSuccessors() == 1 &&
4473 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Hal Finkela995f922014-07-10 14:41:31 +00004474 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004475 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004476 }
Craig Topperf40110f2014-04-25 05:29:35 +00004477 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004478 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004479 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004480 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4481 if (Succ1TI->getNumSuccessors() == 1 &&
4482 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Hal Finkela995f922014-07-10 14:41:31 +00004483 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004484 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004485 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004486
Chris Lattner25c3af32010-12-13 06:25:44 +00004487 // If this is a branch on a phi node in the current block, thread control
4488 // through this block if any PHI node entries are constants.
4489 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4490 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004491 if (FoldCondBranchOnPHI(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004492 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004493
Chris Lattner25c3af32010-12-13 06:25:44 +00004494 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004495 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4496 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004497 if (PBI != BI && PBI->isConditional())
4498 if (SimplifyCondBranchToCondBranch(PBI, BI))
Jingyue Wufc029672014-09-30 22:23:38 +00004499 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004500
4501 return false;
4502}
4503
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004504/// Check if passing a value to an instruction will cause undefined behavior.
4505static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4506 Constant *C = dyn_cast<Constant>(V);
4507 if (!C)
4508 return false;
4509
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004510 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004511 return false;
4512
4513 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004514 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004515 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004516
4517 // Now make sure that there are no instructions in between that can alter
4518 // control flow (eg. calls)
4519 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004520 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004521 return false;
4522
4523 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4524 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4525 if (GEP->getPointerOperand() == I)
4526 return passingValueIsAlwaysUndefined(V, GEP);
4527
4528 // Look through bitcasts.
4529 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4530 return passingValueIsAlwaysUndefined(V, BC);
4531
Benjamin Kramer0655b782011-08-26 02:25:55 +00004532 // Load from null is undefined.
4533 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004534 if (!LI->isVolatile())
4535 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004536
Benjamin Kramer0655b782011-08-26 02:25:55 +00004537 // Store to null is undefined.
4538 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004539 if (!SI->isVolatile())
4540 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004541 }
4542 return false;
4543}
4544
4545/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004546/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004547static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4548 for (BasicBlock::iterator i = BB->begin();
4549 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4550 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4551 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4552 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4553 IRBuilder<> Builder(T);
4554 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4555 BB->removePredecessor(PHI->getIncomingBlock(i));
4556 // Turn uncoditional branches into unreachables and remove the dead
4557 // destination from conditional branches.
4558 if (BI->isUnconditional())
4559 Builder.CreateUnreachable();
4560 else
4561 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4562 BI->getSuccessor(0));
4563 BI->eraseFromParent();
4564 return true;
4565 }
4566 // TODO: SwitchInst.
4567 }
4568
4569 return false;
4570}
4571
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004572bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004573 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004574
Chris Lattnerd7beca32010-12-14 06:17:25 +00004575 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004576 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004577
Dan Gohman4a63fad2010-08-14 00:29:42 +00004578 // Remove basic blocks that have no predecessors (except the entry block)...
4579 // or that just have themself as a predecessor. These are unreachable.
Chris Lattnerd7beca32010-12-14 06:17:25 +00004580 if ((pred_begin(BB) == pred_end(BB) &&
4581 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004582 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004583 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004584 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004585 return true;
4586 }
4587
Chris Lattner031340a2003-08-17 19:41:53 +00004588 // Check to see if we can constant propagate this terminator instruction
4589 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004590 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004591
Dan Gohman1a951062009-10-30 22:39:04 +00004592 // Check for and eliminate duplicate PHI nodes in this block.
4593 Changed |= EliminateDuplicatePHINodes(BB);
4594
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004595 // Check for and remove branches that will always cause undefined behavior.
4596 Changed |= removeUndefIntroducingPredecessor(BB);
4597
Chris Lattner2e3832d2010-12-13 05:10:48 +00004598 // Merge basic blocks into their predecessor if there is only one distinct
4599 // pred, and if there is only one distinct successor of the predecessor, and
4600 // if there are no PHI nodes.
4601 //
4602 if (MergeBlockIntoPredecessor(BB))
4603 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004604
Devang Patel15ad6762011-05-18 18:01:27 +00004605 IRBuilder<> Builder(BB);
4606
Dan Gohman20af5a02008-03-11 21:53:06 +00004607 // If there is a trivial two-entry PHI node in this basic block, and we can
4608 // eliminate it, do so now.
4609 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4610 if (PN->getNumIncomingValues() == 2)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004611 Changed |= FoldTwoEntryPHINode(PN, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004612
Devang Patela7ec47d2011-05-18 20:35:38 +00004613 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004614 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004615 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004616 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004617 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004618 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004619 }
4620 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004621 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004622 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4623 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004624 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004625 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004626 } else if (UnreachableInst *UI =
4627 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4628 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004629 } else if (IndirectBrInst *IBI =
4630 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4631 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004632 }
4633
Chris Lattner031340a2003-08-17 19:41:53 +00004634 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004635}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004636
4637/// SimplifyCFG - This function is used to do simplification of a CFG. For
4638/// example, it adjusts branches to branches to eliminate the extra hop, it
4639/// eliminates unreachable basic blocks, and does other "peephole" optimization
4640/// of the CFG. It returns true if a modification was made.
4641///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004642bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00004643 unsigned BonusInstThreshold,
Hal Finkel60db0582014-09-07 18:57:58 +00004644 const DataLayout *DL, AssumptionTracker *AT) {
Jingyue Wufc029672014-09-30 22:23:38 +00004645 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004646}