blob: 051ed1185a83e0e7720ae10c308a229cca3d2893 [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");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000073STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000074STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Manman Ren93ab6492012-09-20 22:37:36 +000075STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000076STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000077
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000078namespace {
Eric Christopherb65acc62012-07-02 23:22:21 +000079 /// ValueEqualityComparisonCase - Represents a case of a switch.
80 struct ValueEqualityComparisonCase {
81 ConstantInt *Value;
82 BasicBlock *Dest;
83
84 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
85 : Value(Value), Dest(Dest) {}
86
87 bool operator<(ValueEqualityComparisonCase RHS) const {
88 // Comparing pointers is ok as we only rely on the order for uniquing.
89 return Value < RHS.Value;
90 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +000091
92 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +000093 };
94
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000095class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +000096 const TargetTransformInfo &TTI;
Jingyue Wufc029672014-09-30 22:23:38 +000097 unsigned BonusInstThreshold;
Rafael Espindola37dc9e12014-02-21 00:06:31 +000098 const DataLayout *const DL;
Hal Finkel60db0582014-09-07 18:57:58 +000099 AssumptionTracker *AT;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000100 Value *isValueEqualityComparison(TerminatorInst *TI);
101 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000102 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000103 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000104 BasicBlock *Pred,
105 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000106 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
107 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000108
Devang Pateldd14e0f2011-05-18 21:33:11 +0000109 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000110 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000111 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000112 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000113 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000114 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000115 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000116
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000117public:
Jingyue Wufc029672014-09-30 22:23:38 +0000118 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
119 const DataLayout *DL, AssumptionTracker *AT)
120 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000121 bool run(BasicBlock *BB);
122};
123}
124
Chris Lattner76dc2042005-08-03 00:19:45 +0000125/// SafeToMergeTerminators - Return true if it is safe to merge these two
126/// terminator instructions together.
127///
128static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
129 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000130
Chris Lattner76dc2042005-08-03 00:19:45 +0000131 // It is not safe to merge these two switch instructions if they have a common
132 // successor, and if that successor has a PHI node, and if *that* PHI node has
133 // conflicting incoming values from the two switch blocks.
134 BasicBlock *SI1BB = SI1->getParent();
135 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000136 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000137
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000138 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
139 if (SI1Succs.count(*I))
140 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000141 isa<PHINode>(BBI); ++BBI) {
142 PHINode *PN = cast<PHINode>(BBI);
143 if (PN->getIncomingValueForBlock(SI1BB) !=
144 PN->getIncomingValueForBlock(SI2BB))
145 return false;
146 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000147
Chris Lattner76dc2042005-08-03 00:19:45 +0000148 return true;
149}
150
Manman Rend33f4ef2012-06-13 05:43:29 +0000151/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
152/// to merge these two terminator instructions together, where SI1 is an
153/// unconditional branch. PhiNodes will store all PHI nodes in common
154/// successors.
155///
156static bool isProfitableToFoldUnconditional(BranchInst *SI1,
157 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000158 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000159 SmallVectorImpl<PHINode*> &PhiNodes) {
160 if (SI1 == SI2) return false; // Can't merge with self!
161 assert(SI1->isUnconditional() && SI2->isConditional());
162
163 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000164 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000165 // 1> We have a constant incoming value for the conditional branch;
166 // 2> We have "Cond" as the incoming value for the unconditional branch;
167 // 3> SI2->getCondition() and Cond have same operands.
168 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
169 if (!Ci2) return false;
170 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
171 Cond->getOperand(1) == Ci2->getOperand(1)) &&
172 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
173 Cond->getOperand(1) == Ci2->getOperand(0)))
174 return false;
175
176 BasicBlock *SI1BB = SI1->getParent();
177 BasicBlock *SI2BB = SI2->getParent();
178 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000179 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
180 if (SI1Succs.count(*I))
181 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000182 isa<PHINode>(BBI); ++BBI) {
183 PHINode *PN = cast<PHINode>(BBI);
184 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000185 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000186 return false;
187 PhiNodes.push_back(PN);
188 }
189 return true;
190}
191
Chris Lattner76dc2042005-08-03 00:19:45 +0000192/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
193/// now be entries in it from the 'NewPred' block. The values that will be
194/// flowing into the PHI nodes will be the same as those coming in from
195/// ExistPred, an existing predecessor of Succ.
196static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
197 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000198 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000199
Chris Lattner80b03a12008-07-13 22:23:11 +0000200 PHINode *PN;
201 for (BasicBlock::iterator I = Succ->begin();
202 (PN = dyn_cast<PHINode>(I)); ++I)
203 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000204}
205
David Majnemer91142c42013-06-01 19:43:23 +0000206/// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000207/// given instruction, which is assumed to be safe to speculate. 1 means
208/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
Hal Finkela995f922014-07-10 14:41:31 +0000209static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
210 assert(isSafeToSpeculativelyExecute(I, DL) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000211 "Instruction is not safe to speculatively execute!");
212 switch (Operator::getOpcode(I)) {
213 default:
214 // In doubt, be conservative.
215 return UINT_MAX;
216 case Instruction::GetElementPtr:
217 // GEPs are cheap if all indices are constant.
218 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
219 return UINT_MAX;
220 return 1;
Louis Gerbarg1f54b822014-05-09 17:02:46 +0000221 case Instruction::ExtractValue:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000222 case Instruction::Load:
223 case Instruction::Add:
224 case Instruction::Sub:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor:
228 case Instruction::Shl:
229 case Instruction::LShr:
230 case Instruction::AShr:
231 case Instruction::ICmp:
232 case Instruction::Trunc:
233 case Instruction::ZExt:
234 case Instruction::SExt:
Matt Arsenaultc8fc08c2014-05-30 18:34:43 +0000235 case Instruction::BitCast:
236 case Instruction::ExtractElement:
237 case Instruction::InsertElement:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000238 return 1; // These are all cheap.
239
240 case Instruction::Call:
241 case Instruction::Select:
242 return 2;
243 }
244}
245
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000246/// DominatesMergePoint - If we have a merge point of an "if condition" as
247/// accepted above, return true if the specified value dominates the block. We
248/// don't handle the true generality of domination here, just a special case
249/// which works well enough for us.
250///
251/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000252/// see if V (which must be an instruction) and its recursive operands
253/// that do not dominate BB have a combined cost lower than CostRemaining and
254/// are non-trapping. If both are true, the instruction is inserted into the
255/// set and true is returned.
256///
257/// The cost for most non-trapping instructions is defined as 1 except for
258/// Select whose cost is 2.
259///
260/// After this function returns, CostRemaining is decreased by the cost of
261/// V plus its non-dominating operands. If that cost is greater than
262/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000263static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000264 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000265 unsigned &CostRemaining,
266 const DataLayout *DL) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000267 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000268 if (!I) {
269 // Non-instructions all dominate instructions, but not all constantexprs
270 // can be executed unconditionally.
271 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
272 if (C->canTrap())
273 return false;
274 return true;
275 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000276 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000277
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000278 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000279 // the bottom of this block.
280 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000281
Chris Lattner0aa56562004-04-09 22:50:22 +0000282 // If this instruction is defined in a block that contains an unconditional
283 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000284 // statement". If not, it definitely dominates the region.
285 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000286 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000287 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000288
Chris Lattner9ac168d2010-12-14 07:41:39 +0000289 // If we aren't allowing aggressive promotion anymore, then don't consider
290 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000291 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000292
Peter Collingbournee3511e12011-04-29 18:47:31 +0000293 // If we have seen this instruction before, don't count it again.
294 if (AggressiveInsts->count(I)) return true;
295
Chris Lattner9ac168d2010-12-14 07:41:39 +0000296 // Okay, it looks like the instruction IS in the "condition". Check to
297 // see if it's a cheap instruction to unconditionally compute, and if it
298 // only uses stuff defined outside of the condition. If so, hoist it out.
Hal Finkela995f922014-07-10 14:41:31 +0000299 if (!isSafeToSpeculativelyExecute(I, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000300 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000301
Hal Finkela995f922014-07-10 14:41:31 +0000302 unsigned Cost = ComputeSpeculationCost(I, DL);
Chris Lattner0aa56562004-04-09 22:50:22 +0000303
Peter Collingbournee3511e12011-04-29 18:47:31 +0000304 if (Cost > CostRemaining)
305 return false;
306
307 CostRemaining -= Cost;
308
309 // Okay, we can only really hoist these out if their operands do
310 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000311 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Hal Finkela995f922014-07-10 14:41:31 +0000312 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000313 return false;
314 // Okay, it's safe to do this! Remember this instruction.
315 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000316 return true;
317}
Chris Lattner466a0492002-05-21 20:50:24 +0000318
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000319/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
320/// and PointerNullValue. Return NULL if value is not a constant int.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000321static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000322 // Normal constant int.
323 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000324 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000325 return CI;
326
327 // This is some kind of pointer constant. Turn it into a pointer-sized
328 // ConstantInt if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000329 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000330
331 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
332 if (isa<ConstantPointerNull>(V))
333 return ConstantInt::get(PtrTy, 0);
334
335 // IntToPtr const int.
336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
337 if (CE->getOpcode() == Instruction::IntToPtr)
338 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
339 // The constant is very likely to have the right type already.
340 if (CI->getType() == PtrTy)
341 return CI;
342 else
343 return cast<ConstantInt>
344 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
345 }
Craig Topperf40110f2014-04-25 05:29:35 +0000346 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000347}
348
Chris Lattner5a177e62010-12-13 04:26:26 +0000349/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
350/// collection of icmp eq/ne instructions that compare a value against a
351/// constant, return the value being compared, and stick the constant into the
352/// Values vector.
Chris Lattner11dafaa2010-12-13 03:30:12 +0000353static Value *
Chris Lattner5a177e62010-12-13 04:26:26 +0000354GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000355 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000356 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000357 if (!I) return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000358
Chris Lattnera442f242010-12-13 04:50:38 +0000359 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner5a177e62010-12-13 04:26:26 +0000360 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000361 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
Benjamin Kramer37172222013-07-04 14:22:02 +0000362 Value *RHSVal;
363 ConstantInt *RHSC;
364
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000365 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer37172222013-07-04 14:22:02 +0000366 // (x & ~2^x) == y --> x == y || x == y|2^x
367 // This undoes a transformation done by instcombine to fuse 2 compares.
368 if (match(ICI->getOperand(0),
369 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
370 APInt Not = ~RHSC->getValue();
371 if (Not.isPowerOf2()) {
372 Vals.push_back(C);
373 Vals.push_back(
374 ConstantInt::get(C->getContext(), C->getValue() | Not));
375 UsedICmps++;
376 return RHSVal;
377 }
378 }
379
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000380 UsedICmps++;
Chris Lattner5a177e62010-12-13 04:26:26 +0000381 Vals.push_back(C);
382 return I->getOperand(0);
383 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000384
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000385 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
386 // the set.
387 ConstantRange Span =
Chris Lattner6b8b4852010-12-18 20:22:49 +0000388 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +0000389
Benjamin Kramer37172222013-07-04 14:22:02 +0000390 // Shift the range if the compare is fed by an add. This is the range
391 // compare idiom as emitted by instcombine.
392 bool hasAdd =
393 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
394 if (hasAdd)
395 Span = Span.subtract(RHSC->getValue());
396
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000397 // If this is an and/!= check then we want to optimize "x ugt 2" into
398 // x != 0 && x != 1.
399 if (!isEQ)
400 Span = Span.inverse();
Andrew Trickf3cf1932012-08-29 21:46:36 +0000401
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000402 // If there are a ton of values, we don't want to make a ginormous switch.
Nick Lewycky219e6bc2012-01-19 18:19:42 +0000403 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
Craig Topperf40110f2014-04-25 05:29:35 +0000404 return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000405
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000406 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
407 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000408 UsedICmps++;
Benjamin Kramer37172222013-07-04 14:22:02 +0000409 return hasAdd ? RHSVal : I->getOperand(0);
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000410 }
Craig Topperf40110f2014-04-25 05:29:35 +0000411 return nullptr;
Chris Lattner9b1af512010-12-13 04:18:32 +0000412 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000413
Chris Lattnera442f242010-12-13 04:50:38 +0000414 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner5a177e62010-12-13 04:26:26 +0000415 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Craig Topperf40110f2014-04-25 05:29:35 +0000416 return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000417
Chris Lattnera442f242010-12-13 04:50:38 +0000418 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000419 unsigned UsedICmpsBeforeLHS = UsedICmps;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000420 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000421 isEQ, UsedICmps)) {
Chris Lattnera442f242010-12-13 04:50:38 +0000422 unsigned NumVals = Vals.size();
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000423 unsigned UsedICmpsBeforeRHS = UsedICmps;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000424 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000425 isEQ, UsedICmps)) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000426 if (LHS == RHS)
427 return LHS;
Chris Lattner79db3572010-12-13 07:41:29 +0000428 Vals.resize(NumVals);
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000429 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner5a177e62010-12-13 04:26:26 +0000430 }
Chris Lattnera442f242010-12-13 04:50:38 +0000431
432 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
433 // set it and return success.
Craig Topperf40110f2014-04-25 05:29:35 +0000434 if (Extra == nullptr || Extra == I->getOperand(1)) {
Chris Lattnera442f242010-12-13 04:50:38 +0000435 Extra = I->getOperand(1);
436 return LHS;
437 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000438
Chris Lattnera442f242010-12-13 04:50:38 +0000439 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000440 UsedICmps = UsedICmpsBeforeLHS;
Craig Topperf40110f2014-04-25 05:29:35 +0000441 return nullptr;
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000442 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000443
Chris Lattnera442f242010-12-13 04:50:38 +0000444 // If the LHS can't be folded in, but Extra is available and RHS can, try to
445 // use LHS as Extra.
Craig Topperf40110f2014-04-25 05:29:35 +0000446 if (Extra == nullptr || Extra == I->getOperand(0)) {
Chris Lattner79db3572010-12-13 07:41:29 +0000447 Value *OldExtra = Extra;
Chris Lattnera442f242010-12-13 04:50:38 +0000448 Extra = I->getOperand(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000449 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000450 isEQ, UsedICmps))
Chris Lattnera442f242010-12-13 04:50:38 +0000451 return RHS;
Chris Lattner79db3572010-12-13 07:41:29 +0000452 assert(Vals.size() == NumValsBeforeLHS);
453 Extra = OldExtra;
Chris Lattnera442f242010-12-13 04:50:38 +0000454 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000455
Craig Topperf40110f2014-04-25 05:29:35 +0000456 return nullptr;
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000457}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000458
Eli Friedmancb61afb2008-12-16 20:54:32 +0000459static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000460 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000461 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
462 Cond = dyn_cast<Instruction>(SI->getCondition());
463 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
464 if (BI->isConditional())
465 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000466 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
467 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000468 }
469
470 TI->eraseFromParent();
471 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
472}
473
Chris Lattner8e84c122008-11-27 23:25:44 +0000474/// isValueEqualityComparison - Return true if the specified terminator checks
475/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000476Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000477 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000478 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
479 // Do not permit merging of large switch instructions into their
480 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000481 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
482 pred_end(SI->getParent())) <= 128)
483 CV = SI->getCondition();
484 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000485 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000486 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000487 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000488 CV = ICI->getOperand(0);
489
490 // Unwrap any lossless ptrtoint cast.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000491 if (DL && CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000492 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
493 Value *Ptr = PTII->getPointerOperand();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000494 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000495 CV = Ptr;
496 }
497 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000498 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000499}
500
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000501/// GetValueEqualityComparisonCases - Given a value comparison instruction,
502/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000503BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000504GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000505 std::vector<ValueEqualityComparisonCase>
506 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000507 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000508 Cases.reserve(SI->getNumCases());
509 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
510 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
511 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000512 return SI->getDefaultDest();
513 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000514
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000515 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000516 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000517 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
518 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000519 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000520 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000521 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000522}
523
Eric Christopherb65acc62012-07-02 23:22:21 +0000524
525/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
526/// in the list that match the specified block.
527static void EliminateBlockCases(BasicBlock *BB,
528 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000529 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000530}
531
532/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
533/// well.
534static bool
535ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
536 std::vector<ValueEqualityComparisonCase > &C2) {
537 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
538
539 // Make V1 be smaller than V2.
540 if (V1->size() > V2->size())
541 std::swap(V1, V2);
542
543 if (V1->size() == 0) return false;
544 if (V1->size() == 1) {
545 // Just scan V2.
546 ConstantInt *TheVal = (*V1)[0].Value;
547 for (unsigned i = 0, e = V2->size(); i != e; ++i)
548 if (TheVal == (*V2)[i].Value)
549 return true;
550 }
551
552 // Otherwise, just sort both lists and compare element by element.
553 array_pod_sort(V1->begin(), V1->end());
554 array_pod_sort(V2->begin(), V2->end());
555 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
556 while (i1 != e1 && i2 != e2) {
557 if ((*V1)[i1].Value == (*V2)[i2].Value)
558 return true;
559 if ((*V1)[i1].Value < (*V2)[i2].Value)
560 ++i1;
561 else
562 ++i2;
563 }
564 return false;
565}
566
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000567/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
568/// terminator instruction and its block is known to only have a single
569/// predecessor block, check to see if that predecessor is also a value
570/// comparison with the same value, and if that comparison determines the
571/// outcome of this comparison. If so, simplify TI. This does a very limited
572/// form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000573bool SimplifyCFGOpt::
574SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000575 BasicBlock *Pred,
576 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000577 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
578 if (!PredVal) return false; // Not a value comparison in predecessor.
579
580 Value *ThisVal = isValueEqualityComparison(TI);
581 assert(ThisVal && "This isn't a value comparison!!");
582 if (ThisVal != PredVal) return false; // Different predicates.
583
Andrew Trick3051aa12012-08-29 21:46:38 +0000584 // TODO: Preserve branch weight metadata, similarly to how
585 // FoldValueComparisonIntoPredecessors preserves it.
586
Chris Lattner1cca9592005-02-24 06:17:52 +0000587 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000588 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000589 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
590 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000591 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000592
Chris Lattner1cca9592005-02-24 06:17:52 +0000593 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000594 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000595 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000596 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000597
598 // If TI's block is the default block from Pred's comparison, potentially
599 // simplify TI based on this knowledge.
600 if (PredDef == TI->getParent()) {
601 // If we are here, we know that the value is none of those cases listed in
602 // PredCases. If there are any cases in ThisCases that are in PredCases, we
603 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000604 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000605 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000606
Chris Lattner4088e2b2010-12-13 01:47:07 +0000607 if (isa<BranchInst>(TI)) {
608 // Okay, one of the successors of this condbr is dead. Convert it to a
609 // uncond br.
610 assert(ThisCases.size() == 1 && "Branch can only have one case!");
611 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000612 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000613 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000614
Chris Lattner4088e2b2010-12-13 01:47:07 +0000615 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000616 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000617
Chris Lattner4088e2b2010-12-13 01:47:07 +0000618 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
619 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000620
Chris Lattner4088e2b2010-12-13 01:47:07 +0000621 EraseTerminatorInstAndDCECond(TI);
622 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000623 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000624
Chris Lattner4088e2b2010-12-13 01:47:07 +0000625 SwitchInst *SI = cast<SwitchInst>(TI);
626 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000627 SmallPtrSet<Constant*, 16> DeadCases;
628 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
629 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000630
David Greene725c7c32010-01-05 01:26:52 +0000631 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000632 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000633
Manman Ren8691e522012-09-14 21:53:06 +0000634 // Collect branch weights into a vector.
635 SmallVector<uint32_t, 8> Weights;
636 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
637 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
638 if (HasWeight)
639 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
640 ++MD_i) {
641 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
642 assert(CI);
643 Weights.push_back(CI->getValue().getZExtValue());
644 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000645 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
646 --i;
647 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000648 if (HasWeight) {
649 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
650 Weights.pop_back();
651 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000652 i.getCaseSuccessor()->removePredecessor(TI->getParent());
653 SI->removeCase(i);
654 }
655 }
Manman Ren97c18762012-10-11 22:28:34 +0000656 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000657 SI->setMetadata(LLVMContext::MD_prof,
658 MDBuilder(SI->getParent()->getContext()).
659 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000660
661 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000662 return true;
663 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000664
Chris Lattner4088e2b2010-12-13 01:47:07 +0000665 // Otherwise, TI's block must correspond to some matched value. Find out
666 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000667 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000668 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000669 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
670 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000671 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000672 return false; // Cannot handle multiple values coming to this block.
673 TIV = PredCases[i].Value;
674 }
675 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000676
677 // Okay, we found the one constant that our value can be if we get into TI's
678 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000679 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000680 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
681 if (ThisCases[i].Value == TIV) {
682 TheRealDest = ThisCases[i].Dest;
683 break;
684 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000685
686 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000687 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000688
689 // Remove PHI node entries for dead edges.
690 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000691 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
692 if (*SI != CheckEdge)
693 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000694 else
Craig Topperf40110f2014-04-25 05:29:35 +0000695 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000696
697 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000698 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000699 (void) NI;
700
701 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
702 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
703
704 EraseTerminatorInstAndDCECond(TI);
705 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000706}
707
Dale Johannesen7f99d222009-03-12 21:01:11 +0000708namespace {
709 /// ConstantIntOrdering - This class implements a stable ordering of constant
710 /// integers that does not depend on their address. This is important for
711 /// applications that sort ConstantInt's to ensure uniqueness.
712 struct ConstantIntOrdering {
713 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
714 return LHS->getValue().ult(RHS->getValue());
715 }
716 };
717}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000718
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000719static int ConstantIntSortPredicate(ConstantInt *const *P1,
720 ConstantInt *const *P2) {
721 const ConstantInt *LHS = *P1;
722 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000723 if (LHS->getValue().ult(RHS->getValue()))
724 return 1;
725 if (LHS->getValue() == RHS->getValue())
726 return 0;
727 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000728}
729
Andrew Trick3051aa12012-08-29 21:46:38 +0000730static inline bool HasBranchWeights(const Instruction* I) {
731 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
732 if (ProfMD && ProfMD->getOperand(0))
733 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
734 return MDS->getString().equals("branch_weights");
735
736 return false;
737}
738
Manman Ren571d9e42012-09-11 17:43:35 +0000739/// Get Weights of a given TerminatorInst, the default weight is at the front
740/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
741/// metadata.
742static void GetBranchWeights(TerminatorInst *TI,
743 SmallVectorImpl<uint64_t> &Weights) {
744 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
745 assert(MD);
746 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000747 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000748 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000749 }
750
Manman Ren571d9e42012-09-11 17:43:35 +0000751 // If TI is a conditional eq, the default case is the false case,
752 // and the corresponding branch-weight data is at index 2. We swap the
753 // default weight to be the first entry.
754 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
755 assert(Weights.size() == 2);
756 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
757 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
758 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000759 }
760}
761
Manman Renf1cb16e2014-01-27 23:39:03 +0000762/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000763static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000764 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
765 if (Max > UINT_MAX) {
766 unsigned Offset = 32 - countLeadingZeros(Max);
767 for (uint64_t &I : Weights)
768 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000769 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000770}
771
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000772/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
773/// equality comparison instruction (either a switch or a branch on "X == c").
774/// See if any of the predecessors of the terminator block are value comparisons
775/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000776bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
777 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000778 BasicBlock *BB = TI->getParent();
779 Value *CV = isValueEqualityComparison(TI); // CondVal
780 assert(CV && "Not a comparison?");
781 bool Changed = false;
782
Chris Lattner6b39cb92008-02-18 07:42:56 +0000783 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000784 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000785 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000786
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000787 // See if the predecessor is a comparison with the same value.
788 TerminatorInst *PTI = Pred->getTerminator();
789 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
790
791 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
792 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000793 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000794 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
795
Eric Christopherb65acc62012-07-02 23:22:21 +0000796 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000797 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
798
799 // Based on whether the default edge from PTI goes to BB or not, fill in
800 // PredCases and PredDefault with the new switch cases we would like to
801 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000802 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000803
Andrew Trick3051aa12012-08-29 21:46:38 +0000804 // Update the branch weight metadata along the way
805 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000806 bool PredHasWeights = HasBranchWeights(PTI);
807 bool SuccHasWeights = HasBranchWeights(TI);
808
Manman Ren5e5049d2012-09-14 19:05:19 +0000809 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000810 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000811 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000812 if (Weights.size() != 1 + PredCases.size())
813 PredHasWeights = SuccHasWeights = false;
814 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000815 // If there are no predecessor weights but there are successor weights,
816 // populate Weights with 1, which will later be scaled to the sum of
817 // successor's weights
818 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000819
Manman Ren571d9e42012-09-11 17:43:35 +0000820 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000821 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000822 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000823 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000824 if (SuccWeights.size() != 1 + BBCases.size())
825 PredHasWeights = SuccHasWeights = false;
826 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000827 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000828
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000829 if (PredDefault == BB) {
830 // If this is the default destination from PTI, only the edges in TI
831 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000832 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
833 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
834 if (PredCases[i].Dest != BB)
835 PTIHandled.insert(PredCases[i].Value);
836 else {
837 // The default destination is BB, we don't need explicit targets.
838 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000839
Manman Ren571d9e42012-09-11 17:43:35 +0000840 if (PredHasWeights || SuccHasWeights) {
841 // Increase weight for the default case.
842 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000843 std::swap(Weights[i+1], Weights.back());
844 Weights.pop_back();
845 }
846
Eric Christopherb65acc62012-07-02 23:22:21 +0000847 PredCases.pop_back();
848 --i; --e;
849 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000850
Eric Christopherb65acc62012-07-02 23:22:21 +0000851 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000852 if (PredDefault != BBDefault) {
853 PredDefault->removePredecessor(Pred);
854 PredDefault = BBDefault;
855 NewSuccessors.push_back(BBDefault);
856 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000857
Manman Ren571d9e42012-09-11 17:43:35 +0000858 unsigned CasesFromPred = Weights.size();
859 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000860 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
861 if (!PTIHandled.count(BBCases[i].Value) &&
862 BBCases[i].Dest != BBDefault) {
863 PredCases.push_back(BBCases[i]);
864 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000865 if (SuccHasWeights || PredHasWeights) {
866 // The default weight is at index 0, so weight for the ith case
867 // should be at index i+1. Scale the cases from successor by
868 // PredDefaultWeight (Weights[0]).
869 Weights.push_back(Weights[0] * SuccWeights[i+1]);
870 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000871 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000872 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000873
Manman Ren571d9e42012-09-11 17:43:35 +0000874 if (SuccHasWeights || PredHasWeights) {
875 ValidTotalSuccWeight += SuccWeights[0];
876 // Scale the cases from predecessor by ValidTotalSuccWeight.
877 for (unsigned i = 1; i < CasesFromPred; ++i)
878 Weights[i] *= ValidTotalSuccWeight;
879 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
880 Weights[0] *= SuccWeights[0];
881 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000882 } else {
883 // If this is not the default destination from PSI, only the edges
884 // in SI that occur in PSI with a destination of BB will be
885 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000886 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000887 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000888 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
889 if (PredCases[i].Dest == BB) {
890 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000891
892 if (PredHasWeights || SuccHasWeights) {
893 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
894 std::swap(Weights[i+1], Weights.back());
895 Weights.pop_back();
896 }
897
Eric Christopherb65acc62012-07-02 23:22:21 +0000898 std::swap(PredCases[i], PredCases.back());
899 PredCases.pop_back();
900 --i; --e;
901 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000902
903 // Okay, now we know which constants were sent to BB from the
904 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000905 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
906 if (PTIHandled.count(BBCases[i].Value)) {
907 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000908 if (PredHasWeights || SuccHasWeights)
909 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000910 PredCases.push_back(BBCases[i]);
911 NewSuccessors.push_back(BBCases[i].Dest);
912 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
913 }
914
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000915 // If there are any constants vectored to BB that TI doesn't handle,
916 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000917 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000918 PTIHandled.begin(),
919 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000920 if (PredHasWeights || SuccHasWeights)
921 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000922 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000923 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000924 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000925 }
926
927 // Okay, at this point, we know which new successor Pred will get. Make
928 // sure we update the number of entries in the PHI nodes for these
929 // successors.
930 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
931 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
932
Devang Patel58380552011-05-18 20:53:17 +0000933 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000934 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000935 if (CV->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000936 assert(DL && "Cannot switch on pointer without DataLayout");
937 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000938 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000939 }
940
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000941 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000942 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
943 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000944 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +0000945 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
946 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000947
Andrew Trick3051aa12012-08-29 21:46:38 +0000948 if (PredHasWeights || SuccHasWeights) {
949 // Halve the weights if any of them cannot fit in an uint32_t
950 FitWeights(Weights);
951
952 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
953
954 NewSI->setMetadata(LLVMContext::MD_prof,
955 MDBuilder(BB->getContext()).
956 createBranchWeights(MDWeights));
957 }
958
Eli Friedmancb61afb2008-12-16 20:54:32 +0000959 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +0000960
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000961 // Okay, last check. If BB is still a successor of PSI, then we must
962 // have an infinite loop case. If so, add an infinitely looping block
963 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +0000964 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000965 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
966 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000967 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +0000968 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000969 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +0000970 InfLoopBlock = BasicBlock::Create(BB->getContext(),
971 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +0000972 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000973 }
974 NewSI->setSuccessor(i, InfLoopBlock);
975 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000976
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000977 Changed = true;
978 }
979 }
980 return Changed;
981}
982
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000983// isSafeToHoistInvoke - If we would need to insert a select that uses the
984// value of this invoke (comments in HoistThenElseCodeToIf explain why we
985// would need to do this), we can't hoist the invoke, as there is nowhere
986// to put the select in this case.
987static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
988 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000989 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000990 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000991 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000992 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
993 Value *BB1V = PN->getIncomingValueForBlock(BB1);
994 Value *BB2V = PN->getIncomingValueForBlock(BB2);
995 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
996 return false;
997 }
998 }
999 }
1000 return true;
1001}
1002
Chris Lattnerd683bdd2005-08-03 17:59:45 +00001003/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +00001004/// BB2, hoist any common code in the two blocks up into the branch block. The
1005/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Hal Finkela995f922014-07-10 14:41:31 +00001006static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001007 // This does very trivial matching, with limited scanning, to find identical
1008 // instructions in the two blocks. In particular, we don't want to get into
1009 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1010 // such, we currently just scan for obviously identical instructions in an
1011 // identical order.
1012 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1013 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1014
Devang Patelf10e2872009-02-04 00:03:08 +00001015 BasicBlock::iterator BB1_Itr = BB1->begin();
1016 BasicBlock::iterator BB2_Itr = BB2->begin();
1017
1018 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001019 // Skip debug info if it is not identical.
1020 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1021 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1022 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1023 while (isa<DbgInfoIntrinsic>(I1))
1024 I1 = BB1_Itr++;
1025 while (isa<DbgInfoIntrinsic>(I2))
1026 I2 = BB2_Itr++;
1027 }
Devang Patele48ddf82011-04-07 00:30:15 +00001028 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001029 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001030 return false;
1031
Chris Lattner389cfac2004-11-30 00:29:14 +00001032 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001033
David Majnemerc82f27a2013-06-03 20:43:12 +00001034 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001035 do {
1036 // If we are hoisting the terminator instruction, don't move one (making a
1037 // broken BB), instead clone it, and remove BI.
1038 if (isa<TerminatorInst>(I1))
1039 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001040
Chris Lattner389cfac2004-11-30 00:29:14 +00001041 // For a normal instruction, we just move one to right before the branch,
1042 // then replace all uses of the other with the first. Finally, we remove
1043 // the now redundant second instruction.
1044 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1045 if (!I2->use_empty())
1046 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001047 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001048 unsigned KnownIDs[] = {
1049 LLVMContext::MD_tbaa,
1050 LLVMContext::MD_range,
1051 LLVMContext::MD_fpmath,
1052 LLVMContext::MD_invariant_load
1053 };
1054 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001055 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001056 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001057
Devang Patelf10e2872009-02-04 00:03:08 +00001058 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001059 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001060 // Skip debug info if it is not identical.
1061 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1062 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1063 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1064 while (isa<DbgInfoIntrinsic>(I1))
1065 I1 = BB1_Itr++;
1066 while (isa<DbgInfoIntrinsic>(I2))
1067 I2 = BB2_Itr++;
1068 }
Devang Patele48ddf82011-04-07 00:30:15 +00001069 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001070
1071 return true;
1072
1073HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001074 // It may not be possible to hoist an invoke.
1075 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001076 return Changed;
1077
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001078 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001079 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001080 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001081 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1082 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1083 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1084 if (BB1V == BB2V)
1085 continue;
1086
Hal Finkela995f922014-07-10 14:41:31 +00001087 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001088 return Changed;
Hal Finkela995f922014-07-10 14:41:31 +00001089 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001090 return Changed;
1091 }
1092 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001093
Chris Lattner389cfac2004-11-30 00:29:14 +00001094 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001095 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001096 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001097 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001098 I1->replaceAllUsesWith(NT);
1099 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001100 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001101 }
1102
Devang Patel1407fb42011-05-19 20:52:46 +00001103 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001104 // Hoisting one of the terminators from our successor is a great thing.
1105 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1106 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1107 // nodes, so we insert select instruction to compute the final result.
1108 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001109 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001110 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001111 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001112 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001113 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1114 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001115 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001116
Chris Lattner4088e2b2010-12-13 01:47:07 +00001117 // These values do not agree. Insert a select instruction before NT
1118 // that determines the right value.
1119 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001120 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001121 SI = cast<SelectInst>
1122 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1123 BB1V->getName()+"."+BB2V->getName()));
1124
Chris Lattner4088e2b2010-12-13 01:47:07 +00001125 // Make the PHI node use the select for all incoming values for BB1/BB2
1126 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1127 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1128 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001129 }
1130 }
1131
1132 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001133 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1134 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001135
Eli Friedmancb61afb2008-12-16 20:54:32 +00001136 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001137 return true;
1138}
1139
Manman Ren93ab6492012-09-20 22:37:36 +00001140/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1141/// check whether BBEnd has only two predecessors and the other predecessor
1142/// ends with an unconditional branch. If it is true, sink any common code
1143/// in the two predecessors to BBEnd.
1144static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1145 assert(BI1->isUnconditional());
1146 BasicBlock *BB1 = BI1->getParent();
1147 BasicBlock *BBEnd = BI1->getSuccessor(0);
1148
1149 // Check that BBEnd has two predecessors and the other predecessor ends with
1150 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001151 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1152 BasicBlock *Pred0 = *PI++;
1153 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001154 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001155 BasicBlock *Pred1 = *PI++;
1156 if (PI != PE) // More than two predecessors.
1157 return false;
1158 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001159 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1160 if (!BI2 || !BI2->isUnconditional())
1161 return false;
1162
1163 // Gather the PHI nodes in BBEnd.
1164 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
Craig Topperf40110f2014-04-25 05:29:35 +00001165 Instruction *FirstNonPhiInBBEnd = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001166 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1167 I != E; ++I) {
1168 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1169 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001170 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Manman Ren93ab6492012-09-20 22:37:36 +00001171 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1172 } else {
1173 FirstNonPhiInBBEnd = &*I;
1174 break;
1175 }
1176 }
1177 if (!FirstNonPhiInBBEnd)
1178 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001179
Manman Ren93ab6492012-09-20 22:37:36 +00001180
1181 // This does very trivial matching, with limited scanning, to find identical
1182 // instructions in the two blocks. We scan backward for obviously identical
1183 // instructions in an identical order.
1184 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1185 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1186 RE2 = BB2->getInstList().rend();
1187 // Skip debug info.
1188 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1189 if (RI1 == RE1)
1190 return false;
1191 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1192 if (RI2 == RE2)
1193 return false;
1194 // Skip the unconditional branches.
1195 ++RI1;
1196 ++RI2;
1197
1198 bool Changed = false;
1199 while (RI1 != RE1 && RI2 != RE2) {
1200 // Skip debug info.
1201 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1202 if (RI1 == RE1)
1203 return Changed;
1204 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1205 if (RI2 == RE2)
1206 return Changed;
1207
1208 Instruction *I1 = &*RI1, *I2 = &*RI2;
1209 // I1 and I2 should have a single use in the same PHI node, and they
1210 // perform the same operation.
1211 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1212 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1213 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1214 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1215 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1216 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1217 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1218 !I1->hasOneUse() || !I2->hasOneUse() ||
1219 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1220 MapValueFromBB1ToBB2[I1].first != I2)
1221 return Changed;
1222
1223 // Check whether we should swap the operands of ICmpInst.
1224 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1225 bool SwapOpnds = false;
1226 if (ICmp1 && ICmp2 &&
1227 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1228 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1229 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1230 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1231 ICmp2->swapOperands();
1232 SwapOpnds = true;
1233 }
1234 if (!I1->isSameOperationAs(I2)) {
1235 if (SwapOpnds)
1236 ICmp2->swapOperands();
1237 return Changed;
1238 }
1239
1240 // The operands should be either the same or they need to be generated
1241 // with a PHI node after sinking. We only handle the case where there is
1242 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001243 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001244 unsigned Op1Idx = 0;
1245 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1246 if (I1->getOperand(I) == I2->getOperand(I))
1247 continue;
1248 // Early exit if we have more-than one pair of different operands or
1249 // the different operand is already in MapValueFromBB1ToBB2.
1250 // Early exit if we need a PHI node to replace a constant.
1251 if (DifferentOp1 ||
1252 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1253 MapValueFromBB1ToBB2.end() ||
1254 isa<Constant>(I1->getOperand(I)) ||
1255 isa<Constant>(I2->getOperand(I))) {
1256 // If we can't sink the instructions, undo the swapping.
1257 if (SwapOpnds)
1258 ICmp2->swapOperands();
1259 return Changed;
1260 }
1261 DifferentOp1 = I1->getOperand(I);
1262 Op1Idx = I;
1263 DifferentOp2 = I2->getOperand(I);
1264 }
1265
1266 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1267 // remove (I1, I2) from MapValueFromBB1ToBB2.
1268 if (DifferentOp1) {
1269 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1270 DifferentOp1->getName() + ".sink",
1271 BBEnd->begin());
1272 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1273 // I1 should use NewPN instead of DifferentOp1.
1274 I1->setOperand(Op1Idx, NewPN);
1275 NewPN->addIncoming(DifferentOp1, BB1);
1276 NewPN->addIncoming(DifferentOp2, BB2);
1277 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1278 }
1279 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1280 MapValueFromBB1ToBB2.erase(I1);
1281
1282 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1283 DEBUG(dbgs() << " " << *I2 << "\n";);
1284 // We need to update RE1 and RE2 if we are going to sink the first
1285 // instruction in the basic block down.
1286 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1287 // Sink the instruction.
1288 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1289 if (!OldPN->use_empty())
1290 OldPN->replaceAllUsesWith(I1);
1291 OldPN->eraseFromParent();
1292
1293 if (!I2->use_empty())
1294 I2->replaceAllUsesWith(I1);
1295 I1->intersectOptionalDataWith(I2);
1296 I2->eraseFromParent();
1297
1298 if (UpdateRE1)
1299 RE1 = BB1->getInstList().rend();
1300 if (UpdateRE2)
1301 RE2 = BB2->getInstList().rend();
1302 FirstNonPhiInBBEnd = I1;
1303 NumSinkCommons++;
1304 Changed = true;
1305 }
1306 return Changed;
1307}
1308
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001309/// \brief Determine if we can hoist sink a sole store instruction out of a
1310/// conditional block.
1311///
1312/// We are looking for code like the following:
1313/// BrBB:
1314/// store i32 %add, i32* %arrayidx2
1315/// ... // No other stores or function calls (we could be calling a memory
1316/// ... // function).
1317/// %cmp = icmp ult %x, %y
1318/// br i1 %cmp, label %EndBB, label %ThenBB
1319/// ThenBB:
1320/// store i32 %add5, i32* %arrayidx2
1321/// br label EndBB
1322/// EndBB:
1323/// ...
1324/// We are going to transform this into:
1325/// BrBB:
1326/// store i32 %add, i32* %arrayidx2
1327/// ... //
1328/// %cmp = icmp ult %x, %y
1329/// %add.add5 = select i1 %cmp, i32 %add, %add5
1330/// store i32 %add.add5, i32* %arrayidx2
1331/// ...
1332///
1333/// \return The pointer to the value of the previous store if the store can be
1334/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001335static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1336 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001337 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1338 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001339 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001340
1341 // Volatile or atomic.
1342 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001343 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001344
1345 Value *StorePtr = StoreToHoist->getPointerOperand();
1346
1347 // Look for a store to the same pointer in BrBB.
1348 unsigned MaxNumInstToLookAt = 10;
1349 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1350 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1351 Instruction *CurI = &*RI;
1352
1353 // Could be calling an instruction that effects memory like free().
1354 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001355 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001356
1357 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1358 // Found the previous store make sure it stores to the same location.
1359 if (SI && SI->getPointerOperand() == StorePtr)
1360 // Found the previous store, return its value operand.
1361 return SI->getValueOperand();
1362 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001363 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001364 }
1365
Craig Topperf40110f2014-04-25 05:29:35 +00001366 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001367}
1368
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001369/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001370///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001371/// Note that this is a very risky transform currently. Speculating
1372/// instructions like this is most often not desirable. Instead, there is an MI
1373/// pass which can do it with full awareness of the resource constraints.
1374/// However, some cases are "obvious" and we should do directly. An example of
1375/// this is speculating a single, reasonably cheap instruction.
1376///
1377/// There is only one distinct advantage to flattening the CFG at the IR level:
1378/// it makes very common but simplistic optimizations such as are common in
1379/// instcombine and the DAG combiner more powerful by removing CFG edges and
1380/// modeling their effects with easier to reason about SSA value graphs.
1381///
1382///
1383/// An illustration of this transform is turning this IR:
1384/// \code
1385/// BB:
1386/// %cmp = icmp ult %x, %y
1387/// br i1 %cmp, label %EndBB, label %ThenBB
1388/// ThenBB:
1389/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001390/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001391/// EndBB:
1392/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1393/// ...
1394/// \endcode
1395///
1396/// Into this IR:
1397/// \code
1398/// BB:
1399/// %cmp = icmp ult %x, %y
1400/// %sub = sub %x, %y
1401/// %cond = select i1 %cmp, 0, %sub
1402/// ...
1403/// \endcode
1404///
1405/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001406static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1407 const DataLayout *DL) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001408 // Be conservative for now. FP select instruction can often be expensive.
1409 Value *BrCond = BI->getCondition();
1410 if (isa<FCmpInst>(BrCond))
1411 return false;
1412
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001413 BasicBlock *BB = BI->getParent();
1414 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1415
1416 // If ThenBB is actually on the false edge of the conditional branch, remember
1417 // to swap the select operands later.
1418 bool Invert = false;
1419 if (ThenBB != BI->getSuccessor(0)) {
1420 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1421 Invert = true;
1422 }
1423 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1424
Chandler Carruthceff2222013-01-25 05:40:09 +00001425 // Keep a count of how many times instructions are used within CondBB when
1426 // they are candidates for sinking into CondBB. Specifically:
1427 // - They are defined in BB, and
1428 // - They have no side effects, and
1429 // - All of their uses are in CondBB.
1430 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1431
Chandler Carruth7481ca82013-01-24 11:52:58 +00001432 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001433 Value *SpeculatedStoreValue = nullptr;
1434 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001435 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001436 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001437 BBI != BBE; ++BBI) {
1438 Instruction *I = BBI;
1439 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001440 if (isa<DbgInfoIntrinsic>(I))
1441 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001442
Chandler Carruth7481ca82013-01-24 11:52:58 +00001443 // Only speculatively execution a single instruction (not counting the
1444 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001445 ++SpeculationCost;
1446 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001447 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001448
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001449 // Don't hoist the instruction if it's unsafe or expensive.
Hal Finkela995f922014-07-10 14:41:31 +00001450 if (!isSafeToSpeculativelyExecute(I, DL) &&
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001451 !(HoistCondStores &&
1452 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1453 EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001454 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001455 if (!SpeculatedStoreValue &&
Hal Finkela995f922014-07-10 14:41:31 +00001456 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001457 return false;
1458
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001459 // Store the store speculation candidate.
1460 if (SpeculatedStoreValue)
1461 SpeculatedStore = cast<StoreInst>(I);
1462
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001463 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001464 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001465 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001466 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001467 i != e; ++i) {
1468 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001469 if (!OpI || OpI->getParent() != BB ||
1470 OpI->mayHaveSideEffects())
1471 continue; // Not a candidate for sinking.
1472
1473 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001474 }
1475 }
Evan Cheng89200c92008-06-07 08:52:29 +00001476
Chandler Carruthceff2222013-01-25 05:40:09 +00001477 // Consider any sink candidates which are only used in CondBB as costs for
1478 // speculation. Note, while we iterate over a DenseMap here, we are summing
1479 // and so iteration order isn't significant.
1480 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1481 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1482 I != E; ++I)
1483 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001484 ++SpeculationCost;
1485 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001486 return false;
1487 }
1488
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001489 // Check that the PHI nodes can be converted to selects.
1490 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001491 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001492 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001493 Value *OrigV = PN->getIncomingValueForBlock(BB);
1494 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001495
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001496 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001497 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001498 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001499 continue;
1500
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001501 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001502 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1503 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1504 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001505 continue; // Known safe and cheap.
1506
Hal Finkela995f922014-07-10 14:41:31 +00001507 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1508 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001509 return false;
Hal Finkela995f922014-07-10 14:41:31 +00001510 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1511 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001512 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
Chandler Carruth8a210052013-01-24 11:53:01 +00001513 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001514
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001515 // Account for the cost of an unfolded ConstantExpr which could end up
1516 // getting expanded into Instructions.
1517 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001518 // constant expression.
1519 ++SpeculationCost;
1520 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001521 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001522 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001523
1524 // If there are no PHIs to process, bail early. This helps ensure idempotence
1525 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001526 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001527 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001528
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001529 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001530 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001531
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001532 // Insert a select of the value of the speculated store.
1533 if (SpeculatedStoreValue) {
1534 IRBuilder<true, NoFolder> Builder(BI);
1535 Value *TrueV = SpeculatedStore->getValueOperand();
1536 Value *FalseV = SpeculatedStoreValue;
1537 if (Invert)
1538 std::swap(TrueV, FalseV);
1539 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1540 "." + FalseV->getName());
1541 SpeculatedStore->setOperand(0, S);
1542 }
1543
Chandler Carruth7481ca82013-01-24 11:52:58 +00001544 // Hoist the instructions.
1545 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001546 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001547
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001548 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001549 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001550 for (BasicBlock::iterator I = EndBB->begin();
1551 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1552 unsigned OrigI = PN->getBasicBlockIndex(BB);
1553 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1554 Value *OrigV = PN->getIncomingValue(OrigI);
1555 Value *ThenV = PN->getIncomingValue(ThenI);
1556
1557 // Skip PHIs which are trivial.
1558 if (OrigV == ThenV)
1559 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001560
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001561 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001562 // false value is the preexisting value. Swap them if the branch
1563 // destinations were inverted.
1564 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001565 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001566 std::swap(TrueV, FalseV);
1567 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1568 TrueV->getName() + "." + FalseV->getName());
1569 PN->setIncomingValue(OrigI, V);
1570 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001571 }
1572
Evan Cheng89553cc2008-06-12 21:15:59 +00001573 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001574 return true;
1575}
1576
Tom Stellarde1631dd2013-10-21 20:07:30 +00001577/// \returns True if this block contains a CallInst with the NoDuplicate
1578/// attribute.
1579static bool HasNoDuplicateCall(const BasicBlock *BB) {
1580 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1581 const CallInst *CI = dyn_cast<CallInst>(I);
1582 if (!CI)
1583 continue;
1584 if (CI->cannotDuplicate())
1585 return true;
1586 }
1587 return false;
1588}
1589
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001590/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1591/// across this block.
1592static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1593 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001594 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001595
Devang Patel84fceff2009-03-10 18:00:05 +00001596 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001597 if (isa<DbgInfoIntrinsic>(BBI))
1598 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001599 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001600 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001601
Dale Johannesened6f5a82009-03-12 23:18:09 +00001602 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001603 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001604 for (User *U : BBI->users()) {
1605 Instruction *UI = cast<Instruction>(U);
1606 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001607 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001608
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001609 // Looks ok, continue checking.
1610 }
Chris Lattner6c701062005-09-20 01:48:40 +00001611
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001612 return true;
1613}
1614
Chris Lattner748f9032005-09-19 23:49:37 +00001615/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1616/// that is defined in the same block as the branch and if any PHI entries are
1617/// constants, thread edges corresponding to that entry to be branches to their
1618/// ultimate destination.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001619static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001620 BasicBlock *BB = BI->getParent();
1621 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001622 // NOTE: we currently cannot transform this case if the PHI node is used
1623 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001624 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1625 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001626
Chris Lattner748f9032005-09-19 23:49:37 +00001627 // Degenerate case of a single entry PHI.
1628 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001629 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001630 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001631 }
1632
1633 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001634 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001635
Tom Stellarde1631dd2013-10-21 20:07:30 +00001636 if (HasNoDuplicateCall(BB)) return false;
1637
Chris Lattner748f9032005-09-19 23:49:37 +00001638 // Okay, this is a simple enough basic block. See if any phi values are
1639 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001640 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001641 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001642 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001643
Chris Lattner4088e2b2010-12-13 01:47:07 +00001644 // Okay, we now know that all edges from PredBB should be revectored to
1645 // branch to RealDest.
1646 BasicBlock *PredBB = PN->getIncomingBlock(i);
1647 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001648
Chris Lattner4088e2b2010-12-13 01:47:07 +00001649 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001650 // Skip if the predecessor's terminator is an indirect branch.
1651 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001652
Chris Lattner4088e2b2010-12-13 01:47:07 +00001653 // The dest block might have PHI nodes, other predecessors and other
1654 // difficult cases. Instead of being smart about this, just insert a new
1655 // block that jumps to the destination block, effectively splitting
1656 // the edge we are about to create.
1657 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1658 RealDest->getName()+".critedge",
1659 RealDest->getParent(), RealDest);
1660 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001661
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001662 // Update PHI nodes.
1663 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001664
1665 // BB may have instructions that are being threaded over. Clone these
1666 // instructions into EdgeBB. We know that there will be no uses of the
1667 // cloned instructions outside of EdgeBB.
1668 BasicBlock::iterator InsertPt = EdgeBB->begin();
1669 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1670 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1671 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1672 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1673 continue;
1674 }
1675 // Clone the instruction.
1676 Instruction *N = BBI->clone();
1677 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001678
Chris Lattner4088e2b2010-12-13 01:47:07 +00001679 // Update operands due to translation.
1680 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1681 i != e; ++i) {
1682 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1683 if (PI != TranslateMap.end())
1684 *i = PI->second;
1685 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001686
Chris Lattner4088e2b2010-12-13 01:47:07 +00001687 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001688 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001689 TranslateMap[BBI] = V;
1690 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001691 } else {
1692 // Insert the new instruction into its new home.
1693 EdgeBB->getInstList().insert(InsertPt, N);
1694 if (!BBI->use_empty())
1695 TranslateMap[BBI] = N;
1696 }
1697 }
1698
1699 // Loop over all of the edges from PredBB to BB, changing them to branch
1700 // to EdgeBB instead.
1701 TerminatorInst *PredBBTI = PredBB->getTerminator();
1702 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1703 if (PredBBTI->getSuccessor(i) == BB) {
1704 BB->removePredecessor(PredBB);
1705 PredBBTI->setSuccessor(i, EdgeBB);
1706 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001707
Chris Lattner4088e2b2010-12-13 01:47:07 +00001708 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001709 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001710 }
Chris Lattner748f9032005-09-19 23:49:37 +00001711
1712 return false;
1713}
1714
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001715/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1716/// PHI node, see if we can eliminate it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001717static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001718 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1719 // statement", which has a very simple dominance structure. Basically, we
1720 // are trying to find the condition that is being branched on, which
1721 // subsequently causes this merge to happen. We really want control
1722 // dependence information for this check, but simplifycfg can't keep it up
1723 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001724 BasicBlock *BB = PN->getParent();
1725 BasicBlock *IfTrue, *IfFalse;
1726 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001727 if (!IfCond ||
1728 // Don't bother if the branch will be constant folded trivially.
1729 isa<ConstantInt>(IfCond))
1730 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001731
Chris Lattner95adf8f12006-11-18 19:19:36 +00001732 // Okay, we found that we can merge this two-entry phi node into a select.
1733 // Doing so would require us to fold *all* two entry phi nodes in this block.
1734 // At some point this becomes non-profitable (particularly if the target
1735 // doesn't support cmov's). Only do this transformation if there are two or
1736 // fewer PHI nodes in this block.
1737 unsigned NumPhis = 0;
1738 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1739 if (NumPhis > 2)
1740 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001741
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001742 // Loop over the PHI's seeing if we can promote them all to select
1743 // instructions. While we are at it, keep track of the instructions
1744 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001745 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001746 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1747 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001748
Chris Lattner7499b452010-12-14 08:46:09 +00001749 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1750 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001751 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001752 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001753 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001754 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001755 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001756
Peter Collingbournee3511e12011-04-29 18:47:31 +00001757 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001758 MaxCostVal0, DL) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001759 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001760 MaxCostVal1, DL))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001761 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001762 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001763
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001764 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001765 // we ran out of PHIs then we simplified them all.
1766 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001767 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001768
Chris Lattner7499b452010-12-14 08:46:09 +00001769 // Don't fold i1 branches on PHIs which contain binary operators. These can
1770 // often be turned into switches and other things.
1771 if (PN->getType()->isIntegerTy(1) &&
1772 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1773 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1774 isa<BinaryOperator>(IfCond)))
1775 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001776
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001777 // If we all PHI nodes are promotable, check to make sure that all
1778 // instructions in the predecessor blocks can be promoted as well. If
1779 // not, we won't be able to get rid of the control flow, so it's not
1780 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001781 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001782 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1783 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1784 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001785 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001786 } else {
1787 DomBlock = *pred_begin(IfBlock1);
1788 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001789 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001790 // This is not an aggressive instruction that we can promote.
1791 // Because of this, we won't be able to get rid of the control
1792 // flow, so the xform is not worth it.
1793 return false;
1794 }
1795 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001796
Chris Lattner9ac168d2010-12-14 07:41:39 +00001797 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001798 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001799 } else {
1800 DomBlock = *pred_begin(IfBlock2);
1801 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001802 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001803 // This is not an aggressive instruction that we can promote.
1804 // Because of this, we won't be able to get rid of the control
1805 // flow, so the xform is not worth it.
1806 return false;
1807 }
1808 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001809
Chris Lattner9fd838d2010-12-14 07:23:10 +00001810 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001811 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001812
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001813 // If we can still promote the PHI nodes after this gauntlet of tests,
1814 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001815 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001816 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001817
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001818 // Move all 'aggressive' instructions, which are defined in the
1819 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001820 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001821 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001822 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001823 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001824 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001825 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001826 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001827 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001828
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001829 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1830 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001831 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1832 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001833
1834 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001835 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001836 PN->replaceAllUsesWith(NV);
1837 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001838 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001839 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001840
Chris Lattner335f0e42010-12-14 08:01:53 +00001841 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1842 // has been flattened. Change DomBlock to jump directly to our new block to
1843 // avoid other simplifycfg's kicking in on the diamond.
1844 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001845 Builder.SetInsertPoint(OldTI);
1846 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001847 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001848 return true;
1849}
Chris Lattner748f9032005-09-19 23:49:37 +00001850
Chris Lattner86bbf332008-04-24 00:01:19 +00001851/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1852/// to two returning blocks, try to merge them together into one return,
1853/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001854static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001855 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001856 assert(BI->isConditional() && "Must be a conditional branch");
1857 BasicBlock *TrueSucc = BI->getSuccessor(0);
1858 BasicBlock *FalseSucc = BI->getSuccessor(1);
1859 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1860 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001861
Chris Lattner86bbf332008-04-24 00:01:19 +00001862 // Check to ensure both blocks are empty (just a return) or optionally empty
1863 // with PHI nodes. If there are other instructions, merging would cause extra
1864 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001865 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001866 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001867 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001868 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001869
Devang Pateldd14e0f2011-05-18 21:33:11 +00001870 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001871 // Okay, we found a branch that is going to two return nodes. If
1872 // there is no return value for this function, just change the
1873 // branch into a return.
1874 if (FalseRet->getNumOperands() == 0) {
1875 TrueSucc->removePredecessor(BI->getParent());
1876 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001877 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001878 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001879 return true;
1880 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001881
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001882 // Otherwise, figure out what the true and false return values are
1883 // so we can insert a new select instruction.
1884 Value *TrueValue = TrueRet->getReturnValue();
1885 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001886
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001887 // Unwrap any PHI nodes in the return blocks.
1888 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1889 if (TVPN->getParent() == TrueSucc)
1890 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1891 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1892 if (FVPN->getParent() == FalseSucc)
1893 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001894
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001895 // In order for this transformation to be safe, we must be able to
1896 // unconditionally execute both operands to the return. This is
1897 // normally the case, but we could have a potentially-trapping
1898 // constant expression that prevents this transformation from being
1899 // safe.
1900 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1901 if (TCV->canTrap())
1902 return false;
1903 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1904 if (FCV->canTrap())
1905 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001906
Chris Lattner86bbf332008-04-24 00:01:19 +00001907 // Okay, we collected all the mapped values and checked them for sanity, and
1908 // defined to really do this transformation. First, update the CFG.
1909 TrueSucc->removePredecessor(BI->getParent());
1910 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001911
Chris Lattner86bbf332008-04-24 00:01:19 +00001912 // Insert select instructions where needed.
1913 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001914 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001915 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001916 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1917 } else if (isa<UndefValue>(TrueValue)) {
1918 TrueValue = FalseValue;
1919 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001920 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1921 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001922 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001923 }
1924
Andrew Trickf3cf1932012-08-29 21:46:36 +00001925 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001926 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1927
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00001928 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001929
David Greene725c7c32010-01-05 01:26:52 +00001930 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00001931 << "\n " << *BI << "NewRet = " << *RI
1932 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001933
Eli Friedmancb61afb2008-12-16 20:54:32 +00001934 EraseTerminatorInstAndDCECond(BI);
1935
Chris Lattner86bbf332008-04-24 00:01:19 +00001936 return true;
1937}
1938
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001939/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1940/// probabilities of the branch taking each edge. Fills in the two APInt
1941/// parameters and return true, or returns false if no or invalid metadata was
1942/// found.
1943static bool ExtractBranchMetadata(BranchInst *BI,
Manman Renbfb9d432012-09-15 00:39:57 +00001944 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001945 assert(BI->isConditional() &&
1946 "Looking for probabilities on unconditional branch?");
1947 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky398255e2011-12-27 18:27:22 +00001948 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001949 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1950 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky398255e2011-12-27 18:27:22 +00001951 if (!CITrue || !CIFalse) return false;
Manman Renbfb9d432012-09-15 00:39:57 +00001952 ProbTrue = CITrue->getValue().getZExtValue();
1953 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001954 return true;
1955}
1956
Manman Rend33f4ef2012-06-13 05:43:29 +00001957/// checkCSEInPredecessor - Return true if the given instruction is available
1958/// in its predecessor block. If yes, the instruction will be removed.
1959///
Benjamin Kramerabbfe692012-07-13 13:25:15 +00001960static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00001961 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1962 return false;
1963 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1964 Instruction *PBI = &*I;
1965 // Check whether Inst and PBI generate the same value.
1966 if (Inst->isIdenticalTo(PBI)) {
1967 Inst->replaceAllUsesWith(PBI);
1968 Inst->eraseFromParent();
1969 return true;
1970 }
1971 }
1972 return false;
1973}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00001974
Chris Lattner7d4cdae2011-04-11 23:24:57 +00001975/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1976/// predecessor branches to us and one of our successors, fold the block into
1977/// the predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00001978bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
1979 unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001980 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00001981
Craig Topperf40110f2014-04-25 05:29:35 +00001982 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00001983 if (BI->isConditional())
1984 Cond = dyn_cast<Instruction>(BI->getCondition());
1985 else {
1986 // For unconditional branch, check for a simple CFG pattern, where
1987 // BB has a single predecessor and BB's successor is also its predecessor's
1988 // successor. If such pattern exisits, check for CSE between BB and its
1989 // predecessor.
1990 if (BasicBlock *PB = BB->getSinglePredecessor())
1991 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1992 if (PBI->isConditional() &&
1993 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1994 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1995 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1996 I != E; ) {
1997 Instruction *Curr = I++;
1998 if (isa<CmpInst>(Curr)) {
1999 Cond = Curr;
2000 break;
2001 }
2002 // Quit if we can't remove this instruction.
2003 if (!checkCSEInPredecessor(Curr, PB))
2004 return false;
2005 }
2006 }
2007
Craig Topperf40110f2014-04-25 05:29:35 +00002008 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002009 return false;
2010 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002011
Craig Topperf40110f2014-04-25 05:29:35 +00002012 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2013 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002014 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002015
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002016 // Make sure the instruction after the condition is the cond branch.
2017 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002018
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002019 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002020 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002021
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002022 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002023 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002024
Jingyue Wufc029672014-09-30 22:23:38 +00002025 // Only allow this transformation if computing the condition doesn't involve
2026 // too many instructions and these involved instructions can be executed
2027 // unconditionally. We denote all involved instructions except the condition
2028 // as "bonus instructions", and only allow this transformation when the
2029 // number of the bonus instructions does not exceed a certain threshold.
2030 unsigned NumBonusInsts = 0;
2031 for (auto I = BB->begin(); Cond != I; ++I) {
2032 // Ignore dbg intrinsics.
2033 if (isa<DbgInfoIntrinsic>(I))
2034 continue;
2035 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2036 return false;
2037 // I has only one use and can be executed unconditionally.
2038 Instruction *User = dyn_cast<Instruction>(I->user_back());
2039 if (User == nullptr || User->getParent() != BB)
2040 return false;
2041 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2042 // to use any other instruction, User must be an instruction between next(I)
2043 // and Cond.
2044 ++NumBonusInsts;
2045 // Early exits once we reach the limit.
2046 if (NumBonusInsts > BonusInstThreshold)
2047 return false;
2048 }
2049
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002050 // Cond is known to be a compare or binary operator. Check to make sure that
2051 // neither operand is a potentially-trapping constant expression.
2052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2053 if (CE->canTrap())
2054 return false;
2055 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2056 if (CE->canTrap())
2057 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002058
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002059 // Finally, don't infinitely unroll conditional loops.
2060 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002061 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002062 if (TrueDest == BB || FalseDest == BB)
2063 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002064
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002065 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2066 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002067 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002068
Chris Lattner80b03a12008-07-13 22:23:11 +00002069 // Check that we have two conditional branches. If there is a PHI node in
2070 // the common successor, verify that the same value flows in from both
2071 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002072 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002073 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002074 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002075 !SafeToMergeTerminators(BI, PBI)) ||
2076 (!BI->isConditional() &&
2077 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002078 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002079
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002080 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002081 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002082 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002083
Manman Rend33f4ef2012-06-13 05:43:29 +00002084 if (BI->isConditional()) {
2085 if (PBI->getSuccessor(0) == TrueDest)
2086 Opc = Instruction::Or;
2087 else if (PBI->getSuccessor(1) == FalseDest)
2088 Opc = Instruction::And;
2089 else if (PBI->getSuccessor(0) == FalseDest)
2090 Opc = Instruction::And, InvertPredCond = true;
2091 else if (PBI->getSuccessor(1) == TrueDest)
2092 Opc = Instruction::Or, InvertPredCond = true;
2093 else
2094 continue;
2095 } else {
2096 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2097 continue;
2098 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002099
David Greene725c7c32010-01-05 01:26:52 +00002100 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002101 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002102
Chris Lattner55eaae12008-07-13 21:20:19 +00002103 // If we need to invert the condition in the pred block to match, do so now.
2104 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002105 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002106
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002107 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2108 CmpInst *CI = cast<CmpInst>(NewCond);
2109 CI->setPredicate(CI->getInversePredicate());
2110 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002111 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002112 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002113 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002114
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002115 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002116 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002117 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002118
Jingyue Wufc029672014-09-30 22:23:38 +00002119 // If we have bonus instructions, clone them into the predecessor block.
2120 // Note that there may be mutliple predecessor blocks, so we cannot move
2121 // bonus instructions to a predecessor block.
2122 ValueToValueMapTy VMap; // maps original values to cloned values
2123 // We already make sure Cond is the last instruction before BI. Therefore,
2124 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2125 // instructions.
2126 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2127 if (isa<DbgInfoIntrinsic>(BonusInst))
2128 continue;
2129 Instruction *NewBonusInst = BonusInst->clone();
2130 RemapInstruction(NewBonusInst, VMap,
2131 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2132 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002133
2134 // If we moved a load, we cannot any longer claim any knowledge about
2135 // its potential value. The previous information might have been valid
2136 // only given the branch precondition.
2137 // For an analogous reason, we must also drop all the metadata whose
2138 // semantics we don't understand.
Jingyue Wufc029672014-09-30 22:23:38 +00002139 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
Rafael Espindolaab73c492014-01-28 16:56:46 +00002140
Jingyue Wufc029672014-09-30 22:23:38 +00002141 PredBlock->getInstList().insert(PBI, NewBonusInst);
2142 NewBonusInst->takeName(BonusInst);
2143 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002144 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002145
Chris Lattner55eaae12008-07-13 21:20:19 +00002146 // Clone Cond into the predecessor basic block, and or/and the
2147 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002148 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002149 RemapInstruction(New, VMap,
2150 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002151 PredBlock->getInstList().insert(PBI, New);
2152 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002153 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002154
Manman Rend33f4ef2012-06-13 05:43:29 +00002155 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002156 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002157 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002158 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002159 PBI->setCondition(NewCond);
2160
Manman Renbfb9d432012-09-15 00:39:57 +00002161 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2162 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2163 PredFalseWeight);
2164 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2165 SuccFalseWeight);
2166 SmallVector<uint64_t, 8> NewWeights;
2167
Manman Rend33f4ef2012-06-13 05:43:29 +00002168 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002169 if (PredHasWeights && SuccHasWeights) {
2170 // PBI: br i1 %x, BB, FalseDest
2171 // BI: br i1 %y, TrueDest, FalseDest
2172 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2173 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2174 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2175 // TrueWeight for PBI * FalseWeight for BI.
2176 // We assume that total weights of a BranchInst can fit into 32 bits.
2177 // Therefore, we will not have overflow using 64-bit arithmetic.
2178 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2179 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2180 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002181 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2182 PBI->setSuccessor(0, TrueDest);
2183 }
2184 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002185 if (PredHasWeights && SuccHasWeights) {
2186 // PBI: br i1 %x, TrueDest, BB
2187 // BI: br i1 %y, TrueDest, FalseDest
2188 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2189 // FalseWeight for PBI * TrueWeight for BI.
2190 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2191 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2192 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2193 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2194 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002195 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2196 PBI->setSuccessor(1, FalseDest);
2197 }
Manman Renbfb9d432012-09-15 00:39:57 +00002198 if (NewWeights.size() == 2) {
2199 // Halve the weights if any of them cannot fit in an uint32_t
2200 FitWeights(NewWeights);
2201
2202 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2203 PBI->setMetadata(LLVMContext::MD_prof,
2204 MDBuilder(BI->getContext()).
2205 createBranchWeights(MDWeights));
2206 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002207 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002208 } else {
2209 // Update PHI nodes in the common successors.
2210 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002211 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002212 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2213 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002214 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002215 if (PBI->getSuccessor(0) == TrueDest) {
2216 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2217 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2218 // is false: !PBI_Cond and BI_Value
2219 Instruction *NotCond =
2220 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2221 "not.cond"));
2222 MergedCond =
2223 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2224 NotCond, New,
2225 "and.cond"));
2226 if (PBI_C->isOne())
2227 MergedCond =
2228 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2229 PBI->getCondition(), MergedCond,
2230 "or.cond"));
2231 } else {
2232 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2233 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2234 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002235 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002236 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2237 PBI->getCondition(), New,
2238 "and.cond"));
2239 if (PBI_C->isOne()) {
2240 Instruction *NotCond =
2241 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2242 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002243 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002244 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2245 NotCond, MergedCond,
2246 "or.cond"));
2247 }
2248 }
2249 // Update PHI Node.
2250 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2251 MergedCond);
2252 }
2253 // Change PBI from Conditional to Unconditional.
2254 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2255 EraseTerminatorInstAndDCECond(PBI);
2256 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002257 }
Devang Pateld715ec82011-04-06 22:37:20 +00002258
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002259 // TODO: If BB is reachable from all paths through PredBlock, then we
2260 // could replace PBI's branch probabilities with BI's.
2261
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002262 // Copy any debug value intrinsics into the end of PredBlock.
2263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2264 if (isa<DbgInfoIntrinsic>(*I))
2265 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002266
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002267 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002268 }
2269 return false;
2270}
2271
Chris Lattner9aada1d2008-07-13 21:53:26 +00002272/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2273/// predecessor of another block, this function tries to simplify it. We know
2274/// that PBI and BI are both conditional branches, and BI is in one of the
2275/// successor blocks of PBI - PBI branches to BI.
2276static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2277 assert(PBI->isConditional() && BI->isConditional());
2278 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002279
Chris Lattner9aada1d2008-07-13 21:53:26 +00002280 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002281 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002282 // this conditional branch redundant.
2283 if (PBI->getCondition() == BI->getCondition() &&
2284 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2285 // Okay, the outcome of this conditional branch is statically
2286 // knowable. If this block had a single pred, handle specially.
2287 if (BB->getSinglePredecessor()) {
2288 // Turn this into a branch on constant.
2289 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002290 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002291 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002292 return true; // Nuke the branch on constant.
2293 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002294
Chris Lattner9aada1d2008-07-13 21:53:26 +00002295 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2296 // in the constant and simplify the block result. Subsequent passes of
2297 // simplifycfg will thread the block.
2298 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002299 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002300 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002301 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002302 BI->getCondition()->getName() + ".pr",
2303 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002304 // Okay, we're going to insert the PHI node. Since PBI is not the only
2305 // predecessor, compute the PHI'd conditional value for all of the preds.
2306 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002307 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002308 BasicBlock *P = *PI;
2309 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002310 PBI != BI && PBI->isConditional() &&
2311 PBI->getCondition() == BI->getCondition() &&
2312 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2313 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002314 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002315 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002316 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002317 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002318 }
Gabor Greif8629f122010-07-12 10:59:23 +00002319 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002320
Chris Lattner9aada1d2008-07-13 21:53:26 +00002321 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002322 return true;
2323 }
2324 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002325
Chris Lattner9aada1d2008-07-13 21:53:26 +00002326 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002327 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002328 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002329 BasicBlock::iterator BBI = BB->begin();
2330 // Ignore dbg intrinsics.
2331 while (isa<DbgInfoIntrinsic>(BBI))
2332 ++BBI;
2333 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002334 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002335
Andrew Trickf3cf1932012-08-29 21:46:36 +00002336
Chris Lattnerc59945b2009-01-20 01:15:41 +00002337 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2338 if (CE->canTrap())
2339 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002340
Chris Lattner834ab4e2008-07-13 22:04:41 +00002341 int PBIOp, BIOp;
2342 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2343 PBIOp = BIOp = 0;
2344 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2345 PBIOp = 0, BIOp = 1;
2346 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2347 PBIOp = 1, BIOp = 0;
2348 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2349 PBIOp = BIOp = 1;
2350 else
2351 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002352
Chris Lattner834ab4e2008-07-13 22:04:41 +00002353 // Check to make sure that the other destination of this branch
2354 // isn't BB itself. If so, this is an infinite loop that will
2355 // keep getting unwound.
2356 if (PBI->getSuccessor(PBIOp) == BB)
2357 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002358
2359 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002360 // insertion of a large number of select instructions. For targets
2361 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002362
Sanjay Patela932da82014-07-07 21:19:00 +00002363 // Also do not perform this transformation if any phi node in the common
2364 // destination block can trap when reached by BB or PBB (PR17073). In that
2365 // case, it would be unsafe to hoist the operation into a select instruction.
2366
2367 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002368 unsigned NumPhis = 0;
2369 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002370 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002371 if (NumPhis > 2) // Disable this xform.
2372 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002373
Sanjay Patela932da82014-07-07 21:19:00 +00002374 PHINode *PN = cast<PHINode>(II);
2375 Value *BIV = PN->getIncomingValueForBlock(BB);
2376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2377 if (CE->canTrap())
2378 return false;
2379
2380 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2381 Value *PBIV = PN->getIncomingValue(PBBIdx);
2382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2383 if (CE->canTrap())
2384 return false;
2385 }
2386
Chris Lattner834ab4e2008-07-13 22:04:41 +00002387 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002388 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002389
David Greene725c7c32010-01-05 01:26:52 +00002390 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002391 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002392
2393
Chris Lattner80b03a12008-07-13 22:23:11 +00002394 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2395 // branch in it, where one edge (OtherDest) goes back to itself but the other
2396 // exits. We don't *know* that the program avoids the infinite loop
2397 // (even though that seems likely). If we do this xform naively, we'll end up
2398 // recursively unpeeling the loop. Since we know that (after the xform is
2399 // done) that the block *is* infinite if reached, we just make it an obviously
2400 // infinite loop with no cond branch.
2401 if (OtherDest == BB) {
2402 // Insert it at the end of the function, because it's either code,
2403 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002404 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2405 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002406 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2407 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002408 }
2409
David Greene725c7c32010-01-05 01:26:52 +00002410 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002411
Chris Lattner834ab4e2008-07-13 22:04:41 +00002412 // BI may have other predecessors. Because of this, we leave
2413 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002414
Chris Lattner834ab4e2008-07-13 22:04:41 +00002415 // Make sure we get to CommonDest on True&True directions.
2416 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002417 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002418 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002419 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2420
Chris Lattner834ab4e2008-07-13 22:04:41 +00002421 Value *BICond = BI->getCondition();
2422 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002423 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2424
Chris Lattner834ab4e2008-07-13 22:04:41 +00002425 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002426 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002427
Chris Lattner834ab4e2008-07-13 22:04:41 +00002428 // Modify PBI to branch on the new condition to the new dests.
2429 PBI->setCondition(Cond);
2430 PBI->setSuccessor(0, CommonDest);
2431 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002432
Manman Ren2d4c10f2012-09-17 21:30:40 +00002433 // Update branch weight for PBI.
2434 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2435 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2436 PredFalseWeight);
2437 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2438 SuccFalseWeight);
2439 if (PredHasWeights && SuccHasWeights) {
2440 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2441 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2442 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2443 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2444 // The weight to CommonDest should be PredCommon * SuccTotal +
2445 // PredOther * SuccCommon.
2446 // The weight to OtherDest should be PredOther * SuccOther.
2447 SmallVector<uint64_t, 2> NewWeights;
2448 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2449 PredOther * SuccCommon);
2450 NewWeights.push_back(PredOther * SuccOther);
2451 // Halve the weights if any of them cannot fit in an uint32_t
2452 FitWeights(NewWeights);
2453
2454 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2455 PBI->setMetadata(LLVMContext::MD_prof,
2456 MDBuilder(BI->getContext()).
2457 createBranchWeights(MDWeights));
2458 }
2459
Chris Lattner834ab4e2008-07-13 22:04:41 +00002460 // OtherDest may have phi nodes. If so, add an entry from PBI's
2461 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002462 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002463
Chris Lattner834ab4e2008-07-13 22:04:41 +00002464 // We know that the CommonDest already had an edge from PBI to
2465 // it. If it has PHIs though, the PHIs may have different
2466 // entries for BB and PBI's BB. If so, insert a select to make
2467 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002468 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002469 for (BasicBlock::iterator II = CommonDest->begin();
2470 (PN = dyn_cast<PHINode>(II)); ++II) {
2471 Value *BIV = PN->getIncomingValueForBlock(BB);
2472 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2473 Value *PBIV = PN->getIncomingValue(PBBIdx);
2474 if (BIV != PBIV) {
2475 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002476 Value *NV = cast<SelectInst>
2477 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002478 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002479 }
2480 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002481
David Greene725c7c32010-01-05 01:26:52 +00002482 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2483 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002484
Chris Lattner834ab4e2008-07-13 22:04:41 +00002485 // This basic block is probably dead. We know it has at least
2486 // one fewer predecessor.
2487 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002488}
2489
Frits van Bommel8e158492011-01-11 12:52:11 +00002490// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2491// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2492// Takes care of updating the successors and removing the old terminator.
2493// Also makes sure not to introduce new successors by assuming that edges to
2494// non-successor TrueBBs and FalseBBs aren't reachable.
2495static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002496 BasicBlock *TrueBB, BasicBlock *FalseBB,
2497 uint32_t TrueWeight,
2498 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002499 // Remove any superfluous successor edges from the CFG.
2500 // First, figure out which successors to preserve.
2501 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2502 // successor.
2503 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002504 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002505
2506 // Then remove the rest.
2507 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2508 BasicBlock *Succ = OldTerm->getSuccessor(I);
2509 // Make sure only to keep exactly one copy of each edge.
2510 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002511 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002512 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002513 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002514 else
2515 Succ->removePredecessor(OldTerm->getParent());
2516 }
2517
Devang Patel2c2ea222011-05-18 18:43:31 +00002518 IRBuilder<> Builder(OldTerm);
2519 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2520
Frits van Bommel8e158492011-01-11 12:52:11 +00002521 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002522 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002523 if (TrueBB == FalseBB)
2524 // We were only looking for one successor, and it was present.
2525 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002526 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002527 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002528 // We found both of the successors we were looking for.
2529 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002530 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2531 if (TrueWeight != FalseWeight)
2532 NewBI->setMetadata(LLVMContext::MD_prof,
2533 MDBuilder(OldTerm->getContext()).
2534 createBranchWeights(TrueWeight, FalseWeight));
2535 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002536 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2537 // Neither of the selected blocks were successors, so this
2538 // terminator must be unreachable.
2539 new UnreachableInst(OldTerm->getContext(), OldTerm);
2540 } else {
2541 // One of the selected values was a successor, but the other wasn't.
2542 // Insert an unconditional branch to the one that was found;
2543 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002544 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002545 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002546 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002547 else
2548 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002549 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002550 }
2551
2552 EraseTerminatorInstAndDCECond(OldTerm);
2553 return true;
2554}
2555
Frits van Bommel8ae07992011-02-28 09:44:07 +00002556// SimplifySwitchOnSelect - Replaces
2557// (switch (select cond, X, Y)) on constant X, Y
2558// with a branch - conditional if X and Y lead to distinct BBs,
2559// unconditional otherwise.
2560static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2561 // Check for constant integer values in the select.
2562 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2563 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2564 if (!TrueVal || !FalseVal)
2565 return false;
2566
2567 // Find the relevant condition and destinations.
2568 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002569 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2570 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002571
Manman Ren774246a2012-09-17 22:28:55 +00002572 // Get weight for TrueBB and FalseBB.
2573 uint32_t TrueWeight = 0, FalseWeight = 0;
2574 SmallVector<uint64_t, 8> Weights;
2575 bool HasWeights = HasBranchWeights(SI);
2576 if (HasWeights) {
2577 GetBranchWeights(SI, Weights);
2578 if (Weights.size() == 1 + SI->getNumCases()) {
2579 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2580 getSuccessorIndex()];
2581 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2582 getSuccessorIndex()];
2583 }
2584 }
2585
Frits van Bommel8ae07992011-02-28 09:44:07 +00002586 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002587 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2588 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002589}
2590
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002591// SimplifyIndirectBrOnSelect - Replaces
2592// (indirectbr (select cond, blockaddress(@fn, BlockA),
2593// blockaddress(@fn, BlockB)))
2594// with
2595// (br cond, BlockA, BlockB).
2596static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2597 // Check that both operands of the select are block addresses.
2598 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2599 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2600 if (!TBA || !FBA)
2601 return false;
2602
2603 // Extract the actual blocks.
2604 BasicBlock *TrueBB = TBA->getBasicBlock();
2605 BasicBlock *FalseBB = FBA->getBasicBlock();
2606
Frits van Bommel8e158492011-01-11 12:52:11 +00002607 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002608 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2609 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002610}
2611
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002612/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2613/// instruction (a seteq/setne with a constant) as the only instruction in a
2614/// block that ends with an uncond branch. We are looking for a very specific
2615/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2616/// this case, we merge the first two "or's of icmp" into a switch, but then the
2617/// default value goes to an uncond block with a seteq in it, we get something
2618/// like:
2619///
2620/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2621/// DEFAULT:
2622/// %tmp = icmp eq i8 %A, 92
2623/// br label %end
2624/// end:
2625/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002626///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002627/// We prefer to split the edge to 'end' so that there is a true/false entry to
2628/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002629static bool TryToSimplifyUncondBranchWithICmpInIt(
2630 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00002631 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002632 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002633
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002634 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2635 // complex.
2636 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2637
2638 Value *V = ICI->getOperand(0);
2639 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002640
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002641 // The pattern we're looking for is where our only predecessor is a switch on
2642 // 'V' and this block is the default case for the switch. In this case we can
2643 // fold the compared value into the switch to simplify things.
2644 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002645 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002646
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002647 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2648 if (SI->getCondition() != V)
2649 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002650
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002651 // If BB is reachable on a non-default case, then we simply know the value of
2652 // V in this block. Substitute it and constant fold the icmp instruction
2653 // away.
2654 if (SI->getDefaultDest() != BB) {
2655 ConstantInt *VVal = SI->findCaseDest(BB);
2656 assert(VVal && "Should have a unique destination value");
2657 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002658
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002659 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002660 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002661 ICI->eraseFromParent();
2662 }
2663 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002664 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002665 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002666
Chris Lattner62cc76e2010-12-13 03:43:57 +00002667 // Ok, the block is reachable from the default dest. If the constant we're
2668 // comparing exists in one of the other edges, then we can constant fold ICI
2669 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002670 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002671 Value *V;
2672 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2673 V = ConstantInt::getFalse(BB->getContext());
2674 else
2675 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002676
Chris Lattner62cc76e2010-12-13 03:43:57 +00002677 ICI->replaceAllUsesWith(V);
2678 ICI->eraseFromParent();
2679 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002680 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002681 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002682
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002683 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2684 // the block.
2685 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002686 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002687 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002688 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2689 return false;
2690
2691 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2692 // true in the PHI.
2693 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2694 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2695
2696 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2697 std::swap(DefaultCst, NewCst);
2698
2699 // Replace ICI (which is used by the PHI for the default value) with true or
2700 // false depending on if it is EQ or NE.
2701 ICI->replaceAllUsesWith(DefaultCst);
2702 ICI->eraseFromParent();
2703
2704 // Okay, the switch goes to this block on a default value. Add an edge from
2705 // the switch to the merge point on the compared value.
2706 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2707 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002708 SmallVector<uint64_t, 8> Weights;
2709 bool HasWeights = HasBranchWeights(SI);
2710 if (HasWeights) {
2711 GetBranchWeights(SI, Weights);
2712 if (Weights.size() == 1 + SI->getNumCases()) {
2713 // Split weight for default case to case for "Cst".
2714 Weights[0] = (Weights[0]+1) >> 1;
2715 Weights.push_back(Weights[0]);
2716
2717 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2718 SI->setMetadata(LLVMContext::MD_prof,
2719 MDBuilder(SI->getContext()).
2720 createBranchWeights(MDWeights));
2721 }
2722 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002723 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002724
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002725 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002726 Builder.SetInsertPoint(NewBB);
2727 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2728 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002729 PHIUse->addIncoming(NewCst, NewBB);
2730 return true;
2731}
2732
Chris Lattnera69c4432010-12-13 05:03:41 +00002733/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2734/// Check to see if it is branching on an or/and chain of icmp instructions, and
2735/// fold it into a switch instruction if so.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002736static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
Devang Patel7de6c4b2011-05-18 23:18:47 +00002737 IRBuilder<> &Builder) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002738 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002739 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002740
2741
Chris Lattnera69c4432010-12-13 05:03:41 +00002742 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2743 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2744 // 'setne's and'ed together, collect them.
Craig Topperf40110f2014-04-25 05:29:35 +00002745 Value *CompVal = nullptr;
Chris Lattnera69c4432010-12-13 05:03:41 +00002746 std::vector<ConstantInt*> Values;
2747 bool TrueWhenEqual = true;
Craig Topperf40110f2014-04-25 05:29:35 +00002748 Value *ExtraCase = nullptr;
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002749 unsigned UsedICmps = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002750
Chris Lattnera69c4432010-12-13 05:03:41 +00002751 if (Cond->getOpcode() == Instruction::Or) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002752 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002753 UsedICmps);
Chris Lattnera69c4432010-12-13 05:03:41 +00002754 } else if (Cond->getOpcode() == Instruction::And) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002755 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002756 UsedICmps);
Chris Lattnera69c4432010-12-13 05:03:41 +00002757 TrueWhenEqual = false;
2758 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002759
Chris Lattnera69c4432010-12-13 05:03:41 +00002760 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002761 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002762
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002763 // Avoid turning single icmps into a switch.
2764 if (UsedICmps <= 1)
2765 return false;
2766
Chris Lattnera69c4432010-12-13 05:03:41 +00002767 // There might be duplicate constants in the list, which the switch
2768 // instruction can't handle, remove them now.
2769 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2770 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002771
Chris Lattnera69c4432010-12-13 05:03:41 +00002772 // If Extra was used, we require at least two switch values to do the
2773 // transformation. A switch with one value is just an cond branch.
2774 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002775
Andrew Trick3051aa12012-08-29 21:46:38 +00002776 // TODO: Preserve branch weight metadata, similarly to how
2777 // FoldValueComparisonIntoPredecessors preserves it.
2778
Chris Lattnera69c4432010-12-13 05:03:41 +00002779 // Figure out which block is which destination.
2780 BasicBlock *DefaultBB = BI->getSuccessor(1);
2781 BasicBlock *EdgeBB = BI->getSuccessor(0);
2782 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002783
Chris Lattnera69c4432010-12-13 05:03:41 +00002784 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002785
Chris Lattnerd7beca32010-12-14 06:17:25 +00002786 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002787 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002788
Chris Lattnera69c4432010-12-13 05:03:41 +00002789 // If there are any extra values that couldn't be folded into the switch
2790 // then we evaluate them with an explicit branch first. Split the block
2791 // right before the condbr to handle it.
2792 if (ExtraCase) {
2793 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2794 // Remove the uncond branch added to the old block.
2795 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002796 Builder.SetInsertPoint(OldTI);
2797
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002798 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002799 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002800 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002801 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002802
Chris Lattnera69c4432010-12-13 05:03:41 +00002803 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002804
Chris Lattnercb570f82010-12-13 05:34:18 +00002805 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2806 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002807 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002808
Chris Lattnerd7beca32010-12-14 06:17:25 +00002809 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2810 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002811 BB = NewBB;
2812 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002813
2814 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002815 // Convert pointer to int before we switch.
2816 if (CompVal->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002817 assert(DL && "Cannot switch on pointer without DataLayout");
Devang Patel7de6c4b2011-05-18 23:18:47 +00002818 CompVal = Builder.CreatePtrToInt(CompVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002819 DL->getIntPtrType(CompVal->getType()),
Devang Patel7de6c4b2011-05-18 23:18:47 +00002820 "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002821 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002822
Chris Lattnera69c4432010-12-13 05:03:41 +00002823 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002824 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002825
Chris Lattnera69c4432010-12-13 05:03:41 +00002826 // Add all of the 'cases' to the switch instruction.
2827 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2828 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002829
Chris Lattnera69c4432010-12-13 05:03:41 +00002830 // We added edges from PI to the EdgeBB. As such, if there were any
2831 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2832 // the number of edges added.
2833 for (BasicBlock::iterator BBI = EdgeBB->begin();
2834 isa<PHINode>(BBI); ++BBI) {
2835 PHINode *PN = cast<PHINode>(BBI);
2836 Value *InVal = PN->getIncomingValueForBlock(BB);
2837 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2838 PN->addIncoming(InVal, BB);
2839 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002840
Chris Lattnera69c4432010-12-13 05:03:41 +00002841 // Erase the old branch instruction.
2842 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002843
Chris Lattnerd7beca32010-12-14 06:17:25 +00002844 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002845 return true;
2846}
2847
Duncan Sands29192d02011-09-05 12:57:57 +00002848bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2849 // If this is a trivial landing pad that just continues unwinding the caught
2850 // exception then zap the landing pad, turning its invokes into calls.
2851 BasicBlock *BB = RI->getParent();
2852 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2853 if (RI->getValue() != LPInst)
2854 // Not a landing pad, or the resume is not unwinding the exception that
2855 // caused control to branch here.
2856 return false;
2857
2858 // Check that there are no other instructions except for debug intrinsics.
2859 BasicBlock::iterator I = LPInst, E = RI;
2860 while (++I != E)
2861 if (!isa<DbgInfoIntrinsic>(I))
2862 return false;
2863
2864 // Turn all invokes that unwind here into calls and delete the basic block.
Bill Wendling9534d882013-03-11 20:53:00 +00002865 bool InvokeRequiresTableEntry = false;
2866 bool Changed = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002867 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2868 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Bill Wendling9534d882013-03-11 20:53:00 +00002869
2870 if (II->hasFnAttr(Attribute::UWTable)) {
2871 // Don't remove an `invoke' instruction if the ABI requires an entry into
2872 // the table.
2873 InvokeRequiresTableEntry = true;
2874 continue;
2875 }
2876
Duncan Sands29192d02011-09-05 12:57:57 +00002877 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
Bill Wendling9534d882013-03-11 20:53:00 +00002878
Duncan Sands29192d02011-09-05 12:57:57 +00002879 // Insert a call instruction before the invoke.
2880 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2881 Call->takeName(II);
2882 Call->setCallingConv(II->getCallingConv());
2883 Call->setAttributes(II->getAttributes());
2884 Call->setDebugLoc(II->getDebugLoc());
2885
2886 // Anything that used the value produced by the invoke instruction now uses
2887 // the value produced by the call instruction. Note that we do this even
2888 // for void functions and calls with no uses so that the callgraph edge is
2889 // updated.
2890 II->replaceAllUsesWith(Call);
2891 BB->removePredecessor(II->getParent());
2892
2893 // Insert a branch to the normal destination right before the invoke.
2894 BranchInst::Create(II->getNormalDest(), II);
2895
2896 // Finally, delete the invoke instruction!
2897 II->eraseFromParent();
Bill Wendling9534d882013-03-11 20:53:00 +00002898 Changed = true;
Duncan Sands29192d02011-09-05 12:57:57 +00002899 }
2900
Bill Wendling9534d882013-03-11 20:53:00 +00002901 if (!InvokeRequiresTableEntry)
2902 // The landingpad is now unreachable. Zap it.
2903 BB->eraseFromParent();
2904
2905 return Changed;
Duncan Sands29192d02011-09-05 12:57:57 +00002906}
2907
Devang Pateldd14e0f2011-05-18 21:33:11 +00002908bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002909 BasicBlock *BB = RI->getParent();
2910 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002911
Chris Lattner25c3af32010-12-13 06:25:44 +00002912 // Find predecessors that end with branches.
2913 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2914 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002915 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2916 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00002917 TerminatorInst *PTI = P->getTerminator();
2918 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2919 if (BI->isUnconditional())
2920 UncondBranchPreds.push_back(P);
2921 else
2922 CondBranchPreds.push_back(BI);
2923 }
2924 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002925
Chris Lattner25c3af32010-12-13 06:25:44 +00002926 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00002927 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002928 while (!UncondBranchPreds.empty()) {
2929 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2930 DEBUG(dbgs() << "FOLDING: " << *BB
2931 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00002932 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00002933 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002934
Chris Lattner25c3af32010-12-13 06:25:44 +00002935 // If we eliminated all predecessors of the block, delete the block now.
2936 if (pred_begin(BB) == pred_end(BB))
2937 // We know there are no successors, so just nuke the block.
2938 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002939
Chris Lattner25c3af32010-12-13 06:25:44 +00002940 return true;
2941 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002942
Chris Lattner25c3af32010-12-13 06:25:44 +00002943 // Check out all of the conditional branches going to this return
2944 // instruction. If any of them just select between returns, change the
2945 // branch itself into a select/return pair.
2946 while (!CondBranchPreds.empty()) {
2947 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002948
Chris Lattner25c3af32010-12-13 06:25:44 +00002949 // Check to see if the non-BB successor is also a return block.
2950 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2951 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00002952 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00002953 return true;
2954 }
2955 return false;
2956}
2957
Chris Lattner25c3af32010-12-13 06:25:44 +00002958bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2959 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002960
Chris Lattner25c3af32010-12-13 06:25:44 +00002961 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002962
Chris Lattner25c3af32010-12-13 06:25:44 +00002963 // If there are any instructions immediately before the unreachable that can
2964 // be removed, do so.
2965 while (UI != BB->begin()) {
2966 BasicBlock::iterator BBI = UI;
2967 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002968 // Do not delete instructions that can have side effects which might cause
2969 // the unreachable to not be reachable; specifically, calls and volatile
2970 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00002971 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002972
2973 if (BBI->mayHaveSideEffects()) {
2974 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2975 if (SI->isVolatile())
2976 break;
2977 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2978 if (LI->isVolatile())
2979 break;
2980 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2981 if (RMWI->isVolatile())
2982 break;
2983 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2984 if (CXI->isVolatile())
2985 break;
2986 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2987 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002988 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002989 }
Bill Wendling55d875f2011-08-16 20:41:17 +00002990 // Note that deleting LandingPad's here is in fact okay, although it
2991 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2992 // all the predecessors of this block will be the unwind edges of Invokes,
2993 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002994 }
2995
Eli Friedmanaac35b32011-03-09 00:48:33 +00002996 // Delete this instruction (any uses are guaranteed to be dead)
2997 if (!BBI->use_empty())
2998 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00002999 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003000 Changed = true;
3001 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003002
Chris Lattner25c3af32010-12-13 06:25:44 +00003003 // If the unreachable instruction is the first in the block, take a gander
3004 // at all of the predecessors of this instruction, and simplify them.
3005 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003006
Chris Lattner25c3af32010-12-13 06:25:44 +00003007 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3008 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3009 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003010 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003011 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3012 if (BI->isUnconditional()) {
3013 if (BI->getSuccessor(0) == BB) {
3014 new UnreachableInst(TI->getContext(), TI);
3015 TI->eraseFromParent();
3016 Changed = true;
3017 }
3018 } else {
3019 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003020 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003021 EraseTerminatorInstAndDCECond(BI);
3022 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003023 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003024 EraseTerminatorInstAndDCECond(BI);
3025 Changed = true;
3026 }
3027 }
3028 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003029 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003030 i != e; ++i)
3031 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003032 BB->removePredecessor(SI->getParent());
3033 SI->removeCase(i);
3034 --i; --e;
3035 Changed = true;
3036 }
3037 // If the default value is unreachable, figure out the most popular
3038 // destination and make it the default.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003039 if (SI->getDefaultDest() == BB) {
Eli Friedmanc4414c62011-03-15 02:23:35 +00003040 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003041 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003042 i != e; ++i) {
Nick Lewyckye87d54c2011-12-26 20:37:40 +00003043 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003044 Popularity[i.getCaseSuccessor()];
Eli Friedmanc4414c62011-03-15 02:23:35 +00003045 if (entry.first == 0) {
3046 entry.first = 1;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003047 entry.second = i.getCaseIndex();
Eli Friedmanc4414c62011-03-15 02:23:35 +00003048 } else {
3049 entry.first++;
3050 }
3051 }
3052
Chris Lattner25c3af32010-12-13 06:25:44 +00003053 // Find the most popular block.
3054 unsigned MaxPop = 0;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003055 unsigned MaxIndex = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003056 BasicBlock *MaxBlock = nullptr;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003057 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner25c3af32010-12-13 06:25:44 +00003058 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00003059 if (I->second.first > MaxPop ||
Eli Friedmanc4414c62011-03-15 02:23:35 +00003060 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3061 MaxPop = I->second.first;
3062 MaxIndex = I->second.second;
Chris Lattner25c3af32010-12-13 06:25:44 +00003063 MaxBlock = I->first;
3064 }
3065 }
3066 if (MaxBlock) {
3067 // Make this the new default, allowing us to delete any explicit
3068 // edges to it.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003069 SI->setDefaultDest(MaxBlock);
Chris Lattner25c3af32010-12-13 06:25:44 +00003070 Changed = true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003071
Chris Lattner25c3af32010-12-13 06:25:44 +00003072 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3073 // it.
3074 if (isa<PHINode>(MaxBlock->begin()))
3075 for (unsigned i = 0; i != MaxPop-1; ++i)
3076 MaxBlock->removePredecessor(SI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003077
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003078 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003079 i != e; ++i)
3080 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003081 SI->removeCase(i);
3082 --i; --e;
3083 }
3084 }
3085 }
3086 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3087 if (II->getUnwindDest() == BB) {
3088 // Convert the invoke to a call instruction. This would be a good
3089 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003090 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003091 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003092
Chris Lattner25c3af32010-12-13 06:25:44 +00003093 // Insert the call now...
3094 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003095 Builder.SetInsertPoint(BI);
3096 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003097 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003098 CI->setCallingConv(II->getCallingConv());
3099 CI->setAttributes(II->getAttributes());
3100 // If the invoke produced a value, the call does now instead.
3101 II->replaceAllUsesWith(CI);
3102 delete II;
3103 Changed = true;
3104 }
3105 }
3106 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003107
Chris Lattner25c3af32010-12-13 06:25:44 +00003108 // If this block is now dead, remove it.
3109 if (pred_begin(BB) == pred_end(BB) &&
3110 BB != &BB->getParent()->getEntryBlock()) {
3111 // We know there are no successors, so just nuke the block.
3112 BB->eraseFromParent();
3113 return true;
3114 }
3115
3116 return Changed;
3117}
3118
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003119/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3120/// integer range comparison into a sub, an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003121static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003122 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003123
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003124 // Make sure all cases point to the same destination and gather the values.
3125 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003126 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003127 Cases.push_back(I.getCaseValue());
3128 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003129 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003130 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003131 return false;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003132 Cases.push_back(I.getCaseValue());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003133 }
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003134 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003135
3136 // Sort the case values, then check if they form a range we can transform.
3137 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3138 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3139 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3140 return false;
3141 }
3142
3143 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003144 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003145
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003146 Value *Sub = SI->getCondition();
3147 if (!Offset->isNullValue())
Devang Patel3015a542011-05-19 00:13:33 +00003148 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003149 Value *Cmp;
3150 // If NumCases overflowed, then all possible values jump to the successor.
3151 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3152 Cmp = ConstantInt::getTrue(SI->getContext());
3153 else
3154 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren56575552012-09-18 00:47:33 +00003155 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003156 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003157
Manman Ren56575552012-09-18 00:47:33 +00003158 // Update weight for the newly-created conditional branch.
3159 SmallVector<uint64_t, 8> Weights;
3160 bool HasWeights = HasBranchWeights(SI);
3161 if (HasWeights) {
3162 GetBranchWeights(SI, Weights);
3163 if (Weights.size() == 1 + SI->getNumCases()) {
3164 // Combine all weights for the cases to be the true weight of NewBI.
3165 // We assume that the sum of all weights for a Terminator can fit into 32
3166 // bits.
3167 uint32_t NewTrueWeight = 0;
3168 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3169 NewTrueWeight += (uint32_t)Weights[I];
3170 NewBI->setMetadata(LLVMContext::MD_prof,
3171 MDBuilder(SI->getContext()).
3172 createBranchWeights(NewTrueWeight,
3173 (uint32_t)Weights[0]));
3174 }
3175 }
3176
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003177 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003178 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003179 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003180 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003181 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3182 }
3183 SI->eraseFromParent();
3184
3185 return true;
3186}
Chris Lattner25c3af32010-12-13 06:25:44 +00003187
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003188/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3189/// and use it to remove dead cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003190static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3191 AssumptionTracker *AT) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003192 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003193 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003194 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003195 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003196
3197 // Gather dead cases.
3198 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003199 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003200 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3201 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3202 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003203 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003204 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003205 }
3206 }
3207
Manman Ren56575552012-09-18 00:47:33 +00003208 SmallVector<uint64_t, 8> Weights;
3209 bool HasWeight = HasBranchWeights(SI);
3210 if (HasWeight) {
3211 GetBranchWeights(SI, Weights);
3212 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3213 }
3214
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003215 // Remove dead cases from the switch.
3216 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003217 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003218 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003219 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003220 if (HasWeight) {
3221 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3222 Weights.pop_back();
3223 }
3224
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003225 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003226 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003227 SI->removeCase(Case);
3228 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003229 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003230 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3231 SI->setMetadata(LLVMContext::MD_prof,
3232 MDBuilder(SI->getParent()->getContext()).
3233 createBranchWeights(MDWeights));
3234 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003235
3236 return !DeadCases.empty();
3237}
3238
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003239/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3240/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3241/// by an unconditional branch), look at the phi node for BB in the successor
3242/// block and see if the incoming value is equal to CaseValue. If so, return
3243/// the phi node, and set PhiIndex to BB's index in the phi node.
3244static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3245 BasicBlock *BB,
3246 int *PhiIndex) {
3247 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003248 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003249 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003250 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003251
3252 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3253 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003254 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003255
3256 BasicBlock *Succ = Branch->getSuccessor(0);
3257
3258 BasicBlock::iterator I = Succ->begin();
3259 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3260 int Idx = PHI->getBasicBlockIndex(BB);
3261 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3262
3263 Value *InValue = PHI->getIncomingValue(Idx);
3264 if (InValue != CaseValue) continue;
3265
3266 *PhiIndex = Idx;
3267 return PHI;
3268 }
3269
Craig Topperf40110f2014-04-25 05:29:35 +00003270 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003271}
3272
3273/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3274/// instruction to a phi node dominated by the switch, if that would mean that
3275/// some of the destination blocks of the switch can be folded away.
3276/// Returns true if a change is made.
3277static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3278 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3279 ForwardingNodesMap ForwardingNodes;
3280
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003281 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003282 ConstantInt *CaseValue = I.getCaseValue();
3283 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003284
3285 int PhiIndex;
3286 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3287 &PhiIndex);
3288 if (!PHI) continue;
3289
3290 ForwardingNodes[PHI].push_back(PhiIndex);
3291 }
3292
3293 bool Changed = false;
3294
3295 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3296 E = ForwardingNodes.end(); I != E; ++I) {
3297 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003298 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003299
3300 if (Indexes.size() < 2) continue;
3301
3302 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3303 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3304 Changed = true;
3305 }
3306
3307 return Changed;
3308}
3309
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003310/// ValidLookupTableConstant - Return true if the backend will be able to handle
3311/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003312static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003313 if (C->isThreadDependent())
3314 return false;
3315 if (C->isDLLImportDependent())
3316 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003317
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003318 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3319 return CE->isGEPWithNoNotionalOverIndexing();
3320
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003321 return isa<ConstantFP>(C) ||
3322 isa<ConstantInt>(C) ||
3323 isa<ConstantPointerNull>(C) ||
3324 isa<GlobalValue>(C) ||
3325 isa<UndefValue>(C);
3326}
3327
Hans Wennborg09acdb92012-10-31 15:14:39 +00003328/// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003329/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003330static Constant *LookupConstant(Value *V,
3331 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3332 if (Constant *C = dyn_cast<Constant>(V))
3333 return C;
3334 return ConstantPool.lookup(V);
3335}
3336
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003337/// ConstantFold - Try to fold instruction I into a constant. This works for
3338/// simple instructions such as binary operations where both operands are
3339/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003340/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003341static Constant *
3342ConstantFold(Instruction *I,
3343 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3344 const DataLayout *DL) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003345 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003346 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3347 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003348 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003349 if (A->isAllOnesValue())
3350 return LookupConstant(Select->getTrueValue(), ConstantPool);
3351 if (A->isNullValue())
3352 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003353 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003354 }
3355
Benjamin Kramer7c302602013-11-12 12:24:36 +00003356 SmallVector<Constant *, 4> COps;
3357 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3358 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3359 COps.push_back(A);
3360 else
Craig Topperf40110f2014-04-25 05:29:35 +00003361 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003362 }
3363
Benjamin Kramer7c302602013-11-12 12:24:36 +00003364 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3365 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3366 COps[1], DL);
3367
3368 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003369}
3370
3371/// GetCaseResults - Try to determine the resulting constant values in phi nodes
3372/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003373/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003374/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003375static bool
3376GetCaseResults(SwitchInst *SI,
3377 ConstantInt *CaseVal,
3378 BasicBlock *CaseDest,
3379 BasicBlock **CommonDest,
Benjamin Kramer7c302602013-11-12 12:24:36 +00003380 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3381 const DataLayout *DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003382 // The block from which we enter the common destination.
3383 BasicBlock *Pred = SI->getParent();
3384
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003385 // If CaseDest is empty except for some side-effect free instructions through
3386 // which we can constant-propagate the CaseVal, continue to its successor.
3387 SmallDenseMap<Value*, Constant*> ConstantPool;
3388 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3389 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3390 ++I) {
3391 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3392 // If the terminator is a simple branch, continue to the next block.
3393 if (T->getNumSuccessors() != 1)
3394 return false;
3395 Pred = CaseDest;
3396 CaseDest = T->getSuccessor(0);
3397 } else if (isa<DbgInfoIntrinsic>(I)) {
3398 // Skip debug intrinsic.
3399 continue;
Benjamin Kramer7c302602013-11-12 12:24:36 +00003400 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003401 // Instruction is side-effect free and constant.
3402 ConstantPool.insert(std::make_pair(I, C));
3403 } else {
3404 break;
3405 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003406 }
3407
3408 // If we did not have a CommonDest before, use the current one.
3409 if (!*CommonDest)
3410 *CommonDest = CaseDest;
3411 // If the destination isn't the common one, abort.
3412 if (CaseDest != *CommonDest)
3413 return false;
3414
3415 // Get the values for this case from phi nodes in the destination block.
3416 BasicBlock::iterator I = (*CommonDest)->begin();
3417 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3418 int Idx = PHI->getBasicBlockIndex(Pred);
3419 if (Idx == -1)
3420 continue;
3421
Hans Wennborg09acdb92012-10-31 15:14:39 +00003422 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3423 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003424 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003425 return false;
3426
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003427 // Note: If the constant comes from constant-propagating the case value
3428 // through the CaseDest basic block, it will be safe to remove the
3429 // instructions in that block. They cannot be used (except in the phi nodes
3430 // we visit) outside CaseDest, because that block does not dominate its
3431 // successor. If it did, we would not be in this phi node.
3432
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003433 // Be conservative about which kinds of constants we support.
3434 if (!ValidLookupTableConstant(ConstVal))
3435 return false;
3436
3437 Res.push_back(std::make_pair(PHI, ConstVal));
3438 }
3439
Hans Wennborgac114a32014-01-12 00:44:41 +00003440 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003441}
3442
Hans Wennborg776d7122012-09-26 09:34:53 +00003443namespace {
3444 /// SwitchLookupTable - This class represents a lookup table that can be used
3445 /// to replace a switch.
3446 class SwitchLookupTable {
3447 public:
3448 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3449 /// with the contents of Values, using DefaultValue to fill any holes in the
3450 /// table.
3451 SwitchLookupTable(Module &M,
3452 uint64_t TableSize,
3453 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003454 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003455 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003456 const DataLayout *DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003457
3458 /// BuildLookup - Build instructions with Builder to retrieve the value at
3459 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003460 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003461
Hans Wennborg39583b82012-09-26 09:44:49 +00003462 /// WouldFitInRegister - Return true if a table with TableSize elements of
3463 /// type ElementType would fit in a target-legal register.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003464 static bool WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003465 uint64_t TableSize,
3466 const Type *ElementType);
3467
Hans Wennborg776d7122012-09-26 09:34:53 +00003468 private:
3469 // Depending on the contents of the table, it can be represented in
3470 // different ways.
3471 enum {
3472 // For tables where each element contains the same value, we just have to
3473 // store that single value and return it for each lookup.
3474 SingleValueKind,
3475
Hans Wennborg39583b82012-09-26 09:44:49 +00003476 // For small tables with integer elements, we can pack them into a bitmap
3477 // that fits into a target-legal register. Values are retrieved by
3478 // shift and mask operations.
3479 BitMapKind,
3480
Hans Wennborg776d7122012-09-26 09:34:53 +00003481 // The table is stored as an array of values. Values are retrieved by load
3482 // instructions from the table.
3483 ArrayKind
3484 } Kind;
3485
3486 // For SingleValueKind, this is the single value.
3487 Constant *SingleValue;
3488
Hans Wennborg39583b82012-09-26 09:44:49 +00003489 // For BitMapKind, this is the bitmap.
3490 ConstantInt *BitMap;
3491 IntegerType *BitMapElementTy;
3492
Hans Wennborg776d7122012-09-26 09:34:53 +00003493 // For ArrayKind, this is the array.
3494 GlobalVariable *Array;
3495 };
3496}
3497
3498SwitchLookupTable::SwitchLookupTable(Module &M,
3499 uint64_t TableSize,
3500 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003501 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003502 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003503 const DataLayout *DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003504 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3505 Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003506 assert(Values.size() && "Can't build lookup table without values!");
3507 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003508
3509 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003510 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003511
Hans Wennborgac114a32014-01-12 00:44:41 +00003512 Type *ValueType = Values.begin()->second->getType();
3513
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003514 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003515 SmallVector<Constant*, 64> TableContents(TableSize);
3516 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3517 ConstantInt *CaseVal = Values[I].first;
3518 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003519 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003520
Hans Wennborg776d7122012-09-26 09:34:53 +00003521 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3522 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003523 TableContents[Idx] = CaseRes;
3524
Hans Wennborg776d7122012-09-26 09:34:53 +00003525 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003526 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003527 }
3528
3529 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003530 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003531 assert(DefaultValue &&
3532 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003533 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003534 for (uint64_t I = 0; I < TableSize; ++I) {
3535 if (!TableContents[I])
3536 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003537 }
3538
Hans Wennborg776d7122012-09-26 09:34:53 +00003539 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003540 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003541 }
3542
Hans Wennborg776d7122012-09-26 09:34:53 +00003543 // If each element in the table contains the same value, we only need to store
3544 // that single value.
3545 if (SingleValue) {
3546 Kind = SingleValueKind;
3547 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003548 }
3549
Hans Wennborg39583b82012-09-26 09:44:49 +00003550 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003551 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003552 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003553 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3554 for (uint64_t I = TableSize; I > 0; --I) {
3555 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003556 // Insert values into the bitmap. Undef values are set to zero.
3557 if (!isa<UndefValue>(TableContents[I - 1])) {
3558 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3559 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3560 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003561 }
3562 BitMap = ConstantInt::get(M.getContext(), TableInt);
3563 BitMapElementTy = IT;
3564 Kind = BitMapKind;
3565 ++NumBitMaps;
3566 return;
3567 }
3568
Hans Wennborg776d7122012-09-26 09:34:53 +00003569 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003570 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003571 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3572
Hans Wennborg776d7122012-09-26 09:34:53 +00003573 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3574 GlobalVariable::PrivateLinkage,
3575 Initializer,
3576 "switch.table");
3577 Array->setUnnamedAddr(true);
3578 Kind = ArrayKind;
3579}
3580
Manman Ren4d189fb2014-07-24 21:13:20 +00003581Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003582 switch (Kind) {
3583 case SingleValueKind:
3584 return SingleValue;
Hans Wennborg39583b82012-09-26 09:44:49 +00003585 case BitMapKind: {
3586 // Type of the bitmap (e.g. i59).
3587 IntegerType *MapTy = BitMap->getType();
3588
3589 // Cast Index to the same type as the bitmap.
3590 // Note: The Index is <= the number of elements in the table, so
3591 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003592 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003593
3594 // Multiply the shift amount by the element width.
3595 ShiftAmt = Builder.CreateMul(ShiftAmt,
3596 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3597 "switch.shiftamt");
3598
3599 // Shift down.
3600 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3601 "switch.downshift");
3602 // Mask off.
3603 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3604 "switch.masked");
3605 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003606 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003607 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003608 IntegerType *IT = cast<IntegerType>(Index->getType());
3609 uint64_t TableSize = Array->getInitializer()->getType()
3610 ->getArrayNumElements();
3611 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3612 Index = Builder.CreateZExt(Index,
3613 IntegerType::get(IT->getContext(),
3614 IT->getBitWidth() + 1),
3615 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003616
Hans Wennborg776d7122012-09-26 09:34:53 +00003617 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3618 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3619 "switch.gep");
3620 return Builder.CreateLoad(GEP, "switch.load");
3621 }
3622 }
3623 llvm_unreachable("Unknown lookup table kind!");
3624}
3625
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003626bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003627 uint64_t TableSize,
3628 const Type *ElementType) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003629 if (!DL)
Hans Wennborg39583b82012-09-26 09:44:49 +00003630 return false;
3631 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3632 if (!IT)
3633 return false;
3634 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3635 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003636
3637 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3638 if (TableSize >= UINT_MAX/IT->getBitWidth())
3639 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003640 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003641}
3642
Hans Wennborg776d7122012-09-26 09:34:53 +00003643/// ShouldBuildLookupTable - Determine whether a lookup table should be built
Hans Wennborg5cf30be2013-06-04 11:22:30 +00003644/// for this switch, based on the number of cases, size of the table and the
Hans Wennborg776d7122012-09-26 09:34:53 +00003645/// types of the results.
3646static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003647 uint64_t TableSize,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003648 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003649 const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003650 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003651 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3652 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003653
Chandler Carruth77d433d2012-11-30 09:26:25 +00003654 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003655 bool HasIllegalType = false;
Hans Wennborg39583b82012-09-26 09:44:49 +00003656 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3657 E = ResultTypes.end(); I != E; ++I) {
Evan Cheng65df8082012-11-30 02:02:42 +00003658 Type *Ty = I->second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003659
3660 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003661 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003662
3663 // Saturate this flag to false.
3664 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003665 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003666
3667 // If both flags saturate, we're done. NOTE: This *only* works with
3668 // saturating flags, and all flags have to saturate first due to the
3669 // non-deterministic behavior of iterating over a dense map.
3670 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003671 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003672 }
Evan Cheng65df8082012-11-30 02:02:42 +00003673
Chandler Carruth77d433d2012-11-30 09:26:25 +00003674 // If each table would fit in a register, we should build it anyway.
3675 if (AllTablesFitInRegister)
3676 return true;
3677
3678 // Don't build a table that doesn't fit in-register if it has illegal types.
3679 if (HasIllegalType)
3680 return false;
3681
3682 // The table density should be at least 40%. This is the same criterion as for
3683 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3684 // FIXME: Find the best cut-off.
3685 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003686}
3687
3688/// SwitchToLookupTable - If the switch is only used to initialize one or more
3689/// phi nodes in a common successor block with different constant values,
3690/// replace the switch with lookup tables.
3691static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003692 IRBuilder<> &Builder,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003693 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003694 const DataLayout* DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003695 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00003696
Hans Wennborgc3c8d952012-11-07 21:35:12 +00003697 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003698 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00003699 return false;
3700
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003701 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3702 // split off a dense part and build a lookup table for that.
3703
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003704 // FIXME: This creates arrays of GEPs to constant strings, which means each
3705 // GEP needs a runtime relocation in PIC code. We should just build one big
3706 // string and lookup indices into that.
3707
Hans Wennborg4744ac12014-01-15 05:00:27 +00003708 // Ignore switches with less than three cases. Lookup tables will not make them
3709 // faster, so we don't analyze them.
3710 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003711 return false;
3712
3713 // Figure out the corresponding result for each case value and phi node in the
3714 // common destination, as well as the the min and max case values.
3715 assert(SI->case_begin() != SI->case_end());
3716 SwitchInst::CaseIt CI = SI->case_begin();
3717 ConstantInt *MinCaseVal = CI.getCaseValue();
3718 ConstantInt *MaxCaseVal = CI.getCaseValue();
3719
Craig Topperf40110f2014-04-25 05:29:35 +00003720 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003721 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003722 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3723 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3724 SmallDenseMap<PHINode*, Type*> ResultTypes;
3725 SmallVector<PHINode*, 4> PHIs;
3726
3727 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3728 ConstantInt *CaseVal = CI.getCaseValue();
3729 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3730 MinCaseVal = CaseVal;
3731 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3732 MaxCaseVal = CaseVal;
3733
3734 // Resulting value at phi nodes for this case value.
3735 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3736 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003737 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003738 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003739 return false;
3740
3741 // Append the result from this case to the list for each phi.
3742 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3743 if (!ResultLists.count(I->first))
3744 PHIs.push_back(I->first);
3745 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3746 }
3747 }
3748
Hans Wennborgac114a32014-01-12 00:44:41 +00003749 // Keep track of the result types.
3750 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3751 PHINode *PHI = PHIs[I];
3752 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3753 }
3754
3755 uint64_t NumResults = ResultLists[PHIs[0]].size();
3756 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3757 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3758 bool TableHasHoles = (NumResults < TableSize);
3759
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003760 // If the table has holes, we need a constant result for the default case
3761 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003762 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003763 bool HasDefaultResults = false;
3764 if (TableHasHoles) {
Craig Topperf40110f2014-04-25 05:29:35 +00003765 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3766 &CommonDest, DefaultResultsList, DL);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003767 }
3768 bool NeedMask = (TableHasHoles && !HasDefaultResults);
3769 if (NeedMask) {
3770 // As an extra penalty for the validity test we require more cases.
3771 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
3772 return false;
3773 if (!(DL && DL->fitsInLegalInteger(TableSize)))
3774 return false;
3775 }
Hans Wennborgac114a32014-01-12 00:44:41 +00003776
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003777 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3778 PHINode *PHI = DefaultResultsList[I].first;
3779 Constant *Result = DefaultResultsList[I].second;
3780 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003781 }
3782
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003783 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003784 return false;
3785
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003786 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00003787 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003788 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3789 "switch.lookup",
3790 CommonDest->getParent(),
3791 CommonDest);
3792
Michael Gottesmanc024f322013-10-20 07:04:37 +00003793 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003794 Builder.SetInsertPoint(SI);
3795 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3796 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00003797
3798 // Compute the maximum table size representable by the integer type we are
3799 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003800 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00003801 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00003802 assert(MaxTableSize >= TableSize &&
3803 "It is impossible for a switch to have more entries than the max "
3804 "representable value of its input integer type's size.");
3805
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003806 // If we have a fully covered lookup table, unconditionally branch to the
3807 // lookup table BB. Otherwise, check if the condition value is within the case
3808 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3809 // destination.
Michael Gottesmanc024f322013-10-20 07:04:37 +00003810 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3811 if (GeneratingCoveredLookupTable) {
3812 Builder.CreateBr(LookupBB);
Manman Ren062f58d2014-08-02 23:41:54 +00003813 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
3814 // do not delete PHINodes here.
3815 SI->getDefaultDest()->removePredecessor(SI->getParent(),
3816 true/*DontDeleteUselessPHIs*/);
Michael Gottesmanc024f322013-10-20 07:04:37 +00003817 } else {
3818 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00003819 MinCaseVal->getType(), TableSize));
Michael Gottesmanc024f322013-10-20 07:04:37 +00003820 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3821 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003822
3823 // Populate the BB that does the lookups.
3824 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003825
3826 if (NeedMask) {
3827 // Before doing the lookup we do the hole check.
3828 // The LookupBB is therefore re-purposed to do the hole check
3829 // and we create a new LookupBB.
3830 BasicBlock *MaskBB = LookupBB;
3831 MaskBB->setName("switch.hole_check");
3832 LookupBB = BasicBlock::Create(Mod.getContext(),
3833 "switch.lookup",
3834 CommonDest->getParent(),
3835 CommonDest);
3836
3837 // Build bitmask; fill in a 1 bit for every case.
3838 APInt MaskInt(TableSize, 0);
3839 APInt One(TableSize, 1);
3840 const ResultListTy &ResultList = ResultLists[PHIs[0]];
3841 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3842 uint64_t Idx = (ResultList[I].first->getValue() -
3843 MinCaseVal->getValue()).getLimitedValue();
3844 MaskInt |= One << Idx;
3845 }
3846 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3847
3848 // Get the TableIndex'th bit of the bitmask.
3849 // If this bit is 0 (meaning hole) jump to the default destination,
3850 // else continue with table lookup.
3851 IntegerType *MapTy = TableMask->getType();
3852 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3853 "switch.maskindex");
3854 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3855 "switch.shifted");
3856 Value *LoBit = Builder.CreateTrunc(Shifted,
3857 Type::getInt1Ty(Mod.getContext()),
3858 "switch.lobit");
3859 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3860
3861 Builder.SetInsertPoint(LookupBB);
3862 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3863 }
3864
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003865 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00003866 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3867 PHINode *PHI = PHIs[I];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003868
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003869 // If using a bitmask, use any value to fill the lookup table holes.
3870 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Hans Wennborg776d7122012-09-26 09:34:53 +00003871 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003872 DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003873
Manman Ren4d189fb2014-07-24 21:13:20 +00003874 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003875
Hans Wennborgf744fa92012-09-19 14:24:21 +00003876 // If the result is used to return immediately from the function, we want to
3877 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003878 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3879 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00003880 Builder.CreateRet(Result);
3881 ReturnedEarly = true;
3882 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003883 }
3884
Hans Wennborgf744fa92012-09-19 14:24:21 +00003885 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003886 }
3887
3888 if (!ReturnedEarly)
3889 Builder.CreateBr(CommonDest);
3890
3891 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003892 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003893 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00003894
Michael Gottesman63c63ac2013-10-21 05:20:11 +00003895 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00003896 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003897 Succ->removePredecessor(SI->getParent());
3898 }
3899 SI->eraseFromParent();
3900
3901 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00003902 if (NeedMask)
3903 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003904 return true;
3905}
3906
Devang Patela7ec47d2011-05-18 20:35:38 +00003907bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003908 BasicBlock *BB = SI->getParent();
3909
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003910 if (isValueEqualityComparison(SI)) {
3911 // If we only have one predecessor, and if it is a branch on this value,
3912 // see if that predecessor totally determines the outcome of this switch.
3913 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3914 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00003915 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00003916
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003917 Value *Cond = SI->getCondition();
3918 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3919 if (SimplifySwitchOnSelect(SI, Select))
Jingyue Wufc029672014-09-30 22:23:38 +00003920 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00003921
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003922 // If the block only contains the switch, see if we can fold the block
3923 // away into any preds.
3924 BasicBlock::iterator BBI = BB->begin();
3925 // Ignore dbg intrinsics.
3926 while (isa<DbgInfoIntrinsic>(BBI))
3927 ++BBI;
3928 if (SI == &*BBI)
3929 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00003930 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00003931 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003932
3933 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003934 if (TurnSwitchRangeIntoICmp(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00003935 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003936
3937 // Remove unreachable cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003938 if (EliminateDeadSwitchCases(SI, DL, AT))
Jingyue Wufc029672014-09-30 22:23:38 +00003939 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003940
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003941 if (ForwardSwitchConditionToPHI(SI))
Jingyue Wufc029672014-09-30 22:23:38 +00003942 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003943
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003944 if (SwitchToLookupTable(SI, Builder, TTI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00003945 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003946
Chris Lattner25c3af32010-12-13 06:25:44 +00003947 return false;
3948}
3949
3950bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3951 BasicBlock *BB = IBI->getParent();
3952 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003953
Chris Lattner25c3af32010-12-13 06:25:44 +00003954 // Eliminate redundant destinations.
3955 SmallPtrSet<Value *, 8> Succs;
3956 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3957 BasicBlock *Dest = IBI->getDestination(i);
3958 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3959 Dest->removePredecessor(BB);
3960 IBI->removeDestination(i);
3961 --i; --e;
3962 Changed = true;
3963 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003964 }
Chris Lattner25c3af32010-12-13 06:25:44 +00003965
3966 if (IBI->getNumDestinations() == 0) {
3967 // If the indirectbr has no successors, change it to unreachable.
3968 new UnreachableInst(IBI->getContext(), IBI);
3969 EraseTerminatorInstAndDCECond(IBI);
3970 return true;
3971 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003972
Chris Lattner25c3af32010-12-13 06:25:44 +00003973 if (IBI->getNumDestinations() == 1) {
3974 // If the indirectbr has one successor, change it to a direct branch.
3975 BranchInst::Create(IBI->getDestination(0), IBI);
3976 EraseTerminatorInstAndDCECond(IBI);
3977 return true;
3978 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003979
Chris Lattner25c3af32010-12-13 06:25:44 +00003980 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3981 if (SimplifyIndirectBrOnSelect(IBI, SI))
Jingyue Wufc029672014-09-30 22:23:38 +00003982 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003983 }
3984 return Changed;
3985}
3986
Devang Patel767f6932011-05-18 18:28:48 +00003987bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00003988 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003989
Manman Ren93ab6492012-09-20 22:37:36 +00003990 if (SinkCommon && SinkThenElseCodeToEnd(BI))
3991 return true;
3992
Chris Lattner25c3af32010-12-13 06:25:44 +00003993 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00003994 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00003995 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3996 TryToSimplifyUncondBranchFromEmptyBlock(BB))
3997 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003998
Chris Lattner25c3af32010-12-13 06:25:44 +00003999 // If the only instruction in the block is a seteq/setne comparison
4000 // against a constant, try to simplify the block.
4001 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4002 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4003 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4004 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004005 if (I->isTerminator() &&
Jingyue Wufc029672014-09-30 22:23:38 +00004006 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4007 BonusInstThreshold, DL, AT))
Chris Lattner25c3af32010-12-13 06:25:44 +00004008 return true;
4009 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004010
Manman Rend33f4ef2012-06-13 05:43:29 +00004011 // If this basic block is ONLY a compare and a branch, and if a predecessor
4012 // branches to us and our successor, fold the comparison into the
4013 // predecessor and use logical operations to update the incoming value
4014 // for PHI nodes in common successor.
Jingyue Wufc029672014-09-30 22:23:38 +00004015 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4016 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004017 return false;
4018}
4019
4020
Devang Patela7ec47d2011-05-18 20:35:38 +00004021bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004022 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004023
Chris Lattner25c3af32010-12-13 06:25:44 +00004024 // Conditional branch
4025 if (isValueEqualityComparison(BI)) {
4026 // If we only have one predecessor, and if it is a branch on this value,
4027 // see if that predecessor totally determines the outcome of this
4028 // switch.
4029 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004030 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004031 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004032
Chris Lattner25c3af32010-12-13 06:25:44 +00004033 // This block must be empty, except for the setcond inst, if it exists.
4034 // Ignore dbg intrinsics.
4035 BasicBlock::iterator I = BB->begin();
4036 // Ignore dbg intrinsics.
4037 while (isa<DbgInfoIntrinsic>(I))
4038 ++I;
4039 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004040 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004041 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004042 } else if (&*I == cast<Instruction>(BI->getCondition())){
4043 ++I;
4044 // Ignore dbg intrinsics.
4045 while (isa<DbgInfoIntrinsic>(I))
4046 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004047 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004048 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004049 }
4050 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004051
Chris Lattner25c3af32010-12-13 06:25:44 +00004052 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004053 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004054 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004055
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004056 // If this basic block is ONLY a compare and a branch, and if a predecessor
4057 // branches to us and one of our successors, fold the comparison into the
4058 // predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00004059 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4060 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004061
Chris Lattner25c3af32010-12-13 06:25:44 +00004062 // We have a conditional branch to two blocks that are only reachable
4063 // from BI. We know that the condbr dominates the two blocks, so see if
4064 // there is any identical code in the "then" and "else" blocks. If so, we
4065 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004066 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4067 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Hal Finkela995f922014-07-10 14:41:31 +00004068 if (HoistThenElseCodeToIf(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004069 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004070 } else {
4071 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004072 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004073 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4074 if (Succ0TI->getNumSuccessors() == 1 &&
4075 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Hal Finkela995f922014-07-10 14:41:31 +00004076 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004077 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004078 }
Craig Topperf40110f2014-04-25 05:29:35 +00004079 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004080 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004081 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004082 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4083 if (Succ1TI->getNumSuccessors() == 1 &&
4084 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Hal Finkela995f922014-07-10 14:41:31 +00004085 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004086 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004087 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004088
Chris Lattner25c3af32010-12-13 06:25:44 +00004089 // If this is a branch on a phi node in the current block, thread control
4090 // through this block if any PHI node entries are constants.
4091 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4092 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004093 if (FoldCondBranchOnPHI(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004094 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004095
Chris Lattner25c3af32010-12-13 06:25:44 +00004096 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004097 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4098 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004099 if (PBI != BI && PBI->isConditional())
4100 if (SimplifyCondBranchToCondBranch(PBI, BI))
Jingyue Wufc029672014-09-30 22:23:38 +00004101 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004102
4103 return false;
4104}
4105
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004106/// Check if passing a value to an instruction will cause undefined behavior.
4107static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4108 Constant *C = dyn_cast<Constant>(V);
4109 if (!C)
4110 return false;
4111
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004112 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004113 return false;
4114
4115 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004116 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004117 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004118
4119 // Now make sure that there are no instructions in between that can alter
4120 // control flow (eg. calls)
4121 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004122 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004123 return false;
4124
4125 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4126 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4127 if (GEP->getPointerOperand() == I)
4128 return passingValueIsAlwaysUndefined(V, GEP);
4129
4130 // Look through bitcasts.
4131 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4132 return passingValueIsAlwaysUndefined(V, BC);
4133
Benjamin Kramer0655b782011-08-26 02:25:55 +00004134 // Load from null is undefined.
4135 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004136 if (!LI->isVolatile())
4137 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004138
Benjamin Kramer0655b782011-08-26 02:25:55 +00004139 // Store to null is undefined.
4140 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004141 if (!SI->isVolatile())
4142 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004143 }
4144 return false;
4145}
4146
4147/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004148/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004149static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4150 for (BasicBlock::iterator i = BB->begin();
4151 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4152 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4153 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4154 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4155 IRBuilder<> Builder(T);
4156 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4157 BB->removePredecessor(PHI->getIncomingBlock(i));
4158 // Turn uncoditional branches into unreachables and remove the dead
4159 // destination from conditional branches.
4160 if (BI->isUnconditional())
4161 Builder.CreateUnreachable();
4162 else
4163 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4164 BI->getSuccessor(0));
4165 BI->eraseFromParent();
4166 return true;
4167 }
4168 // TODO: SwitchInst.
4169 }
4170
4171 return false;
4172}
4173
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004174bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004175 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004176
Chris Lattnerd7beca32010-12-14 06:17:25 +00004177 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004178 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004179
Dan Gohman4a63fad2010-08-14 00:29:42 +00004180 // Remove basic blocks that have no predecessors (except the entry block)...
4181 // or that just have themself as a predecessor. These are unreachable.
Chris Lattnerd7beca32010-12-14 06:17:25 +00004182 if ((pred_begin(BB) == pred_end(BB) &&
4183 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004184 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004185 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004186 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004187 return true;
4188 }
4189
Chris Lattner031340a2003-08-17 19:41:53 +00004190 // Check to see if we can constant propagate this terminator instruction
4191 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004192 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004193
Dan Gohman1a951062009-10-30 22:39:04 +00004194 // Check for and eliminate duplicate PHI nodes in this block.
4195 Changed |= EliminateDuplicatePHINodes(BB);
4196
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004197 // Check for and remove branches that will always cause undefined behavior.
4198 Changed |= removeUndefIntroducingPredecessor(BB);
4199
Chris Lattner2e3832d2010-12-13 05:10:48 +00004200 // Merge basic blocks into their predecessor if there is only one distinct
4201 // pred, and if there is only one distinct successor of the predecessor, and
4202 // if there are no PHI nodes.
4203 //
4204 if (MergeBlockIntoPredecessor(BB))
4205 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004206
Devang Patel15ad6762011-05-18 18:01:27 +00004207 IRBuilder<> Builder(BB);
4208
Dan Gohman20af5a02008-03-11 21:53:06 +00004209 // If there is a trivial two-entry PHI node in this basic block, and we can
4210 // eliminate it, do so now.
4211 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4212 if (PN->getNumIncomingValues() == 2)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004213 Changed |= FoldTwoEntryPHINode(PN, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004214
Devang Patela7ec47d2011-05-18 20:35:38 +00004215 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004216 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004217 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004218 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004219 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004220 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004221 }
4222 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004223 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004224 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4225 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004226 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004227 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004228 } else if (UnreachableInst *UI =
4229 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4230 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004231 } else if (IndirectBrInst *IBI =
4232 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4233 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004234 }
4235
Chris Lattner031340a2003-08-17 19:41:53 +00004236 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004237}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004238
4239/// SimplifyCFG - This function is used to do simplification of a CFG. For
4240/// example, it adjusts branches to branches to eliminate the extra hop, it
4241/// eliminates unreachable basic blocks, and does other "peephole" optimization
4242/// of the CFG. It returns true if a modification was made.
4243///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004244bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00004245 unsigned BonusInstThreshold,
Hal Finkel60db0582014-09-07 18:57:58 +00004246 const DataLayout *DL, AssumptionTracker *AT) {
Jingyue Wufc029672014-09-30 22:23:38 +00004247 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004248}