blob: aa3baf07ab31162e0a4036abfdfc8da72c0da55e [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000021#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000038#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000042#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000046#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000047#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000048#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000049#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000051using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000052using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "simplifycfg"
55
Peter Collingbourne616044a2011-04-29 18:47:38 +000056static cl::opt<unsigned>
57PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
59
Evan Chengd983eba2011-01-29 04:46:23 +000060static cl::opt<bool>
61DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
63
Manman Ren93ab6492012-09-20 22:37:36 +000064static cl::opt<bool>
65SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
67
Alp Tokercb402912014-01-24 17:20:08 +000068static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000071
Hans Wennborg39583b82012-09-26 09:44:49 +000072STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000073STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000074STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000075STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Manman Ren93ab6492012-09-20 22:37:36 +000076STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000077STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000078
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000079namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000080 // The first field contains the value that the switch produces when a certain
81 // case group is selected, and the second field is a vector containing the cases
82 // composing the case group.
83 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
84 SwitchCaseResultVectorTy;
85 // The first field contains the phi node that generates a result of the switch
86 // and the second field contains the value generated for a certain case in the switch
87 // for that PHI.
88 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
89
Eric Christopherb65acc62012-07-02 23:22:21 +000090 /// ValueEqualityComparisonCase - Represents a case of a switch.
91 struct ValueEqualityComparisonCase {
92 ConstantInt *Value;
93 BasicBlock *Dest;
94
95 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
96 : Value(Value), Dest(Dest) {}
97
98 bool operator<(ValueEqualityComparisonCase RHS) const {
99 // Comparing pointers is ok as we only rely on the order for uniquing.
100 return Value < RHS.Value;
101 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000102
103 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000104 };
105
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000106class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000107 const TargetTransformInfo &TTI;
Jingyue Wufc029672014-09-30 22:23:38 +0000108 unsigned BonusInstThreshold;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000109 const DataLayout *const DL;
Hal Finkel60db0582014-09-07 18:57:58 +0000110 AssumptionTracker *AT;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000111 Value *isValueEqualityComparison(TerminatorInst *TI);
112 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000113 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000114 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000115 BasicBlock *Pred,
116 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000117 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
118 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000119
Devang Pateldd14e0f2011-05-18 21:33:11 +0000120 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000121 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000122 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000123 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000124 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000125 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000126 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000127
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000128public:
Jingyue Wufc029672014-09-30 22:23:38 +0000129 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
130 const DataLayout *DL, AssumptionTracker *AT)
131 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000132 bool run(BasicBlock *BB);
133};
134}
135
Chris Lattner76dc2042005-08-03 00:19:45 +0000136/// SafeToMergeTerminators - Return true if it is safe to merge these two
137/// terminator instructions together.
138///
139static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
140 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000141
Chris Lattner76dc2042005-08-03 00:19:45 +0000142 // It is not safe to merge these two switch instructions if they have a common
143 // successor, and if that successor has a PHI node, and if *that* PHI node has
144 // conflicting incoming values from the two switch blocks.
145 BasicBlock *SI1BB = SI1->getParent();
146 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000147 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000148
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000149 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
150 if (SI1Succs.count(*I))
151 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000152 isa<PHINode>(BBI); ++BBI) {
153 PHINode *PN = cast<PHINode>(BBI);
154 if (PN->getIncomingValueForBlock(SI1BB) !=
155 PN->getIncomingValueForBlock(SI2BB))
156 return false;
157 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000158
Chris Lattner76dc2042005-08-03 00:19:45 +0000159 return true;
160}
161
Manman Rend33f4ef2012-06-13 05:43:29 +0000162/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
163/// to merge these two terminator instructions together, where SI1 is an
164/// unconditional branch. PhiNodes will store all PHI nodes in common
165/// successors.
166///
167static bool isProfitableToFoldUnconditional(BranchInst *SI1,
168 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000169 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000170 SmallVectorImpl<PHINode*> &PhiNodes) {
171 if (SI1 == SI2) return false; // Can't merge with self!
172 assert(SI1->isUnconditional() && SI2->isConditional());
173
174 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000175 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000176 // 1> We have a constant incoming value for the conditional branch;
177 // 2> We have "Cond" as the incoming value for the unconditional branch;
178 // 3> SI2->getCondition() and Cond have same operands.
179 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
180 if (!Ci2) return false;
181 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
182 Cond->getOperand(1) == Ci2->getOperand(1)) &&
183 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
184 Cond->getOperand(1) == Ci2->getOperand(0)))
185 return false;
186
187 BasicBlock *SI1BB = SI1->getParent();
188 BasicBlock *SI2BB = SI2->getParent();
189 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000190 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
191 if (SI1Succs.count(*I))
192 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000193 isa<PHINode>(BBI); ++BBI) {
194 PHINode *PN = cast<PHINode>(BBI);
195 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000196 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000197 return false;
198 PhiNodes.push_back(PN);
199 }
200 return true;
201}
202
Chris Lattner76dc2042005-08-03 00:19:45 +0000203/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
204/// now be entries in it from the 'NewPred' block. The values that will be
205/// flowing into the PHI nodes will be the same as those coming in from
206/// ExistPred, an existing predecessor of Succ.
207static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
208 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000209 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000210
Chris Lattner80b03a12008-07-13 22:23:11 +0000211 PHINode *PN;
212 for (BasicBlock::iterator I = Succ->begin();
213 (PN = dyn_cast<PHINode>(I)); ++I)
214 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000215}
216
David Majnemer91142c42013-06-01 19:43:23 +0000217/// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000218/// given instruction, which is assumed to be safe to speculate. 1 means
219/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
Hal Finkela995f922014-07-10 14:41:31 +0000220static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
221 assert(isSafeToSpeculativelyExecute(I, DL) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000222 "Instruction is not safe to speculatively execute!");
223 switch (Operator::getOpcode(I)) {
224 default:
225 // In doubt, be conservative.
226 return UINT_MAX;
227 case Instruction::GetElementPtr:
228 // GEPs are cheap if all indices are constant.
229 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
230 return UINT_MAX;
231 return 1;
Louis Gerbarg1f54b822014-05-09 17:02:46 +0000232 case Instruction::ExtractValue:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000233 case Instruction::Load:
234 case Instruction::Add:
235 case Instruction::Sub:
236 case Instruction::And:
237 case Instruction::Or:
238 case Instruction::Xor:
239 case Instruction::Shl:
240 case Instruction::LShr:
241 case Instruction::AShr:
242 case Instruction::ICmp:
243 case Instruction::Trunc:
244 case Instruction::ZExt:
245 case Instruction::SExt:
Matt Arsenaultc8fc08c2014-05-30 18:34:43 +0000246 case Instruction::BitCast:
247 case Instruction::ExtractElement:
248 case Instruction::InsertElement:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000249 return 1; // These are all cheap.
250
251 case Instruction::Call:
252 case Instruction::Select:
253 return 2;
254 }
255}
256
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000257/// DominatesMergePoint - If we have a merge point of an "if condition" as
258/// accepted above, return true if the specified value dominates the block. We
259/// don't handle the true generality of domination here, just a special case
260/// which works well enough for us.
261///
262/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000263/// see if V (which must be an instruction) and its recursive operands
264/// that do not dominate BB have a combined cost lower than CostRemaining and
265/// are non-trapping. If both are true, the instruction is inserted into the
266/// set and true is returned.
267///
268/// The cost for most non-trapping instructions is defined as 1 except for
269/// Select whose cost is 2.
270///
271/// After this function returns, CostRemaining is decreased by the cost of
272/// V plus its non-dominating operands. If that cost is greater than
273/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000274static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000275 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000276 unsigned &CostRemaining,
277 const DataLayout *DL) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000278 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000279 if (!I) {
280 // Non-instructions all dominate instructions, but not all constantexprs
281 // can be executed unconditionally.
282 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
283 if (C->canTrap())
284 return false;
285 return true;
286 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000287 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000288
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000289 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000290 // the bottom of this block.
291 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000292
Chris Lattner0aa56562004-04-09 22:50:22 +0000293 // If this instruction is defined in a block that contains an unconditional
294 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000295 // statement". If not, it definitely dominates the region.
296 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000297 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000298 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000299
Chris Lattner9ac168d2010-12-14 07:41:39 +0000300 // If we aren't allowing aggressive promotion anymore, then don't consider
301 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000303
Peter Collingbournee3511e12011-04-29 18:47:31 +0000304 // If we have seen this instruction before, don't count it again.
305 if (AggressiveInsts->count(I)) return true;
306
Chris Lattner9ac168d2010-12-14 07:41:39 +0000307 // Okay, it looks like the instruction IS in the "condition". Check to
308 // see if it's a cheap instruction to unconditionally compute, and if it
309 // only uses stuff defined outside of the condition. If so, hoist it out.
Hal Finkela995f922014-07-10 14:41:31 +0000310 if (!isSafeToSpeculativelyExecute(I, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000311 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000312
Hal Finkela995f922014-07-10 14:41:31 +0000313 unsigned Cost = ComputeSpeculationCost(I, DL);
Chris Lattner0aa56562004-04-09 22:50:22 +0000314
Peter Collingbournee3511e12011-04-29 18:47:31 +0000315 if (Cost > CostRemaining)
316 return false;
317
318 CostRemaining -= Cost;
319
320 // Okay, we can only really hoist these out if their operands do
321 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000322 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Hal Finkela995f922014-07-10 14:41:31 +0000323 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000324 return false;
325 // Okay, it's safe to do this! Remember this instruction.
326 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000327 return true;
328}
Chris Lattner466a0492002-05-21 20:50:24 +0000329
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000330/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
331/// and PointerNullValue. Return NULL if value is not a constant int.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000332static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000333 // Normal constant int.
334 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000335 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000336 return CI;
337
338 // This is some kind of pointer constant. Turn it into a pointer-sized
339 // ConstantInt if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000340 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000341
342 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
343 if (isa<ConstantPointerNull>(V))
344 return ConstantInt::get(PtrTy, 0);
345
346 // IntToPtr const int.
347 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
348 if (CE->getOpcode() == Instruction::IntToPtr)
349 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
350 // The constant is very likely to have the right type already.
351 if (CI->getType() == PtrTy)
352 return CI;
353 else
354 return cast<ConstantInt>
355 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
356 }
Craig Topperf40110f2014-04-25 05:29:35 +0000357 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000358}
359
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000360
361
362// Try to match Instruction I as a comparison against a constant and populates
363// Vals with the set of value that match (or does not depending on isEQ).
364// Return nullptr on failure, or return the Value the comparison matched against
365// on success
366// CurrValue, if supplied, is the value we want to match against. The function
367// is expected to fail if a match is found but the value compared to is not the
368// one expected. If CurrValue is supplied, the return value has to be either
369// nullptr or CurrValue
370static Value* GatherConstantComparesMatch(Instruction *I,
371 Value *CurrValue,
372 SmallVectorImpl<ConstantInt*> &Vals,
373 const DataLayout *DL,
374 unsigned &UsedICmps,
375 bool isEQ) {
376
377 // If this is an icmp against a constant, handle this as one of the cases.
378 ICmpInst *ICI;
379 ConstantInt *C;
380 if (not ((ICI = dyn_cast<ICmpInst>(I)) &&
381 (C = GetConstantInt(I->getOperand(1), DL)))) {
382 return nullptr;
383 }
384
385 Value *RHSVal;
386 ConstantInt *RHSC;
387
388 // Pattern match a special case
389 // (x & ~2^x) == y --> x == y || x == y|2^x
390 // This undoes a transformation done by instcombine to fuse 2 compares.
391 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
392 if (match(ICI->getOperand(0),
393 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
394 APInt Not = ~RHSC->getValue();
395 if (Not.isPowerOf2()) {
396 // If we already have a value for the switch, it has to match!
397 if(CurrValue && CurrValue != RHSVal)
398 return nullptr;
399
400 Vals.push_back(C);
401 Vals.push_back(ConstantInt::get(C->getContext(),
402 C->getValue() | Not));
403 UsedICmps++;
404 return RHSVal;
405 }
406 }
407
408 // If we already have a value for the switch, it has to match!
409 if(CurrValue && CurrValue != ICI->getOperand(0))
410 return nullptr;
411
412 UsedICmps++;
413 Vals.push_back(C);
414 return ICI->getOperand(0);
415 }
416
417 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
418 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
419 C->getValue());
420
421 // Shift the range if the compare is fed by an add. This is the range
422 // compare idiom as emitted by instcombine.
423 Value *CandidateVal = I->getOperand(0);
424 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
425 Span = Span.subtract(RHSC->getValue());
426 CandidateVal = RHSVal;
427 }
428
429 // If we already have a value for the switch, it has to match!
430 if(CurrValue && CurrValue != CandidateVal)
431 return nullptr;
432
433 // If this is an and/!= check, then we are looking to build the set of
434 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
435 // x != 0 && x != 1.
436 if (!isEQ)
437 Span = Span.inverse();
438
439 // If there are a ton of values, we don't want to make a ginormous switch.
440 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
441 return nullptr;
442 }
443
444 // Add all values from the range to the set
445 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
446 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
447
448 UsedICmps++;
449 return CandidateVal;
450
451}
452
Chris Lattner5a177e62010-12-13 04:26:26 +0000453/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
454/// collection of icmp eq/ne instructions that compare a value against a
455/// constant, return the value being compared, and stick the constant into the
456/// Values vector.
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000457/// One "Extra" case is allowed to differ from the other.
Chris Lattner11dafaa2010-12-13 03:30:12 +0000458static Value *
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000459GatherConstantCompares(Value *V, SmallVectorImpl<ConstantInt*> &Vals, Value *&Extra,
460 const DataLayout *DL, unsigned &UsedICmps) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000461 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000462 if (!I) return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000463
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000464 bool isEQ = (I->getOpcode() == Instruction::Or);
Benjamin Kramer37172222013-07-04 14:22:02 +0000465
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000466 // Keep a stack (SmallVector for efficiency) for depth-first traversal
467 SmallVector<Value *, 8> DFT;
Benjamin Kramer37172222013-07-04 14:22:02 +0000468
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000469 // Initialize
470 DFT.push_back(V);
471
472 // Will hold the value used for the switch comparison
473 Value *CurrValue = nullptr;
474
475 while(not DFT.empty()) {
476 V = DFT.pop_back_val();
477
478 if (Instruction *I = dyn_cast<Instruction>(V)) {
479
480 // If it is a || (or && depending on isEQ), process the operands.
481 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
482 DFT.push_back(I->getOperand(1));
483 DFT.push_back(I->getOperand(0));
484 continue;
Chris Lattner5a177e62010-12-13 04:26:26 +0000485 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000486
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000487 // Try to match the current instruction
488 if (Value *Matched = GatherConstantComparesMatch(I,
489 CurrValue,
490 Vals,
491 DL,
492 UsedICmps,
493 isEQ)) {
494 // Match succeed, continue the loop
495 CurrValue = Matched;
496 continue;
497 }
Chris Lattner5a177e62010-12-13 04:26:26 +0000498 }
Chris Lattnera442f242010-12-13 04:50:38 +0000499
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000500 // One element of the sequence of || (or &&) could not be match as a
501 // comparison against the same value as the others.
502 // We allow only one "Extra" case to be checked before the switch
503 if (Extra == nullptr) {
504 Extra = V;
505 continue;
Chris Lattnera442f242010-12-13 04:50:38 +0000506 }
Craig Topperf40110f2014-04-25 05:29:35 +0000507 return nullptr;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000508
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000509 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000510
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000511 // Return the value to be used for the switch comparison (if any)
512 return CurrValue;
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000513}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000514
Eli Friedmancb61afb2008-12-16 20:54:32 +0000515static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000516 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000517 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
518 Cond = dyn_cast<Instruction>(SI->getCondition());
519 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
520 if (BI->isConditional())
521 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000522 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
523 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000524 }
525
526 TI->eraseFromParent();
527 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
528}
529
Chris Lattner8e84c122008-11-27 23:25:44 +0000530/// isValueEqualityComparison - Return true if the specified terminator checks
531/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000532Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000533 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000534 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
535 // Do not permit merging of large switch instructions into their
536 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000537 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
538 pred_end(SI->getParent())) <= 128)
539 CV = SI->getCondition();
540 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000541 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000542 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000543 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000544 CV = ICI->getOperand(0);
545
546 // Unwrap any lossless ptrtoint cast.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000547 if (DL && CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000548 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
549 Value *Ptr = PTII->getPointerOperand();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000550 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000551 CV = Ptr;
552 }
553 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000554 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000555}
556
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000557/// GetValueEqualityComparisonCases - Given a value comparison instruction,
558/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000559BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000560GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000561 std::vector<ValueEqualityComparisonCase>
562 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000563 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000564 Cases.reserve(SI->getNumCases());
565 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
566 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
567 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000568 return SI->getDefaultDest();
569 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000570
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000571 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000572 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000573 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
574 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000575 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000576 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000577 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000578}
579
Eric Christopherb65acc62012-07-02 23:22:21 +0000580
581/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
582/// in the list that match the specified block.
583static void EliminateBlockCases(BasicBlock *BB,
584 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000585 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000586}
587
588/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
589/// well.
590static bool
591ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
592 std::vector<ValueEqualityComparisonCase > &C2) {
593 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
594
595 // Make V1 be smaller than V2.
596 if (V1->size() > V2->size())
597 std::swap(V1, V2);
598
599 if (V1->size() == 0) return false;
600 if (V1->size() == 1) {
601 // Just scan V2.
602 ConstantInt *TheVal = (*V1)[0].Value;
603 for (unsigned i = 0, e = V2->size(); i != e; ++i)
604 if (TheVal == (*V2)[i].Value)
605 return true;
606 }
607
608 // Otherwise, just sort both lists and compare element by element.
609 array_pod_sort(V1->begin(), V1->end());
610 array_pod_sort(V2->begin(), V2->end());
611 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
612 while (i1 != e1 && i2 != e2) {
613 if ((*V1)[i1].Value == (*V2)[i2].Value)
614 return true;
615 if ((*V1)[i1].Value < (*V2)[i2].Value)
616 ++i1;
617 else
618 ++i2;
619 }
620 return false;
621}
622
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000623/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
624/// terminator instruction and its block is known to only have a single
625/// predecessor block, check to see if that predecessor is also a value
626/// comparison with the same value, and if that comparison determines the
627/// outcome of this comparison. If so, simplify TI. This does a very limited
628/// form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000629bool SimplifyCFGOpt::
630SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000631 BasicBlock *Pred,
632 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000633 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
634 if (!PredVal) return false; // Not a value comparison in predecessor.
635
636 Value *ThisVal = isValueEqualityComparison(TI);
637 assert(ThisVal && "This isn't a value comparison!!");
638 if (ThisVal != PredVal) return false; // Different predicates.
639
Andrew Trick3051aa12012-08-29 21:46:38 +0000640 // TODO: Preserve branch weight metadata, similarly to how
641 // FoldValueComparisonIntoPredecessors preserves it.
642
Chris Lattner1cca9592005-02-24 06:17:52 +0000643 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000644 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000645 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
646 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000647 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000648
Chris Lattner1cca9592005-02-24 06:17:52 +0000649 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000650 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000651 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000652 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000653
654 // If TI's block is the default block from Pred's comparison, potentially
655 // simplify TI based on this knowledge.
656 if (PredDef == TI->getParent()) {
657 // If we are here, we know that the value is none of those cases listed in
658 // PredCases. If there are any cases in ThisCases that are in PredCases, we
659 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000660 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000661 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000662
Chris Lattner4088e2b2010-12-13 01:47:07 +0000663 if (isa<BranchInst>(TI)) {
664 // Okay, one of the successors of this condbr is dead. Convert it to a
665 // uncond br.
666 assert(ThisCases.size() == 1 && "Branch can only have one case!");
667 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000668 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000669 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000670
Chris Lattner4088e2b2010-12-13 01:47:07 +0000671 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000672 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000673
Chris Lattner4088e2b2010-12-13 01:47:07 +0000674 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
675 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000676
Chris Lattner4088e2b2010-12-13 01:47:07 +0000677 EraseTerminatorInstAndDCECond(TI);
678 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000679 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000680
Chris Lattner4088e2b2010-12-13 01:47:07 +0000681 SwitchInst *SI = cast<SwitchInst>(TI);
682 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000683 SmallPtrSet<Constant*, 16> DeadCases;
684 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
685 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000686
David Greene725c7c32010-01-05 01:26:52 +0000687 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000688 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000689
Manman Ren8691e522012-09-14 21:53:06 +0000690 // Collect branch weights into a vector.
691 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000692 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000693 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
694 if (HasWeight)
695 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
696 ++MD_i) {
697 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
698 assert(CI);
699 Weights.push_back(CI->getValue().getZExtValue());
700 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000701 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
702 --i;
703 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000704 if (HasWeight) {
705 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
706 Weights.pop_back();
707 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000708 i.getCaseSuccessor()->removePredecessor(TI->getParent());
709 SI->removeCase(i);
710 }
711 }
Manman Ren97c18762012-10-11 22:28:34 +0000712 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000713 SI->setMetadata(LLVMContext::MD_prof,
714 MDBuilder(SI->getParent()->getContext()).
715 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000716
717 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000718 return true;
719 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000720
Chris Lattner4088e2b2010-12-13 01:47:07 +0000721 // Otherwise, TI's block must correspond to some matched value. Find out
722 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000723 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000724 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000725 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
726 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000727 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000728 return false; // Cannot handle multiple values coming to this block.
729 TIV = PredCases[i].Value;
730 }
731 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000732
733 // Okay, we found the one constant that our value can be if we get into TI's
734 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000735 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000736 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
737 if (ThisCases[i].Value == TIV) {
738 TheRealDest = ThisCases[i].Dest;
739 break;
740 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000741
742 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000743 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000744
745 // Remove PHI node entries for dead edges.
746 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000747 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
748 if (*SI != CheckEdge)
749 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000750 else
Craig Topperf40110f2014-04-25 05:29:35 +0000751 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000752
753 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000754 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000755 (void) NI;
756
757 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
758 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
759
760 EraseTerminatorInstAndDCECond(TI);
761 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000762}
763
Dale Johannesen7f99d222009-03-12 21:01:11 +0000764namespace {
765 /// ConstantIntOrdering - This class implements a stable ordering of constant
766 /// integers that does not depend on their address. This is important for
767 /// applications that sort ConstantInt's to ensure uniqueness.
768 struct ConstantIntOrdering {
769 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
770 return LHS->getValue().ult(RHS->getValue());
771 }
772 };
773}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000774
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000775static int ConstantIntSortPredicate(ConstantInt *const *P1,
776 ConstantInt *const *P2) {
777 const ConstantInt *LHS = *P1;
778 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000779 if (LHS->getValue().ult(RHS->getValue()))
780 return 1;
781 if (LHS->getValue() == RHS->getValue())
782 return 0;
783 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000784}
785
Andrew Trick3051aa12012-08-29 21:46:38 +0000786static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000787 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000788 if (ProfMD && ProfMD->getOperand(0))
789 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
790 return MDS->getString().equals("branch_weights");
791
792 return false;
793}
794
Manman Ren571d9e42012-09-11 17:43:35 +0000795/// Get Weights of a given TerminatorInst, the default weight is at the front
796/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
797/// metadata.
798static void GetBranchWeights(TerminatorInst *TI,
799 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000800 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000801 assert(MD);
802 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000803 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000804 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000805 }
806
Manman Ren571d9e42012-09-11 17:43:35 +0000807 // If TI is a conditional eq, the default case is the false case,
808 // and the corresponding branch-weight data is at index 2. We swap the
809 // default weight to be the first entry.
810 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
811 assert(Weights.size() == 2);
812 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
813 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
814 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000815 }
816}
817
Manman Renf1cb16e2014-01-27 23:39:03 +0000818/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000819static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000820 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
821 if (Max > UINT_MAX) {
822 unsigned Offset = 32 - countLeadingZeros(Max);
823 for (uint64_t &I : Weights)
824 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000825 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000826}
827
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000828/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
829/// equality comparison instruction (either a switch or a branch on "X == c").
830/// See if any of the predecessors of the terminator block are value comparisons
831/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000832bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
833 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000834 BasicBlock *BB = TI->getParent();
835 Value *CV = isValueEqualityComparison(TI); // CondVal
836 assert(CV && "Not a comparison?");
837 bool Changed = false;
838
Chris Lattner6b39cb92008-02-18 07:42:56 +0000839 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000840 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000841 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000842
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000843 // See if the predecessor is a comparison with the same value.
844 TerminatorInst *PTI = Pred->getTerminator();
845 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
846
847 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
848 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000849 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000850 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
851
Eric Christopherb65acc62012-07-02 23:22:21 +0000852 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000853 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
854
855 // Based on whether the default edge from PTI goes to BB or not, fill in
856 // PredCases and PredDefault with the new switch cases we would like to
857 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000858 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000859
Andrew Trick3051aa12012-08-29 21:46:38 +0000860 // Update the branch weight metadata along the way
861 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000862 bool PredHasWeights = HasBranchWeights(PTI);
863 bool SuccHasWeights = HasBranchWeights(TI);
864
Manman Ren5e5049d2012-09-14 19:05:19 +0000865 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000866 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000867 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000868 if (Weights.size() != 1 + PredCases.size())
869 PredHasWeights = SuccHasWeights = false;
870 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000871 // If there are no predecessor weights but there are successor weights,
872 // populate Weights with 1, which will later be scaled to the sum of
873 // successor's weights
874 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000875
Manman Ren571d9e42012-09-11 17:43:35 +0000876 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000877 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000878 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000879 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000880 if (SuccWeights.size() != 1 + BBCases.size())
881 PredHasWeights = SuccHasWeights = false;
882 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000883 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000884
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000885 if (PredDefault == BB) {
886 // If this is the default destination from PTI, only the edges in TI
887 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000888 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
889 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
890 if (PredCases[i].Dest != BB)
891 PTIHandled.insert(PredCases[i].Value);
892 else {
893 // The default destination is BB, we don't need explicit targets.
894 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000895
Manman Ren571d9e42012-09-11 17:43:35 +0000896 if (PredHasWeights || SuccHasWeights) {
897 // Increase weight for the default case.
898 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000899 std::swap(Weights[i+1], Weights.back());
900 Weights.pop_back();
901 }
902
Eric Christopherb65acc62012-07-02 23:22:21 +0000903 PredCases.pop_back();
904 --i; --e;
905 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000906
Eric Christopherb65acc62012-07-02 23:22:21 +0000907 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000908 if (PredDefault != BBDefault) {
909 PredDefault->removePredecessor(Pred);
910 PredDefault = BBDefault;
911 NewSuccessors.push_back(BBDefault);
912 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000913
Manman Ren571d9e42012-09-11 17:43:35 +0000914 unsigned CasesFromPred = Weights.size();
915 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000916 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
917 if (!PTIHandled.count(BBCases[i].Value) &&
918 BBCases[i].Dest != BBDefault) {
919 PredCases.push_back(BBCases[i]);
920 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000921 if (SuccHasWeights || PredHasWeights) {
922 // The default weight is at index 0, so weight for the ith case
923 // should be at index i+1. Scale the cases from successor by
924 // PredDefaultWeight (Weights[0]).
925 Weights.push_back(Weights[0] * SuccWeights[i+1]);
926 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000927 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000928 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000929
Manman Ren571d9e42012-09-11 17:43:35 +0000930 if (SuccHasWeights || PredHasWeights) {
931 ValidTotalSuccWeight += SuccWeights[0];
932 // Scale the cases from predecessor by ValidTotalSuccWeight.
933 for (unsigned i = 1; i < CasesFromPred; ++i)
934 Weights[i] *= ValidTotalSuccWeight;
935 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
936 Weights[0] *= SuccWeights[0];
937 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000938 } else {
939 // If this is not the default destination from PSI, only the edges
940 // in SI that occur in PSI with a destination of BB will be
941 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000942 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000943 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000944 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
945 if (PredCases[i].Dest == BB) {
946 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000947
948 if (PredHasWeights || SuccHasWeights) {
949 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
950 std::swap(Weights[i+1], Weights.back());
951 Weights.pop_back();
952 }
953
Eric Christopherb65acc62012-07-02 23:22:21 +0000954 std::swap(PredCases[i], PredCases.back());
955 PredCases.pop_back();
956 --i; --e;
957 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000958
959 // Okay, now we know which constants were sent to BB from the
960 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000961 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
962 if (PTIHandled.count(BBCases[i].Value)) {
963 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000964 if (PredHasWeights || SuccHasWeights)
965 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000966 PredCases.push_back(BBCases[i]);
967 NewSuccessors.push_back(BBCases[i].Dest);
968 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
969 }
970
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000971 // If there are any constants vectored to BB that TI doesn't handle,
972 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000973 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000974 PTIHandled.begin(),
975 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000976 if (PredHasWeights || SuccHasWeights)
977 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000978 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000979 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000980 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000981 }
982
983 // Okay, at this point, we know which new successor Pred will get. Make
984 // sure we update the number of entries in the PHI nodes for these
985 // successors.
986 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
987 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
988
Devang Patel58380552011-05-18 20:53:17 +0000989 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000990 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000991 if (CV->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000992 assert(DL && "Cannot switch on pointer without DataLayout");
993 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000994 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000995 }
996
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000997 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000998 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
999 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001000 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +00001001 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1002 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001003
Andrew Trick3051aa12012-08-29 21:46:38 +00001004 if (PredHasWeights || SuccHasWeights) {
1005 // Halve the weights if any of them cannot fit in an uint32_t
1006 FitWeights(Weights);
1007
1008 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1009
1010 NewSI->setMetadata(LLVMContext::MD_prof,
1011 MDBuilder(BB->getContext()).
1012 createBranchWeights(MDWeights));
1013 }
1014
Eli Friedmancb61afb2008-12-16 20:54:32 +00001015 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001016
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001017 // Okay, last check. If BB is still a successor of PSI, then we must
1018 // have an infinite loop case. If so, add an infinitely looping block
1019 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001020 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001021 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1022 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001023 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001024 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001025 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001026 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1027 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001028 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001029 }
1030 NewSI->setSuccessor(i, InfLoopBlock);
1031 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001032
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001033 Changed = true;
1034 }
1035 }
1036 return Changed;
1037}
1038
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001039// isSafeToHoistInvoke - If we would need to insert a select that uses the
1040// value of this invoke (comments in HoistThenElseCodeToIf explain why we
1041// would need to do this), we can't hoist the invoke, as there is nowhere
1042// to put the select in this case.
1043static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1044 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001045 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001046 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001047 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001048 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1049 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1050 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1051 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1052 return false;
1053 }
1054 }
1055 }
1056 return true;
1057}
1058
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001059static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1060
Chris Lattnerd683bdd2005-08-03 17:59:45 +00001061/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +00001062/// BB2, hoist any common code in the two blocks up into the branch block. The
1063/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Hal Finkela995f922014-07-10 14:41:31 +00001064static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001065 // This does very trivial matching, with limited scanning, to find identical
1066 // instructions in the two blocks. In particular, we don't want to get into
1067 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1068 // such, we currently just scan for obviously identical instructions in an
1069 // identical order.
1070 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1071 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1072
Devang Patelf10e2872009-02-04 00:03:08 +00001073 BasicBlock::iterator BB1_Itr = BB1->begin();
1074 BasicBlock::iterator BB2_Itr = BB2->begin();
1075
1076 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001077 // Skip debug info if it is not identical.
1078 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1079 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1080 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1081 while (isa<DbgInfoIntrinsic>(I1))
1082 I1 = BB1_Itr++;
1083 while (isa<DbgInfoIntrinsic>(I2))
1084 I2 = BB2_Itr++;
1085 }
Devang Patele48ddf82011-04-07 00:30:15 +00001086 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001087 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001088 return false;
1089
Chris Lattner389cfac2004-11-30 00:29:14 +00001090 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001091
David Majnemerc82f27a2013-06-03 20:43:12 +00001092 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001093 do {
1094 // If we are hoisting the terminator instruction, don't move one (making a
1095 // broken BB), instead clone it, and remove BI.
1096 if (isa<TerminatorInst>(I1))
1097 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001098
Chris Lattner389cfac2004-11-30 00:29:14 +00001099 // For a normal instruction, we just move one to right before the branch,
1100 // then replace all uses of the other with the first. Finally, we remove
1101 // the now redundant second instruction.
1102 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1103 if (!I2->use_empty())
1104 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001105 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001106 unsigned KnownIDs[] = {
1107 LLVMContext::MD_tbaa,
1108 LLVMContext::MD_range,
1109 LLVMContext::MD_fpmath,
Philip Reamesd92c2a72014-10-22 16:37:13 +00001110 LLVMContext::MD_invariant_load,
1111 LLVMContext::MD_nonnull
Rafael Espindolaea46c322014-08-15 15:46:38 +00001112 };
1113 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001114 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001115 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001116
Devang Patelf10e2872009-02-04 00:03:08 +00001117 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001118 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001119 // Skip debug info if it is not identical.
1120 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1121 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1122 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1123 while (isa<DbgInfoIntrinsic>(I1))
1124 I1 = BB1_Itr++;
1125 while (isa<DbgInfoIntrinsic>(I2))
1126 I2 = BB2_Itr++;
1127 }
Devang Patele48ddf82011-04-07 00:30:15 +00001128 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001129
1130 return true;
1131
1132HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001133 // It may not be possible to hoist an invoke.
1134 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001135 return Changed;
1136
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001137 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001138 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001139 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001140 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1141 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1142 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1143 if (BB1V == BB2V)
1144 continue;
1145
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001146 // Check for passingValueIsAlwaysUndefined here because we would rather
1147 // eliminate undefined control flow then converting it to a select.
1148 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1149 passingValueIsAlwaysUndefined(BB2V, PN))
1150 return Changed;
1151
Hal Finkela995f922014-07-10 14:41:31 +00001152 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001153 return Changed;
Hal Finkela995f922014-07-10 14:41:31 +00001154 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001155 return Changed;
1156 }
1157 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001158
Chris Lattner389cfac2004-11-30 00:29:14 +00001159 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001160 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001161 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001162 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001163 I1->replaceAllUsesWith(NT);
1164 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001165 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001166 }
1167
Devang Patel1407fb42011-05-19 20:52:46 +00001168 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001169 // Hoisting one of the terminators from our successor is a great thing.
1170 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1171 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1172 // nodes, so we insert select instruction to compute the final result.
1173 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001174 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001175 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001176 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001177 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001178 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1179 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001180 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001181
Chris Lattner4088e2b2010-12-13 01:47:07 +00001182 // These values do not agree. Insert a select instruction before NT
1183 // that determines the right value.
1184 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001185 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001186 SI = cast<SelectInst>
1187 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1188 BB1V->getName()+"."+BB2V->getName()));
1189
Chris Lattner4088e2b2010-12-13 01:47:07 +00001190 // Make the PHI node use the select for all incoming values for BB1/BB2
1191 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1192 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1193 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001194 }
1195 }
1196
1197 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001198 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1199 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001200
Eli Friedmancb61afb2008-12-16 20:54:32 +00001201 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001202 return true;
1203}
1204
Manman Ren93ab6492012-09-20 22:37:36 +00001205/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1206/// check whether BBEnd has only two predecessors and the other predecessor
1207/// ends with an unconditional branch. If it is true, sink any common code
1208/// in the two predecessors to BBEnd.
1209static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1210 assert(BI1->isUnconditional());
1211 BasicBlock *BB1 = BI1->getParent();
1212 BasicBlock *BBEnd = BI1->getSuccessor(0);
1213
1214 // Check that BBEnd has two predecessors and the other predecessor ends with
1215 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001216 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1217 BasicBlock *Pred0 = *PI++;
1218 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001219 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001220 BasicBlock *Pred1 = *PI++;
1221 if (PI != PE) // More than two predecessors.
1222 return false;
1223 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001224 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1225 if (!BI2 || !BI2->isUnconditional())
1226 return false;
1227
1228 // Gather the PHI nodes in BBEnd.
1229 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
Craig Topperf40110f2014-04-25 05:29:35 +00001230 Instruction *FirstNonPhiInBBEnd = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001231 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1232 I != E; ++I) {
1233 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1234 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001235 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Manman Ren93ab6492012-09-20 22:37:36 +00001236 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1237 } else {
1238 FirstNonPhiInBBEnd = &*I;
1239 break;
1240 }
1241 }
1242 if (!FirstNonPhiInBBEnd)
1243 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001244
Manman Ren93ab6492012-09-20 22:37:36 +00001245
1246 // This does very trivial matching, with limited scanning, to find identical
1247 // instructions in the two blocks. We scan backward for obviously identical
1248 // instructions in an identical order.
1249 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1250 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1251 RE2 = BB2->getInstList().rend();
1252 // Skip debug info.
1253 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1254 if (RI1 == RE1)
1255 return false;
1256 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1257 if (RI2 == RE2)
1258 return false;
1259 // Skip the unconditional branches.
1260 ++RI1;
1261 ++RI2;
1262
1263 bool Changed = false;
1264 while (RI1 != RE1 && RI2 != RE2) {
1265 // Skip debug info.
1266 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1267 if (RI1 == RE1)
1268 return Changed;
1269 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1270 if (RI2 == RE2)
1271 return Changed;
1272
1273 Instruction *I1 = &*RI1, *I2 = &*RI2;
1274 // I1 and I2 should have a single use in the same PHI node, and they
1275 // perform the same operation.
1276 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1277 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1278 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1279 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1280 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1281 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1282 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1283 !I1->hasOneUse() || !I2->hasOneUse() ||
1284 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1285 MapValueFromBB1ToBB2[I1].first != I2)
1286 return Changed;
1287
1288 // Check whether we should swap the operands of ICmpInst.
1289 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1290 bool SwapOpnds = false;
1291 if (ICmp1 && ICmp2 &&
1292 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1293 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1294 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1295 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1296 ICmp2->swapOperands();
1297 SwapOpnds = true;
1298 }
1299 if (!I1->isSameOperationAs(I2)) {
1300 if (SwapOpnds)
1301 ICmp2->swapOperands();
1302 return Changed;
1303 }
1304
1305 // The operands should be either the same or they need to be generated
1306 // with a PHI node after sinking. We only handle the case where there is
1307 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001308 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001309 unsigned Op1Idx = 0;
1310 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1311 if (I1->getOperand(I) == I2->getOperand(I))
1312 continue;
1313 // Early exit if we have more-than one pair of different operands or
1314 // the different operand is already in MapValueFromBB1ToBB2.
1315 // Early exit if we need a PHI node to replace a constant.
1316 if (DifferentOp1 ||
1317 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1318 MapValueFromBB1ToBB2.end() ||
1319 isa<Constant>(I1->getOperand(I)) ||
1320 isa<Constant>(I2->getOperand(I))) {
1321 // If we can't sink the instructions, undo the swapping.
1322 if (SwapOpnds)
1323 ICmp2->swapOperands();
1324 return Changed;
1325 }
1326 DifferentOp1 = I1->getOperand(I);
1327 Op1Idx = I;
1328 DifferentOp2 = I2->getOperand(I);
1329 }
1330
1331 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1332 // remove (I1, I2) from MapValueFromBB1ToBB2.
1333 if (DifferentOp1) {
1334 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1335 DifferentOp1->getName() + ".sink",
1336 BBEnd->begin());
1337 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1338 // I1 should use NewPN instead of DifferentOp1.
1339 I1->setOperand(Op1Idx, NewPN);
1340 NewPN->addIncoming(DifferentOp1, BB1);
1341 NewPN->addIncoming(DifferentOp2, BB2);
1342 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1343 }
1344 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1345 MapValueFromBB1ToBB2.erase(I1);
1346
1347 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1348 DEBUG(dbgs() << " " << *I2 << "\n";);
1349 // We need to update RE1 and RE2 if we are going to sink the first
1350 // instruction in the basic block down.
1351 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1352 // Sink the instruction.
1353 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1354 if (!OldPN->use_empty())
1355 OldPN->replaceAllUsesWith(I1);
1356 OldPN->eraseFromParent();
1357
1358 if (!I2->use_empty())
1359 I2->replaceAllUsesWith(I1);
1360 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001361 // TODO: Use combineMetadata here to preserve what metadata we can
1362 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001363 I2->eraseFromParent();
1364
1365 if (UpdateRE1)
1366 RE1 = BB1->getInstList().rend();
1367 if (UpdateRE2)
1368 RE2 = BB2->getInstList().rend();
1369 FirstNonPhiInBBEnd = I1;
1370 NumSinkCommons++;
1371 Changed = true;
1372 }
1373 return Changed;
1374}
1375
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001376/// \brief Determine if we can hoist sink a sole store instruction out of a
1377/// conditional block.
1378///
1379/// We are looking for code like the following:
1380/// BrBB:
1381/// store i32 %add, i32* %arrayidx2
1382/// ... // No other stores or function calls (we could be calling a memory
1383/// ... // function).
1384/// %cmp = icmp ult %x, %y
1385/// br i1 %cmp, label %EndBB, label %ThenBB
1386/// ThenBB:
1387/// store i32 %add5, i32* %arrayidx2
1388/// br label EndBB
1389/// EndBB:
1390/// ...
1391/// We are going to transform this into:
1392/// BrBB:
1393/// store i32 %add, i32* %arrayidx2
1394/// ... //
1395/// %cmp = icmp ult %x, %y
1396/// %add.add5 = select i1 %cmp, i32 %add, %add5
1397/// store i32 %add.add5, i32* %arrayidx2
1398/// ...
1399///
1400/// \return The pointer to the value of the previous store if the store can be
1401/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001402static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1403 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001404 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1405 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001406 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001407
1408 // Volatile or atomic.
1409 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001410 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001411
1412 Value *StorePtr = StoreToHoist->getPointerOperand();
1413
1414 // Look for a store to the same pointer in BrBB.
1415 unsigned MaxNumInstToLookAt = 10;
1416 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1417 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1418 Instruction *CurI = &*RI;
1419
1420 // Could be calling an instruction that effects memory like free().
1421 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001422 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001423
1424 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1425 // Found the previous store make sure it stores to the same location.
1426 if (SI && SI->getPointerOperand() == StorePtr)
1427 // Found the previous store, return its value operand.
1428 return SI->getValueOperand();
1429 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001430 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001431 }
1432
Craig Topperf40110f2014-04-25 05:29:35 +00001433 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001434}
1435
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001436/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001437///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001438/// Note that this is a very risky transform currently. Speculating
1439/// instructions like this is most often not desirable. Instead, there is an MI
1440/// pass which can do it with full awareness of the resource constraints.
1441/// However, some cases are "obvious" and we should do directly. An example of
1442/// this is speculating a single, reasonably cheap instruction.
1443///
1444/// There is only one distinct advantage to flattening the CFG at the IR level:
1445/// it makes very common but simplistic optimizations such as are common in
1446/// instcombine and the DAG combiner more powerful by removing CFG edges and
1447/// modeling their effects with easier to reason about SSA value graphs.
1448///
1449///
1450/// An illustration of this transform is turning this IR:
1451/// \code
1452/// BB:
1453/// %cmp = icmp ult %x, %y
1454/// br i1 %cmp, label %EndBB, label %ThenBB
1455/// ThenBB:
1456/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001457/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001458/// EndBB:
1459/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1460/// ...
1461/// \endcode
1462///
1463/// Into this IR:
1464/// \code
1465/// BB:
1466/// %cmp = icmp ult %x, %y
1467/// %sub = sub %x, %y
1468/// %cond = select i1 %cmp, 0, %sub
1469/// ...
1470/// \endcode
1471///
1472/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001473static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1474 const DataLayout *DL) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001475 // Be conservative for now. FP select instruction can often be expensive.
1476 Value *BrCond = BI->getCondition();
1477 if (isa<FCmpInst>(BrCond))
1478 return false;
1479
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001480 BasicBlock *BB = BI->getParent();
1481 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1482
1483 // If ThenBB is actually on the false edge of the conditional branch, remember
1484 // to swap the select operands later.
1485 bool Invert = false;
1486 if (ThenBB != BI->getSuccessor(0)) {
1487 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1488 Invert = true;
1489 }
1490 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1491
Chandler Carruthceff2222013-01-25 05:40:09 +00001492 // Keep a count of how many times instructions are used within CondBB when
1493 // they are candidates for sinking into CondBB. Specifically:
1494 // - They are defined in BB, and
1495 // - They have no side effects, and
1496 // - All of their uses are in CondBB.
1497 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1498
Chandler Carruth7481ca82013-01-24 11:52:58 +00001499 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001500 Value *SpeculatedStoreValue = nullptr;
1501 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001502 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001503 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001504 BBI != BBE; ++BBI) {
1505 Instruction *I = BBI;
1506 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001507 if (isa<DbgInfoIntrinsic>(I))
1508 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001509
Chandler Carruth7481ca82013-01-24 11:52:58 +00001510 // Only speculatively execution a single instruction (not counting the
1511 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001512 ++SpeculationCost;
1513 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001514 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001515
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001516 // Don't hoist the instruction if it's unsafe or expensive.
Hal Finkela995f922014-07-10 14:41:31 +00001517 if (!isSafeToSpeculativelyExecute(I, DL) &&
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001518 !(HoistCondStores &&
1519 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1520 EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001521 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001522 if (!SpeculatedStoreValue &&
Hal Finkela995f922014-07-10 14:41:31 +00001523 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001524 return false;
1525
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001526 // Store the store speculation candidate.
1527 if (SpeculatedStoreValue)
1528 SpeculatedStore = cast<StoreInst>(I);
1529
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001530 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001531 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001532 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001533 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001534 i != e; ++i) {
1535 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001536 if (!OpI || OpI->getParent() != BB ||
1537 OpI->mayHaveSideEffects())
1538 continue; // Not a candidate for sinking.
1539
1540 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001541 }
1542 }
Evan Cheng89200c92008-06-07 08:52:29 +00001543
Chandler Carruthceff2222013-01-25 05:40:09 +00001544 // Consider any sink candidates which are only used in CondBB as costs for
1545 // speculation. Note, while we iterate over a DenseMap here, we are summing
1546 // and so iteration order isn't significant.
1547 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1548 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1549 I != E; ++I)
1550 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001551 ++SpeculationCost;
1552 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001553 return false;
1554 }
1555
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001556 // Check that the PHI nodes can be converted to selects.
1557 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001558 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001559 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001560 Value *OrigV = PN->getIncomingValueForBlock(BB);
1561 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001562
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001563 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001564 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001565 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001566 continue;
1567
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001568 // Don't convert to selects if we could remove undefined behavior instead.
1569 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1570 passingValueIsAlwaysUndefined(ThenV, PN))
1571 return false;
1572
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001573 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001574 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1575 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1576 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001577 continue; // Known safe and cheap.
1578
Hal Finkela995f922014-07-10 14:41:31 +00001579 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1580 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001581 return false;
Hal Finkela995f922014-07-10 14:41:31 +00001582 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1583 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001584 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
Chandler Carruth8a210052013-01-24 11:53:01 +00001585 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001586
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001587 // Account for the cost of an unfolded ConstantExpr which could end up
1588 // getting expanded into Instructions.
1589 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001590 // constant expression.
1591 ++SpeculationCost;
1592 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001593 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001594 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001595
1596 // If there are no PHIs to process, bail early. This helps ensure idempotence
1597 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001598 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001599 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001600
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001601 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001602 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001603
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001604 // Insert a select of the value of the speculated store.
1605 if (SpeculatedStoreValue) {
1606 IRBuilder<true, NoFolder> Builder(BI);
1607 Value *TrueV = SpeculatedStore->getValueOperand();
1608 Value *FalseV = SpeculatedStoreValue;
1609 if (Invert)
1610 std::swap(TrueV, FalseV);
1611 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1612 "." + FalseV->getName());
1613 SpeculatedStore->setOperand(0, S);
1614 }
1615
Chandler Carruth7481ca82013-01-24 11:52:58 +00001616 // Hoist the instructions.
1617 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001618 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001619
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001620 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001621 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001622 for (BasicBlock::iterator I = EndBB->begin();
1623 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1624 unsigned OrigI = PN->getBasicBlockIndex(BB);
1625 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1626 Value *OrigV = PN->getIncomingValue(OrigI);
1627 Value *ThenV = PN->getIncomingValue(ThenI);
1628
1629 // Skip PHIs which are trivial.
1630 if (OrigV == ThenV)
1631 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001632
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001633 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001634 // false value is the preexisting value. Swap them if the branch
1635 // destinations were inverted.
1636 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001637 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001638 std::swap(TrueV, FalseV);
1639 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1640 TrueV->getName() + "." + FalseV->getName());
1641 PN->setIncomingValue(OrigI, V);
1642 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001643 }
1644
Evan Cheng89553cc2008-06-12 21:15:59 +00001645 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001646 return true;
1647}
1648
Tom Stellarde1631dd2013-10-21 20:07:30 +00001649/// \returns True if this block contains a CallInst with the NoDuplicate
1650/// attribute.
1651static bool HasNoDuplicateCall(const BasicBlock *BB) {
1652 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1653 const CallInst *CI = dyn_cast<CallInst>(I);
1654 if (!CI)
1655 continue;
1656 if (CI->cannotDuplicate())
1657 return true;
1658 }
1659 return false;
1660}
1661
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001662/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1663/// across this block.
1664static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1665 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001666 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001667
Devang Patel84fceff2009-03-10 18:00:05 +00001668 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001669 if (isa<DbgInfoIntrinsic>(BBI))
1670 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001671 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001672 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001673
Dale Johannesened6f5a82009-03-12 23:18:09 +00001674 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001675 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001676 for (User *U : BBI->users()) {
1677 Instruction *UI = cast<Instruction>(U);
1678 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001679 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001680
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001681 // Looks ok, continue checking.
1682 }
Chris Lattner6c701062005-09-20 01:48:40 +00001683
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001684 return true;
1685}
1686
Chris Lattner748f9032005-09-19 23:49:37 +00001687/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1688/// that is defined in the same block as the branch and if any PHI entries are
1689/// constants, thread edges corresponding to that entry to be branches to their
1690/// ultimate destination.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001691static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001692 BasicBlock *BB = BI->getParent();
1693 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001694 // NOTE: we currently cannot transform this case if the PHI node is used
1695 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001696 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1697 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001698
Chris Lattner748f9032005-09-19 23:49:37 +00001699 // Degenerate case of a single entry PHI.
1700 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001701 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001702 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001703 }
1704
1705 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001706 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001707
Tom Stellarde1631dd2013-10-21 20:07:30 +00001708 if (HasNoDuplicateCall(BB)) return false;
1709
Chris Lattner748f9032005-09-19 23:49:37 +00001710 // Okay, this is a simple enough basic block. See if any phi values are
1711 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001712 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001713 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001714 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001715
Chris Lattner4088e2b2010-12-13 01:47:07 +00001716 // Okay, we now know that all edges from PredBB should be revectored to
1717 // branch to RealDest.
1718 BasicBlock *PredBB = PN->getIncomingBlock(i);
1719 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001720
Chris Lattner4088e2b2010-12-13 01:47:07 +00001721 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001722 // Skip if the predecessor's terminator is an indirect branch.
1723 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001724
Chris Lattner4088e2b2010-12-13 01:47:07 +00001725 // The dest block might have PHI nodes, other predecessors and other
1726 // difficult cases. Instead of being smart about this, just insert a new
1727 // block that jumps to the destination block, effectively splitting
1728 // the edge we are about to create.
1729 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1730 RealDest->getName()+".critedge",
1731 RealDest->getParent(), RealDest);
1732 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001733
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001734 // Update PHI nodes.
1735 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001736
1737 // BB may have instructions that are being threaded over. Clone these
1738 // instructions into EdgeBB. We know that there will be no uses of the
1739 // cloned instructions outside of EdgeBB.
1740 BasicBlock::iterator InsertPt = EdgeBB->begin();
1741 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1742 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1743 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1744 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1745 continue;
1746 }
1747 // Clone the instruction.
1748 Instruction *N = BBI->clone();
1749 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001750
Chris Lattner4088e2b2010-12-13 01:47:07 +00001751 // Update operands due to translation.
1752 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1753 i != e; ++i) {
1754 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1755 if (PI != TranslateMap.end())
1756 *i = PI->second;
1757 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001758
Chris Lattner4088e2b2010-12-13 01:47:07 +00001759 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001760 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001761 TranslateMap[BBI] = V;
1762 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001763 } else {
1764 // Insert the new instruction into its new home.
1765 EdgeBB->getInstList().insert(InsertPt, N);
1766 if (!BBI->use_empty())
1767 TranslateMap[BBI] = N;
1768 }
1769 }
1770
1771 // Loop over all of the edges from PredBB to BB, changing them to branch
1772 // to EdgeBB instead.
1773 TerminatorInst *PredBBTI = PredBB->getTerminator();
1774 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1775 if (PredBBTI->getSuccessor(i) == BB) {
1776 BB->removePredecessor(PredBB);
1777 PredBBTI->setSuccessor(i, EdgeBB);
1778 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001779
Chris Lattner4088e2b2010-12-13 01:47:07 +00001780 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001781 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001782 }
Chris Lattner748f9032005-09-19 23:49:37 +00001783
1784 return false;
1785}
1786
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001787/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1788/// PHI node, see if we can eliminate it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001789static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001790 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1791 // statement", which has a very simple dominance structure. Basically, we
1792 // are trying to find the condition that is being branched on, which
1793 // subsequently causes this merge to happen. We really want control
1794 // dependence information for this check, but simplifycfg can't keep it up
1795 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001796 BasicBlock *BB = PN->getParent();
1797 BasicBlock *IfTrue, *IfFalse;
1798 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001799 if (!IfCond ||
1800 // Don't bother if the branch will be constant folded trivially.
1801 isa<ConstantInt>(IfCond))
1802 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001803
Chris Lattner95adf8f12006-11-18 19:19:36 +00001804 // Okay, we found that we can merge this two-entry phi node into a select.
1805 // Doing so would require us to fold *all* two entry phi nodes in this block.
1806 // At some point this becomes non-profitable (particularly if the target
1807 // doesn't support cmov's). Only do this transformation if there are two or
1808 // fewer PHI nodes in this block.
1809 unsigned NumPhis = 0;
1810 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1811 if (NumPhis > 2)
1812 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001813
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001814 // Loop over the PHI's seeing if we can promote them all to select
1815 // instructions. While we are at it, keep track of the instructions
1816 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001817 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001818 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1819 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001820
Chris Lattner7499b452010-12-14 08:46:09 +00001821 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1822 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001823 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001824 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001825 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001826 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001827 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001828
Peter Collingbournee3511e12011-04-29 18:47:31 +00001829 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001830 MaxCostVal0, DL) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001831 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001832 MaxCostVal1, DL))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001833 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001834 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001835
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001836 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001837 // we ran out of PHIs then we simplified them all.
1838 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001839 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001840
Chris Lattner7499b452010-12-14 08:46:09 +00001841 // Don't fold i1 branches on PHIs which contain binary operators. These can
1842 // often be turned into switches and other things.
1843 if (PN->getType()->isIntegerTy(1) &&
1844 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1845 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1846 isa<BinaryOperator>(IfCond)))
1847 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001848
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001849 // If we all PHI nodes are promotable, check to make sure that all
1850 // instructions in the predecessor blocks can be promoted as well. If
1851 // not, we won't be able to get rid of the control flow, so it's not
1852 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001853 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001854 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1855 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1856 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001857 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001858 } else {
1859 DomBlock = *pred_begin(IfBlock1);
1860 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001861 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001862 // This is not an aggressive instruction that we can promote.
1863 // Because of this, we won't be able to get rid of the control
1864 // flow, so the xform is not worth it.
1865 return false;
1866 }
1867 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001868
Chris Lattner9ac168d2010-12-14 07:41:39 +00001869 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001870 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001871 } else {
1872 DomBlock = *pred_begin(IfBlock2);
1873 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001874 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001875 // This is not an aggressive instruction that we can promote.
1876 // Because of this, we won't be able to get rid of the control
1877 // flow, so the xform is not worth it.
1878 return false;
1879 }
1880 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001881
Chris Lattner9fd838d2010-12-14 07:23:10 +00001882 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001883 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001884
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001885 // If we can still promote the PHI nodes after this gauntlet of tests,
1886 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001887 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001888 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001889
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001890 // Move all 'aggressive' instructions, which are defined in the
1891 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001892 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001893 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001894 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001895 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001896 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001897 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001898 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001899 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001900
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001901 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1902 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001903 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1904 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001905
1906 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001907 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001908 PN->replaceAllUsesWith(NV);
1909 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001910 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001911 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001912
Chris Lattner335f0e42010-12-14 08:01:53 +00001913 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1914 // has been flattened. Change DomBlock to jump directly to our new block to
1915 // avoid other simplifycfg's kicking in on the diamond.
1916 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001917 Builder.SetInsertPoint(OldTI);
1918 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001919 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001920 return true;
1921}
Chris Lattner748f9032005-09-19 23:49:37 +00001922
Chris Lattner86bbf332008-04-24 00:01:19 +00001923/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1924/// to two returning blocks, try to merge them together into one return,
1925/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001926static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001927 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001928 assert(BI->isConditional() && "Must be a conditional branch");
1929 BasicBlock *TrueSucc = BI->getSuccessor(0);
1930 BasicBlock *FalseSucc = BI->getSuccessor(1);
1931 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1932 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001933
Chris Lattner86bbf332008-04-24 00:01:19 +00001934 // Check to ensure both blocks are empty (just a return) or optionally empty
1935 // with PHI nodes. If there are other instructions, merging would cause extra
1936 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001937 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001938 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001939 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001940 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001941
Devang Pateldd14e0f2011-05-18 21:33:11 +00001942 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001943 // Okay, we found a branch that is going to two return nodes. If
1944 // there is no return value for this function, just change the
1945 // branch into a return.
1946 if (FalseRet->getNumOperands() == 0) {
1947 TrueSucc->removePredecessor(BI->getParent());
1948 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001949 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001950 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001951 return true;
1952 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001953
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001954 // Otherwise, figure out what the true and false return values are
1955 // so we can insert a new select instruction.
1956 Value *TrueValue = TrueRet->getReturnValue();
1957 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001958
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001959 // Unwrap any PHI nodes in the return blocks.
1960 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1961 if (TVPN->getParent() == TrueSucc)
1962 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1963 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1964 if (FVPN->getParent() == FalseSucc)
1965 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001966
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001967 // In order for this transformation to be safe, we must be able to
1968 // unconditionally execute both operands to the return. This is
1969 // normally the case, but we could have a potentially-trapping
1970 // constant expression that prevents this transformation from being
1971 // safe.
1972 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1973 if (TCV->canTrap())
1974 return false;
1975 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1976 if (FCV->canTrap())
1977 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001978
Chris Lattner86bbf332008-04-24 00:01:19 +00001979 // Okay, we collected all the mapped values and checked them for sanity, and
1980 // defined to really do this transformation. First, update the CFG.
1981 TrueSucc->removePredecessor(BI->getParent());
1982 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001983
Chris Lattner86bbf332008-04-24 00:01:19 +00001984 // Insert select instructions where needed.
1985 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001986 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001987 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001988 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1989 } else if (isa<UndefValue>(TrueValue)) {
1990 TrueValue = FalseValue;
1991 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001992 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1993 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001994 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001995 }
1996
Andrew Trickf3cf1932012-08-29 21:46:36 +00001997 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001998 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1999
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002000 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002001
David Greene725c7c32010-01-05 01:26:52 +00002002 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002003 << "\n " << *BI << "NewRet = " << *RI
2004 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002005
Eli Friedmancb61afb2008-12-16 20:54:32 +00002006 EraseTerminatorInstAndDCECond(BI);
2007
Chris Lattner86bbf332008-04-24 00:01:19 +00002008 return true;
2009}
2010
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002011/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2012/// probabilities of the branch taking each edge. Fills in the two APInt
2013/// parameters and return true, or returns false if no or invalid metadata was
2014/// found.
2015static bool ExtractBranchMetadata(BranchInst *BI,
Manman Renbfb9d432012-09-15 00:39:57 +00002016 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002017 assert(BI->isConditional() &&
2018 "Looking for probabilities on unconditional branch?");
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00002019 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky398255e2011-12-27 18:27:22 +00002020 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002021 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
2022 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky398255e2011-12-27 18:27:22 +00002023 if (!CITrue || !CIFalse) return false;
Manman Renbfb9d432012-09-15 00:39:57 +00002024 ProbTrue = CITrue->getValue().getZExtValue();
2025 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002026 return true;
2027}
2028
Manman Rend33f4ef2012-06-13 05:43:29 +00002029/// checkCSEInPredecessor - Return true if the given instruction is available
2030/// in its predecessor block. If yes, the instruction will be removed.
2031///
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002032static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002033 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2034 return false;
2035 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2036 Instruction *PBI = &*I;
2037 // Check whether Inst and PBI generate the same value.
2038 if (Inst->isIdenticalTo(PBI)) {
2039 Inst->replaceAllUsesWith(PBI);
2040 Inst->eraseFromParent();
2041 return true;
2042 }
2043 }
2044 return false;
2045}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002046
Chris Lattner7d4cdae2011-04-11 23:24:57 +00002047/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2048/// predecessor branches to us and one of our successors, fold the block into
2049/// the predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00002050bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2051 unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002052 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002053
Craig Topperf40110f2014-04-25 05:29:35 +00002054 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002055 if (BI->isConditional())
2056 Cond = dyn_cast<Instruction>(BI->getCondition());
2057 else {
2058 // For unconditional branch, check for a simple CFG pattern, where
2059 // BB has a single predecessor and BB's successor is also its predecessor's
2060 // successor. If such pattern exisits, check for CSE between BB and its
2061 // predecessor.
2062 if (BasicBlock *PB = BB->getSinglePredecessor())
2063 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2064 if (PBI->isConditional() &&
2065 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2066 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2067 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2068 I != E; ) {
2069 Instruction *Curr = I++;
2070 if (isa<CmpInst>(Curr)) {
2071 Cond = Curr;
2072 break;
2073 }
2074 // Quit if we can't remove this instruction.
2075 if (!checkCSEInPredecessor(Curr, PB))
2076 return false;
2077 }
2078 }
2079
Craig Topperf40110f2014-04-25 05:29:35 +00002080 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002081 return false;
2082 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002083
Craig Topperf40110f2014-04-25 05:29:35 +00002084 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2085 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002086 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002087
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002088 // Make sure the instruction after the condition is the cond branch.
2089 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002090
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002091 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002092 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002093
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002094 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002095 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002096
Jingyue Wufc029672014-09-30 22:23:38 +00002097 // Only allow this transformation if computing the condition doesn't involve
2098 // too many instructions and these involved instructions can be executed
2099 // unconditionally. We denote all involved instructions except the condition
2100 // as "bonus instructions", and only allow this transformation when the
2101 // number of the bonus instructions does not exceed a certain threshold.
2102 unsigned NumBonusInsts = 0;
2103 for (auto I = BB->begin(); Cond != I; ++I) {
2104 // Ignore dbg intrinsics.
2105 if (isa<DbgInfoIntrinsic>(I))
2106 continue;
2107 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2108 return false;
2109 // I has only one use and can be executed unconditionally.
2110 Instruction *User = dyn_cast<Instruction>(I->user_back());
2111 if (User == nullptr || User->getParent() != BB)
2112 return false;
2113 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2114 // to use any other instruction, User must be an instruction between next(I)
2115 // and Cond.
2116 ++NumBonusInsts;
2117 // Early exits once we reach the limit.
2118 if (NumBonusInsts > BonusInstThreshold)
2119 return false;
2120 }
2121
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002122 // Cond is known to be a compare or binary operator. Check to make sure that
2123 // neither operand is a potentially-trapping constant expression.
2124 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2125 if (CE->canTrap())
2126 return false;
2127 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2128 if (CE->canTrap())
2129 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002130
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002131 // Finally, don't infinitely unroll conditional loops.
2132 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002133 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002134 if (TrueDest == BB || FalseDest == BB)
2135 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002136
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002137 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2138 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002139 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002140
Chris Lattner80b03a12008-07-13 22:23:11 +00002141 // Check that we have two conditional branches. If there is a PHI node in
2142 // the common successor, verify that the same value flows in from both
2143 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002144 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002145 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002146 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002147 !SafeToMergeTerminators(BI, PBI)) ||
2148 (!BI->isConditional() &&
2149 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002150 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002151
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002152 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002153 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002154 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002155
Manman Rend33f4ef2012-06-13 05:43:29 +00002156 if (BI->isConditional()) {
2157 if (PBI->getSuccessor(0) == TrueDest)
2158 Opc = Instruction::Or;
2159 else if (PBI->getSuccessor(1) == FalseDest)
2160 Opc = Instruction::And;
2161 else if (PBI->getSuccessor(0) == FalseDest)
2162 Opc = Instruction::And, InvertPredCond = true;
2163 else if (PBI->getSuccessor(1) == TrueDest)
2164 Opc = Instruction::Or, InvertPredCond = true;
2165 else
2166 continue;
2167 } else {
2168 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2169 continue;
2170 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002171
David Greene725c7c32010-01-05 01:26:52 +00002172 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002173 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002174
Chris Lattner55eaae12008-07-13 21:20:19 +00002175 // If we need to invert the condition in the pred block to match, do so now.
2176 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002177 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002179 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2180 CmpInst *CI = cast<CmpInst>(NewCond);
2181 CI->setPredicate(CI->getInversePredicate());
2182 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002183 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002184 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002185 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002186
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002187 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002188 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002189 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002190
Jingyue Wufc029672014-09-30 22:23:38 +00002191 // If we have bonus instructions, clone them into the predecessor block.
2192 // Note that there may be mutliple predecessor blocks, so we cannot move
2193 // bonus instructions to a predecessor block.
2194 ValueToValueMapTy VMap; // maps original values to cloned values
2195 // We already make sure Cond is the last instruction before BI. Therefore,
2196 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2197 // instructions.
2198 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2199 if (isa<DbgInfoIntrinsic>(BonusInst))
2200 continue;
2201 Instruction *NewBonusInst = BonusInst->clone();
2202 RemapInstruction(NewBonusInst, VMap,
2203 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2204 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002205
2206 // If we moved a load, we cannot any longer claim any knowledge about
2207 // its potential value. The previous information might have been valid
2208 // only given the branch precondition.
2209 // For an analogous reason, we must also drop all the metadata whose
2210 // semantics we don't understand.
Jingyue Wufc029672014-09-30 22:23:38 +00002211 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
Rafael Espindolaab73c492014-01-28 16:56:46 +00002212
Jingyue Wufc029672014-09-30 22:23:38 +00002213 PredBlock->getInstList().insert(PBI, NewBonusInst);
2214 NewBonusInst->takeName(BonusInst);
2215 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002216 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002217
Chris Lattner55eaae12008-07-13 21:20:19 +00002218 // Clone Cond into the predecessor basic block, and or/and the
2219 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002220 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002221 RemapInstruction(New, VMap,
2222 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002223 PredBlock->getInstList().insert(PBI, New);
2224 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002225 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002226
Manman Rend33f4ef2012-06-13 05:43:29 +00002227 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002228 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002229 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002230 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002231 PBI->setCondition(NewCond);
2232
Manman Renbfb9d432012-09-15 00:39:57 +00002233 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2234 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2235 PredFalseWeight);
2236 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2237 SuccFalseWeight);
2238 SmallVector<uint64_t, 8> NewWeights;
2239
Manman Rend33f4ef2012-06-13 05:43:29 +00002240 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002241 if (PredHasWeights && SuccHasWeights) {
2242 // PBI: br i1 %x, BB, FalseDest
2243 // BI: br i1 %y, TrueDest, FalseDest
2244 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2245 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2246 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2247 // TrueWeight for PBI * FalseWeight for BI.
2248 // We assume that total weights of a BranchInst can fit into 32 bits.
2249 // Therefore, we will not have overflow using 64-bit arithmetic.
2250 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2251 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2252 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002253 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2254 PBI->setSuccessor(0, TrueDest);
2255 }
2256 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002257 if (PredHasWeights && SuccHasWeights) {
2258 // PBI: br i1 %x, TrueDest, BB
2259 // BI: br i1 %y, TrueDest, FalseDest
2260 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2261 // FalseWeight for PBI * TrueWeight for BI.
2262 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2263 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2264 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2265 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2266 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002267 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2268 PBI->setSuccessor(1, FalseDest);
2269 }
Manman Renbfb9d432012-09-15 00:39:57 +00002270 if (NewWeights.size() == 2) {
2271 // Halve the weights if any of them cannot fit in an uint32_t
2272 FitWeights(NewWeights);
2273
2274 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2275 PBI->setMetadata(LLVMContext::MD_prof,
2276 MDBuilder(BI->getContext()).
2277 createBranchWeights(MDWeights));
2278 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002279 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002280 } else {
2281 // Update PHI nodes in the common successors.
2282 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002283 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002284 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2285 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002286 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002287 if (PBI->getSuccessor(0) == TrueDest) {
2288 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2289 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2290 // is false: !PBI_Cond and BI_Value
2291 Instruction *NotCond =
2292 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2293 "not.cond"));
2294 MergedCond =
2295 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2296 NotCond, New,
2297 "and.cond"));
2298 if (PBI_C->isOne())
2299 MergedCond =
2300 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2301 PBI->getCondition(), MergedCond,
2302 "or.cond"));
2303 } else {
2304 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2305 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2306 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002307 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002308 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2309 PBI->getCondition(), New,
2310 "and.cond"));
2311 if (PBI_C->isOne()) {
2312 Instruction *NotCond =
2313 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2314 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002315 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002316 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2317 NotCond, MergedCond,
2318 "or.cond"));
2319 }
2320 }
2321 // Update PHI Node.
2322 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2323 MergedCond);
2324 }
2325 // Change PBI from Conditional to Unconditional.
2326 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2327 EraseTerminatorInstAndDCECond(PBI);
2328 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002329 }
Devang Pateld715ec82011-04-06 22:37:20 +00002330
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002331 // TODO: If BB is reachable from all paths through PredBlock, then we
2332 // could replace PBI's branch probabilities with BI's.
2333
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002334 // Copy any debug value intrinsics into the end of PredBlock.
2335 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2336 if (isa<DbgInfoIntrinsic>(*I))
2337 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002338
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002339 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002340 }
2341 return false;
2342}
2343
Chris Lattner9aada1d2008-07-13 21:53:26 +00002344/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2345/// predecessor of another block, this function tries to simplify it. We know
2346/// that PBI and BI are both conditional branches, and BI is in one of the
2347/// successor blocks of PBI - PBI branches to BI.
2348static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2349 assert(PBI->isConditional() && BI->isConditional());
2350 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002351
Chris Lattner9aada1d2008-07-13 21:53:26 +00002352 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002353 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002354 // this conditional branch redundant.
2355 if (PBI->getCondition() == BI->getCondition() &&
2356 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2357 // Okay, the outcome of this conditional branch is statically
2358 // knowable. If this block had a single pred, handle specially.
2359 if (BB->getSinglePredecessor()) {
2360 // Turn this into a branch on constant.
2361 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002362 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002363 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002364 return true; // Nuke the branch on constant.
2365 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002366
Chris Lattner9aada1d2008-07-13 21:53:26 +00002367 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2368 // in the constant and simplify the block result. Subsequent passes of
2369 // simplifycfg will thread the block.
2370 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002371 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002372 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002373 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002374 BI->getCondition()->getName() + ".pr",
2375 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002376 // Okay, we're going to insert the PHI node. Since PBI is not the only
2377 // predecessor, compute the PHI'd conditional value for all of the preds.
2378 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002379 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002380 BasicBlock *P = *PI;
2381 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002382 PBI != BI && PBI->isConditional() &&
2383 PBI->getCondition() == BI->getCondition() &&
2384 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2385 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002386 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002387 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002388 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002389 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002390 }
Gabor Greif8629f122010-07-12 10:59:23 +00002391 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002392
Chris Lattner9aada1d2008-07-13 21:53:26 +00002393 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002394 return true;
2395 }
2396 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002397
Chris Lattner9aada1d2008-07-13 21:53:26 +00002398 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002399 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002400 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002401 BasicBlock::iterator BBI = BB->begin();
2402 // Ignore dbg intrinsics.
2403 while (isa<DbgInfoIntrinsic>(BBI))
2404 ++BBI;
2405 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002406 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002407
Andrew Trickf3cf1932012-08-29 21:46:36 +00002408
Chris Lattnerc59945b2009-01-20 01:15:41 +00002409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2410 if (CE->canTrap())
2411 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002412
Chris Lattner834ab4e2008-07-13 22:04:41 +00002413 int PBIOp, BIOp;
2414 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2415 PBIOp = BIOp = 0;
2416 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2417 PBIOp = 0, BIOp = 1;
2418 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2419 PBIOp = 1, BIOp = 0;
2420 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2421 PBIOp = BIOp = 1;
2422 else
2423 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002424
Chris Lattner834ab4e2008-07-13 22:04:41 +00002425 // Check to make sure that the other destination of this branch
2426 // isn't BB itself. If so, this is an infinite loop that will
2427 // keep getting unwound.
2428 if (PBI->getSuccessor(PBIOp) == BB)
2429 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002430
2431 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002432 // insertion of a large number of select instructions. For targets
2433 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002434
Sanjay Patela932da82014-07-07 21:19:00 +00002435 // Also do not perform this transformation if any phi node in the common
2436 // destination block can trap when reached by BB or PBB (PR17073). In that
2437 // case, it would be unsafe to hoist the operation into a select instruction.
2438
2439 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002440 unsigned NumPhis = 0;
2441 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002442 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002443 if (NumPhis > 2) // Disable this xform.
2444 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002445
Sanjay Patela932da82014-07-07 21:19:00 +00002446 PHINode *PN = cast<PHINode>(II);
2447 Value *BIV = PN->getIncomingValueForBlock(BB);
2448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2449 if (CE->canTrap())
2450 return false;
2451
2452 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2453 Value *PBIV = PN->getIncomingValue(PBBIdx);
2454 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2455 if (CE->canTrap())
2456 return false;
2457 }
2458
Chris Lattner834ab4e2008-07-13 22:04:41 +00002459 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002460 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002461
David Greene725c7c32010-01-05 01:26:52 +00002462 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002463 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002464
2465
Chris Lattner80b03a12008-07-13 22:23:11 +00002466 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2467 // branch in it, where one edge (OtherDest) goes back to itself but the other
2468 // exits. We don't *know* that the program avoids the infinite loop
2469 // (even though that seems likely). If we do this xform naively, we'll end up
2470 // recursively unpeeling the loop. Since we know that (after the xform is
2471 // done) that the block *is* infinite if reached, we just make it an obviously
2472 // infinite loop with no cond branch.
2473 if (OtherDest == BB) {
2474 // Insert it at the end of the function, because it's either code,
2475 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002476 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2477 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002478 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2479 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002480 }
2481
David Greene725c7c32010-01-05 01:26:52 +00002482 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002483
Chris Lattner834ab4e2008-07-13 22:04:41 +00002484 // BI may have other predecessors. Because of this, we leave
2485 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002486
Chris Lattner834ab4e2008-07-13 22:04:41 +00002487 // Make sure we get to CommonDest on True&True directions.
2488 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002489 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002490 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002491 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2492
Chris Lattner834ab4e2008-07-13 22:04:41 +00002493 Value *BICond = BI->getCondition();
2494 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002495 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2496
Chris Lattner834ab4e2008-07-13 22:04:41 +00002497 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002498 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002499
Chris Lattner834ab4e2008-07-13 22:04:41 +00002500 // Modify PBI to branch on the new condition to the new dests.
2501 PBI->setCondition(Cond);
2502 PBI->setSuccessor(0, CommonDest);
2503 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002504
Manman Ren2d4c10f2012-09-17 21:30:40 +00002505 // Update branch weight for PBI.
2506 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2507 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2508 PredFalseWeight);
2509 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2510 SuccFalseWeight);
2511 if (PredHasWeights && SuccHasWeights) {
2512 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2513 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2514 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2515 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2516 // The weight to CommonDest should be PredCommon * SuccTotal +
2517 // PredOther * SuccCommon.
2518 // The weight to OtherDest should be PredOther * SuccOther.
2519 SmallVector<uint64_t, 2> NewWeights;
2520 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2521 PredOther * SuccCommon);
2522 NewWeights.push_back(PredOther * SuccOther);
2523 // Halve the weights if any of them cannot fit in an uint32_t
2524 FitWeights(NewWeights);
2525
2526 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2527 PBI->setMetadata(LLVMContext::MD_prof,
2528 MDBuilder(BI->getContext()).
2529 createBranchWeights(MDWeights));
2530 }
2531
Chris Lattner834ab4e2008-07-13 22:04:41 +00002532 // OtherDest may have phi nodes. If so, add an entry from PBI's
2533 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002534 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002535
Chris Lattner834ab4e2008-07-13 22:04:41 +00002536 // We know that the CommonDest already had an edge from PBI to
2537 // it. If it has PHIs though, the PHIs may have different
2538 // entries for BB and PBI's BB. If so, insert a select to make
2539 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002540 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002541 for (BasicBlock::iterator II = CommonDest->begin();
2542 (PN = dyn_cast<PHINode>(II)); ++II) {
2543 Value *BIV = PN->getIncomingValueForBlock(BB);
2544 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2545 Value *PBIV = PN->getIncomingValue(PBBIdx);
2546 if (BIV != PBIV) {
2547 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002548 Value *NV = cast<SelectInst>
2549 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002550 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002551 }
2552 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002553
David Greene725c7c32010-01-05 01:26:52 +00002554 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2555 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002556
Chris Lattner834ab4e2008-07-13 22:04:41 +00002557 // This basic block is probably dead. We know it has at least
2558 // one fewer predecessor.
2559 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002560}
2561
Frits van Bommel8e158492011-01-11 12:52:11 +00002562// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2563// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2564// Takes care of updating the successors and removing the old terminator.
2565// Also makes sure not to introduce new successors by assuming that edges to
2566// non-successor TrueBBs and FalseBBs aren't reachable.
2567static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002568 BasicBlock *TrueBB, BasicBlock *FalseBB,
2569 uint32_t TrueWeight,
2570 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002571 // Remove any superfluous successor edges from the CFG.
2572 // First, figure out which successors to preserve.
2573 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2574 // successor.
2575 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002576 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002577
2578 // Then remove the rest.
2579 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2580 BasicBlock *Succ = OldTerm->getSuccessor(I);
2581 // Make sure only to keep exactly one copy of each edge.
2582 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002583 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002584 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002585 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002586 else
2587 Succ->removePredecessor(OldTerm->getParent());
2588 }
2589
Devang Patel2c2ea222011-05-18 18:43:31 +00002590 IRBuilder<> Builder(OldTerm);
2591 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2592
Frits van Bommel8e158492011-01-11 12:52:11 +00002593 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002594 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002595 if (TrueBB == FalseBB)
2596 // We were only looking for one successor, and it was present.
2597 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002598 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002599 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002600 // We found both of the successors we were looking for.
2601 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002602 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2603 if (TrueWeight != FalseWeight)
2604 NewBI->setMetadata(LLVMContext::MD_prof,
2605 MDBuilder(OldTerm->getContext()).
2606 createBranchWeights(TrueWeight, FalseWeight));
2607 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002608 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2609 // Neither of the selected blocks were successors, so this
2610 // terminator must be unreachable.
2611 new UnreachableInst(OldTerm->getContext(), OldTerm);
2612 } else {
2613 // One of the selected values was a successor, but the other wasn't.
2614 // Insert an unconditional branch to the one that was found;
2615 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002616 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002617 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002618 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002619 else
2620 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002621 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002622 }
2623
2624 EraseTerminatorInstAndDCECond(OldTerm);
2625 return true;
2626}
2627
Frits van Bommel8ae07992011-02-28 09:44:07 +00002628// SimplifySwitchOnSelect - Replaces
2629// (switch (select cond, X, Y)) on constant X, Y
2630// with a branch - conditional if X and Y lead to distinct BBs,
2631// unconditional otherwise.
2632static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2633 // Check for constant integer values in the select.
2634 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2635 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2636 if (!TrueVal || !FalseVal)
2637 return false;
2638
2639 // Find the relevant condition and destinations.
2640 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002641 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2642 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002643
Manman Ren774246a2012-09-17 22:28:55 +00002644 // Get weight for TrueBB and FalseBB.
2645 uint32_t TrueWeight = 0, FalseWeight = 0;
2646 SmallVector<uint64_t, 8> Weights;
2647 bool HasWeights = HasBranchWeights(SI);
2648 if (HasWeights) {
2649 GetBranchWeights(SI, Weights);
2650 if (Weights.size() == 1 + SI->getNumCases()) {
2651 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2652 getSuccessorIndex()];
2653 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2654 getSuccessorIndex()];
2655 }
2656 }
2657
Frits van Bommel8ae07992011-02-28 09:44:07 +00002658 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002659 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2660 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002661}
2662
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002663// SimplifyIndirectBrOnSelect - Replaces
2664// (indirectbr (select cond, blockaddress(@fn, BlockA),
2665// blockaddress(@fn, BlockB)))
2666// with
2667// (br cond, BlockA, BlockB).
2668static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2669 // Check that both operands of the select are block addresses.
2670 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2671 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2672 if (!TBA || !FBA)
2673 return false;
2674
2675 // Extract the actual blocks.
2676 BasicBlock *TrueBB = TBA->getBasicBlock();
2677 BasicBlock *FalseBB = FBA->getBasicBlock();
2678
Frits van Bommel8e158492011-01-11 12:52:11 +00002679 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002680 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2681 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002682}
2683
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002684/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2685/// instruction (a seteq/setne with a constant) as the only instruction in a
2686/// block that ends with an uncond branch. We are looking for a very specific
2687/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2688/// this case, we merge the first two "or's of icmp" into a switch, but then the
2689/// default value goes to an uncond block with a seteq in it, we get something
2690/// like:
2691///
2692/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2693/// DEFAULT:
2694/// %tmp = icmp eq i8 %A, 92
2695/// br label %end
2696/// end:
2697/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002698///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002699/// We prefer to split the edge to 'end' so that there is a true/false entry to
2700/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002701static bool TryToSimplifyUncondBranchWithICmpInIt(
2702 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00002703 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002704 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002705
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002706 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2707 // complex.
2708 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2709
2710 Value *V = ICI->getOperand(0);
2711 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002712
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002713 // The pattern we're looking for is where our only predecessor is a switch on
2714 // 'V' and this block is the default case for the switch. In this case we can
2715 // fold the compared value into the switch to simplify things.
2716 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002717 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002718
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002719 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2720 if (SI->getCondition() != V)
2721 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002722
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002723 // If BB is reachable on a non-default case, then we simply know the value of
2724 // V in this block. Substitute it and constant fold the icmp instruction
2725 // away.
2726 if (SI->getDefaultDest() != BB) {
2727 ConstantInt *VVal = SI->findCaseDest(BB);
2728 assert(VVal && "Should have a unique destination value");
2729 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002730
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002731 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002732 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002733 ICI->eraseFromParent();
2734 }
2735 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002736 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002737 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002738
Chris Lattner62cc76e2010-12-13 03:43:57 +00002739 // Ok, the block is reachable from the default dest. If the constant we're
2740 // comparing exists in one of the other edges, then we can constant fold ICI
2741 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002742 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002743 Value *V;
2744 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2745 V = ConstantInt::getFalse(BB->getContext());
2746 else
2747 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002748
Chris Lattner62cc76e2010-12-13 03:43:57 +00002749 ICI->replaceAllUsesWith(V);
2750 ICI->eraseFromParent();
2751 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002752 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002753 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002754
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002755 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2756 // the block.
2757 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002758 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002759 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002760 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2761 return false;
2762
2763 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2764 // true in the PHI.
2765 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2766 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2767
2768 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2769 std::swap(DefaultCst, NewCst);
2770
2771 // Replace ICI (which is used by the PHI for the default value) with true or
2772 // false depending on if it is EQ or NE.
2773 ICI->replaceAllUsesWith(DefaultCst);
2774 ICI->eraseFromParent();
2775
2776 // Okay, the switch goes to this block on a default value. Add an edge from
2777 // the switch to the merge point on the compared value.
2778 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2779 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002780 SmallVector<uint64_t, 8> Weights;
2781 bool HasWeights = HasBranchWeights(SI);
2782 if (HasWeights) {
2783 GetBranchWeights(SI, Weights);
2784 if (Weights.size() == 1 + SI->getNumCases()) {
2785 // Split weight for default case to case for "Cst".
2786 Weights[0] = (Weights[0]+1) >> 1;
2787 Weights.push_back(Weights[0]);
2788
2789 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2790 SI->setMetadata(LLVMContext::MD_prof,
2791 MDBuilder(SI->getContext()).
2792 createBranchWeights(MDWeights));
2793 }
2794 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002795 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002796
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002797 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002798 Builder.SetInsertPoint(NewBB);
2799 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2800 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002801 PHIUse->addIncoming(NewCst, NewBB);
2802 return true;
2803}
2804
Chris Lattnera69c4432010-12-13 05:03:41 +00002805/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2806/// Check to see if it is branching on an or/and chain of icmp instructions, and
2807/// fold it into a switch instruction if so.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002808static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
Devang Patel7de6c4b2011-05-18 23:18:47 +00002809 IRBuilder<> &Builder) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002810 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002811 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002812
2813
Chris Lattnera69c4432010-12-13 05:03:41 +00002814 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2815 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2816 // 'setne's and'ed together, collect them.
Craig Topperf40110f2014-04-25 05:29:35 +00002817 Value *CompVal = nullptr;
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002818 SmallVector<ConstantInt*, 8> Values;
2819 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
Craig Topperf40110f2014-04-25 05:29:35 +00002820 Value *ExtraCase = nullptr;
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002821 unsigned UsedICmps = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002822
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002823 // Try to gather values from a chain of and/or to be turned into a switch
2824 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, UsedICmps);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002825
Chris Lattnera69c4432010-12-13 05:03:41 +00002826 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002827 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002828
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002829 // Avoid turning single icmps into a switch.
2830 if (UsedICmps <= 1)
2831 return false;
2832
Chris Lattnera69c4432010-12-13 05:03:41 +00002833 // There might be duplicate constants in the list, which the switch
2834 // instruction can't handle, remove them now.
2835 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2836 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002837
Chris Lattnera69c4432010-12-13 05:03:41 +00002838 // If Extra was used, we require at least two switch values to do the
2839 // transformation. A switch with one value is just an cond branch.
2840 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002841
Andrew Trick3051aa12012-08-29 21:46:38 +00002842 // TODO: Preserve branch weight metadata, similarly to how
2843 // FoldValueComparisonIntoPredecessors preserves it.
2844
Chris Lattnera69c4432010-12-13 05:03:41 +00002845 // Figure out which block is which destination.
2846 BasicBlock *DefaultBB = BI->getSuccessor(1);
2847 BasicBlock *EdgeBB = BI->getSuccessor(0);
2848 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002849
Chris Lattnera69c4432010-12-13 05:03:41 +00002850 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002851
Chris Lattnerd7beca32010-12-14 06:17:25 +00002852 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002853 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002854
Chris Lattnera69c4432010-12-13 05:03:41 +00002855 // If there are any extra values that couldn't be folded into the switch
2856 // then we evaluate them with an explicit branch first. Split the block
2857 // right before the condbr to handle it.
2858 if (ExtraCase) {
2859 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2860 // Remove the uncond branch added to the old block.
2861 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002862 Builder.SetInsertPoint(OldTI);
2863
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002864 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002865 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002866 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002867 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002868
Chris Lattnera69c4432010-12-13 05:03:41 +00002869 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002870
Chris Lattnercb570f82010-12-13 05:34:18 +00002871 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2872 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002873 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002874
Chris Lattnerd7beca32010-12-14 06:17:25 +00002875 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2876 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002877 BB = NewBB;
2878 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002879
2880 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002881 // Convert pointer to int before we switch.
2882 if (CompVal->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002883 assert(DL && "Cannot switch on pointer without DataLayout");
Devang Patel7de6c4b2011-05-18 23:18:47 +00002884 CompVal = Builder.CreatePtrToInt(CompVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002885 DL->getIntPtrType(CompVal->getType()),
Devang Patel7de6c4b2011-05-18 23:18:47 +00002886 "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002887 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002888
Chris Lattnera69c4432010-12-13 05:03:41 +00002889 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002890 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002891
Chris Lattnera69c4432010-12-13 05:03:41 +00002892 // Add all of the 'cases' to the switch instruction.
2893 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2894 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002895
Chris Lattnera69c4432010-12-13 05:03:41 +00002896 // We added edges from PI to the EdgeBB. As such, if there were any
2897 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2898 // the number of edges added.
2899 for (BasicBlock::iterator BBI = EdgeBB->begin();
2900 isa<PHINode>(BBI); ++BBI) {
2901 PHINode *PN = cast<PHINode>(BBI);
2902 Value *InVal = PN->getIncomingValueForBlock(BB);
2903 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2904 PN->addIncoming(InVal, BB);
2905 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002906
Chris Lattnera69c4432010-12-13 05:03:41 +00002907 // Erase the old branch instruction.
2908 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002909
Chris Lattnerd7beca32010-12-14 06:17:25 +00002910 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002911 return true;
2912}
2913
Duncan Sands29192d02011-09-05 12:57:57 +00002914bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2915 // If this is a trivial landing pad that just continues unwinding the caught
2916 // exception then zap the landing pad, turning its invokes into calls.
2917 BasicBlock *BB = RI->getParent();
2918 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2919 if (RI->getValue() != LPInst)
2920 // Not a landing pad, or the resume is not unwinding the exception that
2921 // caused control to branch here.
2922 return false;
2923
2924 // Check that there are no other instructions except for debug intrinsics.
2925 BasicBlock::iterator I = LPInst, E = RI;
2926 while (++I != E)
2927 if (!isa<DbgInfoIntrinsic>(I))
2928 return false;
2929
2930 // Turn all invokes that unwind here into calls and delete the basic block.
Bill Wendling9534d882013-03-11 20:53:00 +00002931 bool InvokeRequiresTableEntry = false;
2932 bool Changed = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002933 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2934 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Bill Wendling9534d882013-03-11 20:53:00 +00002935
2936 if (II->hasFnAttr(Attribute::UWTable)) {
2937 // Don't remove an `invoke' instruction if the ABI requires an entry into
2938 // the table.
2939 InvokeRequiresTableEntry = true;
2940 continue;
2941 }
2942
Duncan Sands29192d02011-09-05 12:57:57 +00002943 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
Bill Wendling9534d882013-03-11 20:53:00 +00002944
Duncan Sands29192d02011-09-05 12:57:57 +00002945 // Insert a call instruction before the invoke.
2946 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2947 Call->takeName(II);
2948 Call->setCallingConv(II->getCallingConv());
2949 Call->setAttributes(II->getAttributes());
2950 Call->setDebugLoc(II->getDebugLoc());
2951
2952 // Anything that used the value produced by the invoke instruction now uses
2953 // the value produced by the call instruction. Note that we do this even
2954 // for void functions and calls with no uses so that the callgraph edge is
2955 // updated.
2956 II->replaceAllUsesWith(Call);
2957 BB->removePredecessor(II->getParent());
2958
2959 // Insert a branch to the normal destination right before the invoke.
2960 BranchInst::Create(II->getNormalDest(), II);
2961
2962 // Finally, delete the invoke instruction!
2963 II->eraseFromParent();
Bill Wendling9534d882013-03-11 20:53:00 +00002964 Changed = true;
Duncan Sands29192d02011-09-05 12:57:57 +00002965 }
2966
Bill Wendling9534d882013-03-11 20:53:00 +00002967 if (!InvokeRequiresTableEntry)
2968 // The landingpad is now unreachable. Zap it.
2969 BB->eraseFromParent();
2970
2971 return Changed;
Duncan Sands29192d02011-09-05 12:57:57 +00002972}
2973
Devang Pateldd14e0f2011-05-18 21:33:11 +00002974bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002975 BasicBlock *BB = RI->getParent();
2976 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002977
Chris Lattner25c3af32010-12-13 06:25:44 +00002978 // Find predecessors that end with branches.
2979 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2980 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002981 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2982 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00002983 TerminatorInst *PTI = P->getTerminator();
2984 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2985 if (BI->isUnconditional())
2986 UncondBranchPreds.push_back(P);
2987 else
2988 CondBranchPreds.push_back(BI);
2989 }
2990 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002991
Chris Lattner25c3af32010-12-13 06:25:44 +00002992 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00002993 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002994 while (!UncondBranchPreds.empty()) {
2995 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2996 DEBUG(dbgs() << "FOLDING: " << *BB
2997 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00002998 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00002999 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003000
Chris Lattner25c3af32010-12-13 06:25:44 +00003001 // If we eliminated all predecessors of the block, delete the block now.
3002 if (pred_begin(BB) == pred_end(BB))
3003 // We know there are no successors, so just nuke the block.
3004 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003005
Chris Lattner25c3af32010-12-13 06:25:44 +00003006 return true;
3007 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003008
Chris Lattner25c3af32010-12-13 06:25:44 +00003009 // Check out all of the conditional branches going to this return
3010 // instruction. If any of them just select between returns, change the
3011 // branch itself into a select/return pair.
3012 while (!CondBranchPreds.empty()) {
3013 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003014
Chris Lattner25c3af32010-12-13 06:25:44 +00003015 // Check to see if the non-BB successor is also a return block.
3016 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3017 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003018 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003019 return true;
3020 }
3021 return false;
3022}
3023
Chris Lattner25c3af32010-12-13 06:25:44 +00003024bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3025 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003026
Chris Lattner25c3af32010-12-13 06:25:44 +00003027 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003028
Chris Lattner25c3af32010-12-13 06:25:44 +00003029 // If there are any instructions immediately before the unreachable that can
3030 // be removed, do so.
3031 while (UI != BB->begin()) {
3032 BasicBlock::iterator BBI = UI;
3033 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003034 // Do not delete instructions that can have side effects which might cause
3035 // the unreachable to not be reachable; specifically, calls and volatile
3036 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003037 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003038
3039 if (BBI->mayHaveSideEffects()) {
3040 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3041 if (SI->isVolatile())
3042 break;
3043 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3044 if (LI->isVolatile())
3045 break;
3046 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3047 if (RMWI->isVolatile())
3048 break;
3049 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3050 if (CXI->isVolatile())
3051 break;
3052 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3053 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003054 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003055 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003056 // Note that deleting LandingPad's here is in fact okay, although it
3057 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3058 // all the predecessors of this block will be the unwind edges of Invokes,
3059 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003060 }
3061
Eli Friedmanaac35b32011-03-09 00:48:33 +00003062 // Delete this instruction (any uses are guaranteed to be dead)
3063 if (!BBI->use_empty())
3064 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003065 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003066 Changed = true;
3067 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003068
Chris Lattner25c3af32010-12-13 06:25:44 +00003069 // If the unreachable instruction is the first in the block, take a gander
3070 // at all of the predecessors of this instruction, and simplify them.
3071 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003072
Chris Lattner25c3af32010-12-13 06:25:44 +00003073 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3074 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3075 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003076 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003077 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3078 if (BI->isUnconditional()) {
3079 if (BI->getSuccessor(0) == BB) {
3080 new UnreachableInst(TI->getContext(), TI);
3081 TI->eraseFromParent();
3082 Changed = true;
3083 }
3084 } else {
3085 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003086 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003087 EraseTerminatorInstAndDCECond(BI);
3088 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003089 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003090 EraseTerminatorInstAndDCECond(BI);
3091 Changed = true;
3092 }
3093 }
3094 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003095 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003096 i != e; ++i)
3097 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003098 BB->removePredecessor(SI->getParent());
3099 SI->removeCase(i);
3100 --i; --e;
3101 Changed = true;
3102 }
3103 // If the default value is unreachable, figure out the most popular
3104 // destination and make it the default.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003105 if (SI->getDefaultDest() == BB) {
Eli Friedmanc4414c62011-03-15 02:23:35 +00003106 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003107 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003108 i != e; ++i) {
Nick Lewyckye87d54c2011-12-26 20:37:40 +00003109 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003110 Popularity[i.getCaseSuccessor()];
Eli Friedmanc4414c62011-03-15 02:23:35 +00003111 if (entry.first == 0) {
3112 entry.first = 1;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003113 entry.second = i.getCaseIndex();
Eli Friedmanc4414c62011-03-15 02:23:35 +00003114 } else {
3115 entry.first++;
3116 }
3117 }
3118
Chris Lattner25c3af32010-12-13 06:25:44 +00003119 // Find the most popular block.
3120 unsigned MaxPop = 0;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003121 unsigned MaxIndex = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003122 BasicBlock *MaxBlock = nullptr;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003123 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner25c3af32010-12-13 06:25:44 +00003124 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00003125 if (I->second.first > MaxPop ||
Eli Friedmanc4414c62011-03-15 02:23:35 +00003126 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3127 MaxPop = I->second.first;
3128 MaxIndex = I->second.second;
Chris Lattner25c3af32010-12-13 06:25:44 +00003129 MaxBlock = I->first;
3130 }
3131 }
3132 if (MaxBlock) {
3133 // Make this the new default, allowing us to delete any explicit
3134 // edges to it.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003135 SI->setDefaultDest(MaxBlock);
Chris Lattner25c3af32010-12-13 06:25:44 +00003136 Changed = true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003137
Chris Lattner25c3af32010-12-13 06:25:44 +00003138 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3139 // it.
3140 if (isa<PHINode>(MaxBlock->begin()))
3141 for (unsigned i = 0; i != MaxPop-1; ++i)
3142 MaxBlock->removePredecessor(SI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003143
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003144 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003145 i != e; ++i)
3146 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003147 SI->removeCase(i);
3148 --i; --e;
3149 }
3150 }
3151 }
3152 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3153 if (II->getUnwindDest() == BB) {
3154 // Convert the invoke to a call instruction. This would be a good
3155 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003156 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003157 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003158
Chris Lattner25c3af32010-12-13 06:25:44 +00003159 // Insert the call now...
3160 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003161 Builder.SetInsertPoint(BI);
3162 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003163 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003164 CI->setCallingConv(II->getCallingConv());
3165 CI->setAttributes(II->getAttributes());
3166 // If the invoke produced a value, the call does now instead.
3167 II->replaceAllUsesWith(CI);
3168 delete II;
3169 Changed = true;
3170 }
3171 }
3172 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003173
Chris Lattner25c3af32010-12-13 06:25:44 +00003174 // If this block is now dead, remove it.
3175 if (pred_begin(BB) == pred_end(BB) &&
3176 BB != &BB->getParent()->getEntryBlock()) {
3177 // We know there are no successors, so just nuke the block.
3178 BB->eraseFromParent();
3179 return true;
3180 }
3181
3182 return Changed;
3183}
3184
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003185/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3186/// integer range comparison into a sub, an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003187static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003188 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003189
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003190 // Make sure all cases point to the same destination and gather the values.
3191 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003192 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003193 Cases.push_back(I.getCaseValue());
3194 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003195 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003196 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003197 return false;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003198 Cases.push_back(I.getCaseValue());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003199 }
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003200 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003201
3202 // Sort the case values, then check if they form a range we can transform.
3203 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3204 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3205 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3206 return false;
3207 }
3208
3209 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003210 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003211
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003212 Value *Sub = SI->getCondition();
3213 if (!Offset->isNullValue())
Devang Patel3015a542011-05-19 00:13:33 +00003214 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003215 Value *Cmp;
3216 // If NumCases overflowed, then all possible values jump to the successor.
3217 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3218 Cmp = ConstantInt::getTrue(SI->getContext());
3219 else
3220 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren56575552012-09-18 00:47:33 +00003221 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003222 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003223
Manman Ren56575552012-09-18 00:47:33 +00003224 // Update weight for the newly-created conditional branch.
3225 SmallVector<uint64_t, 8> Weights;
3226 bool HasWeights = HasBranchWeights(SI);
3227 if (HasWeights) {
3228 GetBranchWeights(SI, Weights);
3229 if (Weights.size() == 1 + SI->getNumCases()) {
3230 // Combine all weights for the cases to be the true weight of NewBI.
3231 // We assume that the sum of all weights for a Terminator can fit into 32
3232 // bits.
3233 uint32_t NewTrueWeight = 0;
3234 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3235 NewTrueWeight += (uint32_t)Weights[I];
3236 NewBI->setMetadata(LLVMContext::MD_prof,
3237 MDBuilder(SI->getContext()).
3238 createBranchWeights(NewTrueWeight,
3239 (uint32_t)Weights[0]));
3240 }
3241 }
3242
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003243 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003244 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003245 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003246 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003247 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3248 }
3249 SI->eraseFromParent();
3250
3251 return true;
3252}
Chris Lattner25c3af32010-12-13 06:25:44 +00003253
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003254/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3255/// and use it to remove dead cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003256static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3257 AssumptionTracker *AT) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003258 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003259 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003260 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003261 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003262
3263 // Gather dead cases.
3264 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003265 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003266 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3267 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3268 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003269 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003270 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003271 }
3272 }
3273
Manman Ren56575552012-09-18 00:47:33 +00003274 SmallVector<uint64_t, 8> Weights;
3275 bool HasWeight = HasBranchWeights(SI);
3276 if (HasWeight) {
3277 GetBranchWeights(SI, Weights);
3278 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3279 }
3280
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003281 // Remove dead cases from the switch.
3282 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003283 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003284 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003285 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003286 if (HasWeight) {
3287 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3288 Weights.pop_back();
3289 }
3290
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003291 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003292 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003293 SI->removeCase(Case);
3294 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003295 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003296 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3297 SI->setMetadata(LLVMContext::MD_prof,
3298 MDBuilder(SI->getParent()->getContext()).
3299 createBranchWeights(MDWeights));
3300 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003301
3302 return !DeadCases.empty();
3303}
3304
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003305/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3306/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3307/// by an unconditional branch), look at the phi node for BB in the successor
3308/// block and see if the incoming value is equal to CaseValue. If so, return
3309/// the phi node, and set PhiIndex to BB's index in the phi node.
3310static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3311 BasicBlock *BB,
3312 int *PhiIndex) {
3313 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003314 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003315 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003316 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003317
3318 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3319 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003320 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003321
3322 BasicBlock *Succ = Branch->getSuccessor(0);
3323
3324 BasicBlock::iterator I = Succ->begin();
3325 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3326 int Idx = PHI->getBasicBlockIndex(BB);
3327 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3328
3329 Value *InValue = PHI->getIncomingValue(Idx);
3330 if (InValue != CaseValue) continue;
3331
3332 *PhiIndex = Idx;
3333 return PHI;
3334 }
3335
Craig Topperf40110f2014-04-25 05:29:35 +00003336 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003337}
3338
3339/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3340/// instruction to a phi node dominated by the switch, if that would mean that
3341/// some of the destination blocks of the switch can be folded away.
3342/// Returns true if a change is made.
3343static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3344 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3345 ForwardingNodesMap ForwardingNodes;
3346
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003347 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003348 ConstantInt *CaseValue = I.getCaseValue();
3349 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003350
3351 int PhiIndex;
3352 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3353 &PhiIndex);
3354 if (!PHI) continue;
3355
3356 ForwardingNodes[PHI].push_back(PhiIndex);
3357 }
3358
3359 bool Changed = false;
3360
3361 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3362 E = ForwardingNodes.end(); I != E; ++I) {
3363 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003364 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003365
3366 if (Indexes.size() < 2) continue;
3367
3368 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3369 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3370 Changed = true;
3371 }
3372
3373 return Changed;
3374}
3375
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003376/// ValidLookupTableConstant - Return true if the backend will be able to handle
3377/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003378static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003379 if (C->isThreadDependent())
3380 return false;
3381 if (C->isDLLImportDependent())
3382 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003383
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003384 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3385 return CE->isGEPWithNoNotionalOverIndexing();
3386
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003387 return isa<ConstantFP>(C) ||
3388 isa<ConstantInt>(C) ||
3389 isa<ConstantPointerNull>(C) ||
3390 isa<GlobalValue>(C) ||
3391 isa<UndefValue>(C);
3392}
3393
Hans Wennborg09acdb92012-10-31 15:14:39 +00003394/// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003395/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003396static Constant *LookupConstant(Value *V,
3397 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3398 if (Constant *C = dyn_cast<Constant>(V))
3399 return C;
3400 return ConstantPool.lookup(V);
3401}
3402
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003403/// ConstantFold - Try to fold instruction I into a constant. This works for
3404/// simple instructions such as binary operations where both operands are
3405/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003406/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003407static Constant *
3408ConstantFold(Instruction *I,
3409 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3410 const DataLayout *DL) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003411 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003412 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3413 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003414 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003415 if (A->isAllOnesValue())
3416 return LookupConstant(Select->getTrueValue(), ConstantPool);
3417 if (A->isNullValue())
3418 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003419 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003420 }
3421
Benjamin Kramer7c302602013-11-12 12:24:36 +00003422 SmallVector<Constant *, 4> COps;
3423 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3424 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3425 COps.push_back(A);
3426 else
Craig Topperf40110f2014-04-25 05:29:35 +00003427 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003428 }
3429
Benjamin Kramer7c302602013-11-12 12:24:36 +00003430 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3431 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3432 COps[1], DL);
3433
3434 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003435}
3436
3437/// GetCaseResults - Try to determine the resulting constant values in phi nodes
3438/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003439/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003440/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003441static bool
3442GetCaseResults(SwitchInst *SI,
3443 ConstantInt *CaseVal,
3444 BasicBlock *CaseDest,
3445 BasicBlock **CommonDest,
Benjamin Kramer7c302602013-11-12 12:24:36 +00003446 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3447 const DataLayout *DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003448 // The block from which we enter the common destination.
3449 BasicBlock *Pred = SI->getParent();
3450
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003451 // If CaseDest is empty except for some side-effect free instructions through
3452 // which we can constant-propagate the CaseVal, continue to its successor.
3453 SmallDenseMap<Value*, Constant*> ConstantPool;
3454 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3455 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3456 ++I) {
3457 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3458 // If the terminator is a simple branch, continue to the next block.
3459 if (T->getNumSuccessors() != 1)
3460 return false;
3461 Pred = CaseDest;
3462 CaseDest = T->getSuccessor(0);
3463 } else if (isa<DbgInfoIntrinsic>(I)) {
3464 // Skip debug intrinsic.
3465 continue;
Benjamin Kramer7c302602013-11-12 12:24:36 +00003466 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003467 // Instruction is side-effect free and constant.
3468 ConstantPool.insert(std::make_pair(I, C));
3469 } else {
3470 break;
3471 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003472 }
3473
3474 // If we did not have a CommonDest before, use the current one.
3475 if (!*CommonDest)
3476 *CommonDest = CaseDest;
3477 // If the destination isn't the common one, abort.
3478 if (CaseDest != *CommonDest)
3479 return false;
3480
3481 // Get the values for this case from phi nodes in the destination block.
3482 BasicBlock::iterator I = (*CommonDest)->begin();
3483 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3484 int Idx = PHI->getBasicBlockIndex(Pred);
3485 if (Idx == -1)
3486 continue;
3487
Hans Wennborg09acdb92012-10-31 15:14:39 +00003488 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3489 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003490 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003491 return false;
3492
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003493 // Note: If the constant comes from constant-propagating the case value
3494 // through the CaseDest basic block, it will be safe to remove the
3495 // instructions in that block. They cannot be used (except in the phi nodes
3496 // we visit) outside CaseDest, because that block does not dominate its
3497 // successor. If it did, we would not be in this phi node.
3498
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003499 // Be conservative about which kinds of constants we support.
3500 if (!ValidLookupTableConstant(ConstVal))
3501 return false;
3502
3503 Res.push_back(std::make_pair(PHI, ConstVal));
3504 }
3505
Hans Wennborgac114a32014-01-12 00:44:41 +00003506 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003507}
3508
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003509// MapCaseToResult - Helper function used to
3510// add CaseVal to the list of cases that generate Result.
3511static void MapCaseToResult(ConstantInt *CaseVal,
3512 SwitchCaseResultVectorTy &UniqueResults,
3513 Constant *Result) {
3514 for (auto &I : UniqueResults) {
3515 if (I.first == Result) {
3516 I.second.push_back(CaseVal);
3517 return;
3518 }
3519 }
3520 UniqueResults.push_back(std::make_pair(Result,
3521 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3522}
3523
3524// InitializeUniqueCases - Helper function that initializes a map containing
3525// results for the PHI node of the common destination block for a switch
3526// instruction. Returns false if multiple PHI nodes have been found or if
3527// there is not a common destination block for the switch.
3528static bool InitializeUniqueCases(
3529 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3530 BasicBlock *&CommonDest,
3531 SwitchCaseResultVectorTy &UniqueResults,
3532 Constant *&DefaultResult) {
3533 for (auto &I : SI->cases()) {
3534 ConstantInt *CaseVal = I.getCaseValue();
3535
3536 // Resulting value at phi nodes for this case value.
3537 SwitchCaseResultsTy Results;
3538 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3539 DL))
3540 return false;
3541
3542 // Only one value per case is permitted
3543 if (Results.size() > 1)
3544 return false;
3545 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3546
3547 // Check the PHI consistency.
3548 if (!PHI)
3549 PHI = Results[0].first;
3550 else if (PHI != Results[0].first)
3551 return false;
3552 }
3553 // Find the default result value.
3554 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3555 BasicBlock *DefaultDest = SI->getDefaultDest();
3556 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3557 DL);
3558 // If the default value is not found abort unless the default destination
3559 // is unreachable.
3560 DefaultResult =
3561 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3562 if ((!DefaultResult &&
3563 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3564 return false;
3565
3566 return true;
3567}
3568
3569// ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3570// transform a switch with only two cases (or two cases + default)
3571// that produces a result into a value select.
3572// Example:
3573// switch (a) {
3574// case 10: %0 = icmp eq i32 %a, 10
3575// return 10; %1 = select i1 %0, i32 10, i32 4
3576// case 20: ----> %2 = icmp eq i32 %a, 20
3577// return 2; %3 = select i1 %2, i32 2, i32 %1
3578// default:
3579// return 4;
3580// }
3581static Value *
3582ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3583 Constant *DefaultResult, Value *Condition,
3584 IRBuilder<> &Builder) {
3585 assert(ResultVector.size() == 2 &&
3586 "We should have exactly two unique results at this point");
3587 // If we are selecting between only two cases transform into a simple
3588 // select or a two-way select if default is possible.
3589 if (ResultVector[0].second.size() == 1 &&
3590 ResultVector[1].second.size() == 1) {
3591 ConstantInt *const FirstCase = ResultVector[0].second[0];
3592 ConstantInt *const SecondCase = ResultVector[1].second[0];
3593
3594 bool DefaultCanTrigger = DefaultResult;
3595 Value *SelectValue = ResultVector[1].first;
3596 if (DefaultCanTrigger) {
3597 Value *const ValueCompare =
3598 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3599 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3600 DefaultResult, "switch.select");
3601 }
3602 Value *const ValueCompare =
3603 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3604 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3605 "switch.select");
3606 }
3607
3608 return nullptr;
3609}
3610
3611// RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3612// instruction that has been converted into a select, fixing up PHI nodes and
3613// basic blocks.
3614static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3615 Value *SelectValue,
3616 IRBuilder<> &Builder) {
3617 BasicBlock *SelectBB = SI->getParent();
3618 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3619 PHI->removeIncomingValue(SelectBB);
3620 PHI->addIncoming(SelectValue, SelectBB);
3621
3622 Builder.CreateBr(PHI->getParent());
3623
3624 // Remove the switch.
3625 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3626 BasicBlock *Succ = SI->getSuccessor(i);
3627
3628 if (Succ == PHI->getParent())
3629 continue;
3630 Succ->removePredecessor(SelectBB);
3631 }
3632 SI->eraseFromParent();
3633}
3634
3635/// SwitchToSelect - If the switch is only used to initialize one or more
3636/// phi nodes in a common successor block with only two different
3637/// constant values, replace the switch with select.
3638static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3639 const DataLayout *DL, AssumptionTracker *AT) {
3640 Value *const Cond = SI->getCondition();
3641 PHINode *PHI = nullptr;
3642 BasicBlock *CommonDest = nullptr;
3643 Constant *DefaultResult;
3644 SwitchCaseResultVectorTy UniqueResults;
3645 // Collect all the cases that will deliver the same value from the switch.
3646 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3647 DefaultResult))
3648 return false;
3649 // Selects choose between maximum two values.
3650 if (UniqueResults.size() != 2)
3651 return false;
3652 assert(PHI != nullptr && "PHI for value select not found");
3653
3654 Builder.SetInsertPoint(SI);
3655 Value *SelectValue = ConvertTwoCaseSwitch(
3656 UniqueResults,
3657 DefaultResult, Cond, Builder);
3658 if (SelectValue) {
3659 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3660 return true;
3661 }
3662 // The switch couldn't be converted into a select.
3663 return false;
3664}
3665
Hans Wennborg776d7122012-09-26 09:34:53 +00003666namespace {
3667 /// SwitchLookupTable - This class represents a lookup table that can be used
3668 /// to replace a switch.
3669 class SwitchLookupTable {
3670 public:
3671 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3672 /// with the contents of Values, using DefaultValue to fill any holes in the
3673 /// table.
3674 SwitchLookupTable(Module &M,
3675 uint64_t TableSize,
3676 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003677 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003678 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003679 const DataLayout *DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003680
3681 /// BuildLookup - Build instructions with Builder to retrieve the value at
3682 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003683 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003684
Hans Wennborg39583b82012-09-26 09:44:49 +00003685 /// WouldFitInRegister - Return true if a table with TableSize elements of
3686 /// type ElementType would fit in a target-legal register.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003687 static bool WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003688 uint64_t TableSize,
3689 const Type *ElementType);
3690
Hans Wennborg776d7122012-09-26 09:34:53 +00003691 private:
3692 // Depending on the contents of the table, it can be represented in
3693 // different ways.
3694 enum {
3695 // For tables where each element contains the same value, we just have to
3696 // store that single value and return it for each lookup.
3697 SingleValueKind,
3698
Erik Eckstein105374f2014-11-17 09:13:57 +00003699 // For tables where there is a linear relationship between table index
3700 // and values. We calculate the result with a simple multiplication
3701 // and addition instead of a table lookup.
3702 LinearMapKind,
3703
Hans Wennborg39583b82012-09-26 09:44:49 +00003704 // For small tables with integer elements, we can pack them into a bitmap
3705 // that fits into a target-legal register. Values are retrieved by
3706 // shift and mask operations.
3707 BitMapKind,
3708
Hans Wennborg776d7122012-09-26 09:34:53 +00003709 // The table is stored as an array of values. Values are retrieved by load
3710 // instructions from the table.
3711 ArrayKind
3712 } Kind;
3713
3714 // For SingleValueKind, this is the single value.
3715 Constant *SingleValue;
3716
Hans Wennborg39583b82012-09-26 09:44:49 +00003717 // For BitMapKind, this is the bitmap.
3718 ConstantInt *BitMap;
3719 IntegerType *BitMapElementTy;
3720
Erik Eckstein105374f2014-11-17 09:13:57 +00003721 // For LinearMapKind, these are the constants used to derive the value.
3722 ConstantInt *LinearOffset;
3723 ConstantInt *LinearMultiplier;
3724
Hans Wennborg776d7122012-09-26 09:34:53 +00003725 // For ArrayKind, this is the array.
3726 GlobalVariable *Array;
3727 };
3728}
3729
3730SwitchLookupTable::SwitchLookupTable(Module &M,
3731 uint64_t TableSize,
3732 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003733 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003734 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003735 const DataLayout *DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003736 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003737 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003738 assert(Values.size() && "Can't build lookup table without values!");
3739 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003740
3741 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003742 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003743
Hans Wennborgac114a32014-01-12 00:44:41 +00003744 Type *ValueType = Values.begin()->second->getType();
3745
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003746 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003747 SmallVector<Constant*, 64> TableContents(TableSize);
3748 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3749 ConstantInt *CaseVal = Values[I].first;
3750 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003751 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003752
Hans Wennborg776d7122012-09-26 09:34:53 +00003753 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3754 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003755 TableContents[Idx] = CaseRes;
3756
Hans Wennborg776d7122012-09-26 09:34:53 +00003757 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003758 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003759 }
3760
3761 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003762 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003763 assert(DefaultValue &&
3764 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003765 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003766 for (uint64_t I = 0; I < TableSize; ++I) {
3767 if (!TableContents[I])
3768 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003769 }
3770
Hans Wennborg776d7122012-09-26 09:34:53 +00003771 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003772 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003773 }
3774
Hans Wennborg776d7122012-09-26 09:34:53 +00003775 // If each element in the table contains the same value, we only need to store
3776 // that single value.
3777 if (SingleValue) {
3778 Kind = SingleValueKind;
3779 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003780 }
3781
Erik Eckstein105374f2014-11-17 09:13:57 +00003782 // Check if we can derive the value with a linear transformation from the
3783 // table index.
3784 if (isa<IntegerType>(ValueType)) {
3785 bool LinearMappingPossible = true;
3786 APInt PrevVal;
3787 APInt DistToPrev;
3788 assert(TableSize >= 2 && "Should be a SingleValue table.");
3789 // Check if there is the same distance between two consecutive values.
3790 for (uint64_t I = 0; I < TableSize; ++I) {
3791 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3792 if (!ConstVal) {
3793 // This is an undef. We could deal with it, but undefs in lookup tables
3794 // are very seldom. It's probably not worth the additional complexity.
3795 LinearMappingPossible = false;
3796 break;
3797 }
3798 APInt Val = ConstVal->getValue();
3799 if (I != 0) {
3800 APInt Dist = Val - PrevVal;
3801 if (I == 1) {
3802 DistToPrev = Dist;
3803 } else if (Dist != DistToPrev) {
3804 LinearMappingPossible = false;
3805 break;
3806 }
3807 }
3808 PrevVal = Val;
3809 }
3810 if (LinearMappingPossible) {
3811 LinearOffset = cast<ConstantInt>(TableContents[0]);
3812 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3813 Kind = LinearMapKind;
3814 ++NumLinearMaps;
3815 return;
3816 }
3817 }
3818
Hans Wennborg39583b82012-09-26 09:44:49 +00003819 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003820 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003821 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003822 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3823 for (uint64_t I = TableSize; I > 0; --I) {
3824 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003825 // Insert values into the bitmap. Undef values are set to zero.
3826 if (!isa<UndefValue>(TableContents[I - 1])) {
3827 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3828 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3829 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003830 }
3831 BitMap = ConstantInt::get(M.getContext(), TableInt);
3832 BitMapElementTy = IT;
3833 Kind = BitMapKind;
3834 ++NumBitMaps;
3835 return;
3836 }
3837
Hans Wennborg776d7122012-09-26 09:34:53 +00003838 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003839 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003840 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3841
Hans Wennborg776d7122012-09-26 09:34:53 +00003842 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3843 GlobalVariable::PrivateLinkage,
3844 Initializer,
3845 "switch.table");
3846 Array->setUnnamedAddr(true);
3847 Kind = ArrayKind;
3848}
3849
Manman Ren4d189fb2014-07-24 21:13:20 +00003850Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003851 switch (Kind) {
3852 case SingleValueKind:
3853 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00003854 case LinearMapKind: {
3855 // Derive the result value from the input value.
3856 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3857 false, "switch.idx.cast");
3858 if (!LinearMultiplier->isOne())
3859 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3860 if (!LinearOffset->isZero())
3861 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3862 return Result;
3863 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003864 case BitMapKind: {
3865 // Type of the bitmap (e.g. i59).
3866 IntegerType *MapTy = BitMap->getType();
3867
3868 // Cast Index to the same type as the bitmap.
3869 // Note: The Index is <= the number of elements in the table, so
3870 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003871 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003872
3873 // Multiply the shift amount by the element width.
3874 ShiftAmt = Builder.CreateMul(ShiftAmt,
3875 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3876 "switch.shiftamt");
3877
3878 // Shift down.
3879 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3880 "switch.downshift");
3881 // Mask off.
3882 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3883 "switch.masked");
3884 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003885 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003886 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003887 IntegerType *IT = cast<IntegerType>(Index->getType());
3888 uint64_t TableSize = Array->getInitializer()->getType()
3889 ->getArrayNumElements();
3890 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3891 Index = Builder.CreateZExt(Index,
3892 IntegerType::get(IT->getContext(),
3893 IT->getBitWidth() + 1),
3894 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003895
Hans Wennborg776d7122012-09-26 09:34:53 +00003896 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3897 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3898 "switch.gep");
3899 return Builder.CreateLoad(GEP, "switch.load");
3900 }
3901 }
3902 llvm_unreachable("Unknown lookup table kind!");
3903}
3904
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003905bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003906 uint64_t TableSize,
3907 const Type *ElementType) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003908 if (!DL)
Hans Wennborg39583b82012-09-26 09:44:49 +00003909 return false;
3910 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3911 if (!IT)
3912 return false;
3913 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3914 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003915
3916 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3917 if (TableSize >= UINT_MAX/IT->getBitWidth())
3918 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003919 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003920}
3921
Hans Wennborg776d7122012-09-26 09:34:53 +00003922/// ShouldBuildLookupTable - Determine whether a lookup table should be built
Hans Wennborg5cf30be2013-06-04 11:22:30 +00003923/// for this switch, based on the number of cases, size of the table and the
Hans Wennborg776d7122012-09-26 09:34:53 +00003924/// types of the results.
3925static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003926 uint64_t TableSize,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003927 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003928 const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003929 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003930 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3931 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003932
Chandler Carruth77d433d2012-11-30 09:26:25 +00003933 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003934 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00003935 for (const auto &I : ResultTypes) {
3936 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003937
3938 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003939 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003940
3941 // Saturate this flag to false.
3942 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003943 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003944
3945 // If both flags saturate, we're done. NOTE: This *only* works with
3946 // saturating flags, and all flags have to saturate first due to the
3947 // non-deterministic behavior of iterating over a dense map.
3948 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003949 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003950 }
Evan Cheng65df8082012-11-30 02:02:42 +00003951
Chandler Carruth77d433d2012-11-30 09:26:25 +00003952 // If each table would fit in a register, we should build it anyway.
3953 if (AllTablesFitInRegister)
3954 return true;
3955
3956 // Don't build a table that doesn't fit in-register if it has illegal types.
3957 if (HasIllegalType)
3958 return false;
3959
3960 // The table density should be at least 40%. This is the same criterion as for
3961 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3962 // FIXME: Find the best cut-off.
3963 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003964}
3965
3966/// SwitchToLookupTable - If the switch is only used to initialize one or more
3967/// phi nodes in a common successor block with different constant values,
3968/// replace the switch with lookup tables.
3969static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003970 IRBuilder<> &Builder,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003971 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003972 const DataLayout* DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003973 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00003974
Hans Wennborgc3c8d952012-11-07 21:35:12 +00003975 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003976 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00003977 return false;
3978
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003979 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3980 // split off a dense part and build a lookup table for that.
3981
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003982 // FIXME: This creates arrays of GEPs to constant strings, which means each
3983 // GEP needs a runtime relocation in PIC code. We should just build one big
3984 // string and lookup indices into that.
3985
Hans Wennborg4744ac12014-01-15 05:00:27 +00003986 // Ignore switches with less than three cases. Lookup tables will not make them
3987 // faster, so we don't analyze them.
3988 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003989 return false;
3990
3991 // Figure out the corresponding result for each case value and phi node in the
3992 // common destination, as well as the the min and max case values.
3993 assert(SI->case_begin() != SI->case_end());
3994 SwitchInst::CaseIt CI = SI->case_begin();
3995 ConstantInt *MinCaseVal = CI.getCaseValue();
3996 ConstantInt *MaxCaseVal = CI.getCaseValue();
3997
Craig Topperf40110f2014-04-25 05:29:35 +00003998 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003999 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004000 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4001 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4002 SmallDenseMap<PHINode*, Type*> ResultTypes;
4003 SmallVector<PHINode*, 4> PHIs;
4004
4005 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4006 ConstantInt *CaseVal = CI.getCaseValue();
4007 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4008 MinCaseVal = CaseVal;
4009 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4010 MaxCaseVal = CaseVal;
4011
4012 // Resulting value at phi nodes for this case value.
4013 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4014 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004015 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004016 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004017 return false;
4018
4019 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004020 for (const auto &I : Results) {
4021 PHINode *PHI = I.first;
4022 Constant *Value = I.second;
4023 if (!ResultLists.count(PHI))
4024 PHIs.push_back(PHI);
4025 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004026 }
4027 }
4028
Hans Wennborgac114a32014-01-12 00:44:41 +00004029 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004030 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004031 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4032 }
4033
4034 uint64_t NumResults = ResultLists[PHIs[0]].size();
4035 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4036 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4037 bool TableHasHoles = (NumResults < TableSize);
4038
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004039 // If the table has holes, we need a constant result for the default case
4040 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004041 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004042 bool HasDefaultResults = false;
4043 if (TableHasHoles) {
Craig Topperf40110f2014-04-25 05:29:35 +00004044 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4045 &CommonDest, DefaultResultsList, DL);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004046 }
Hans Wennborga6a11a92014-11-18 02:37:11 +00004047
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004048 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4049 if (NeedMask) {
4050 // As an extra penalty for the validity test we require more cases.
4051 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4052 return false;
4053 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4054 return false;
4055 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004056
Hans Wennborga6a11a92014-11-18 02:37:11 +00004057 for (const auto &I : DefaultResultsList) {
4058 PHINode *PHI = I.first;
4059 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004060 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004061 }
4062
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004063 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004064 return false;
4065
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004066 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004067 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004068 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4069 "switch.lookup",
4070 CommonDest->getParent(),
4071 CommonDest);
4072
Michael Gottesmanc024f322013-10-20 07:04:37 +00004073 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004074 Builder.SetInsertPoint(SI);
4075 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4076 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004077
4078 // Compute the maximum table size representable by the integer type we are
4079 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004080 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004081 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004082 assert(MaxTableSize >= TableSize &&
4083 "It is impossible for a switch to have more entries than the max "
4084 "representable value of its input integer type's size.");
4085
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004086 // If we have a fully covered lookup table, unconditionally branch to the
4087 // lookup table BB. Otherwise, check if the condition value is within the case
4088 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
4089 // destination.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004090 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
4091 if (GeneratingCoveredLookupTable) {
4092 Builder.CreateBr(LookupBB);
Manman Ren062f58d2014-08-02 23:41:54 +00004093 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4094 // do not delete PHINodes here.
4095 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4096 true/*DontDeleteUselessPHIs*/);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004097 } else {
4098 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004099 MinCaseVal->getType(), TableSize));
Michael Gottesmanc024f322013-10-20 07:04:37 +00004100 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4101 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004102
4103 // Populate the BB that does the lookups.
4104 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004105
4106 if (NeedMask) {
4107 // Before doing the lookup we do the hole check.
4108 // The LookupBB is therefore re-purposed to do the hole check
4109 // and we create a new LookupBB.
4110 BasicBlock *MaskBB = LookupBB;
4111 MaskBB->setName("switch.hole_check");
4112 LookupBB = BasicBlock::Create(Mod.getContext(),
4113 "switch.lookup",
4114 CommonDest->getParent(),
4115 CommonDest);
4116
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004117 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4118 // unnecessary illegal types.
4119 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4120 APInt MaskInt(TableSizePowOf2, 0);
4121 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004122 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004123 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4124 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4125 uint64_t Idx = (ResultList[I].first->getValue() -
4126 MinCaseVal->getValue()).getLimitedValue();
4127 MaskInt |= One << Idx;
4128 }
4129 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4130
4131 // Get the TableIndex'th bit of the bitmask.
4132 // If this bit is 0 (meaning hole) jump to the default destination,
4133 // else continue with table lookup.
4134 IntegerType *MapTy = TableMask->getType();
4135 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4136 "switch.maskindex");
4137 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4138 "switch.shifted");
4139 Value *LoBit = Builder.CreateTrunc(Shifted,
4140 Type::getInt1Ty(Mod.getContext()),
4141 "switch.lobit");
4142 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4143
4144 Builder.SetInsertPoint(LookupBB);
4145 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4146 }
4147
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004148 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004149 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4150 PHINode *PHI = PHIs[I];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004151
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004152 // If using a bitmask, use any value to fill the lookup table holes.
4153 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Hans Wennborg776d7122012-09-26 09:34:53 +00004154 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004155 DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004156
Manman Ren4d189fb2014-07-24 21:13:20 +00004157 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004158
Hans Wennborgf744fa92012-09-19 14:24:21 +00004159 // If the result is used to return immediately from the function, we want to
4160 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004161 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4162 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004163 Builder.CreateRet(Result);
4164 ReturnedEarly = true;
4165 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004166 }
4167
Hans Wennborgf744fa92012-09-19 14:24:21 +00004168 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004169 }
4170
4171 if (!ReturnedEarly)
4172 Builder.CreateBr(CommonDest);
4173
4174 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004175 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004176 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004177
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004178 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004179 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004180 Succ->removePredecessor(SI->getParent());
4181 }
4182 SI->eraseFromParent();
4183
4184 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004185 if (NeedMask)
4186 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004187 return true;
4188}
4189
Devang Patela7ec47d2011-05-18 20:35:38 +00004190bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004191 BasicBlock *BB = SI->getParent();
4192
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004193 if (isValueEqualityComparison(SI)) {
4194 // If we only have one predecessor, and if it is a branch on this value,
4195 // see if that predecessor totally determines the outcome of this switch.
4196 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4197 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004198 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004199
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004200 Value *Cond = SI->getCondition();
4201 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4202 if (SimplifySwitchOnSelect(SI, Select))
Jingyue Wufc029672014-09-30 22:23:38 +00004203 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004204
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004205 // If the block only contains the switch, see if we can fold the block
4206 // away into any preds.
4207 BasicBlock::iterator BBI = BB->begin();
4208 // Ignore dbg intrinsics.
4209 while (isa<DbgInfoIntrinsic>(BBI))
4210 ++BBI;
4211 if (SI == &*BBI)
4212 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004213 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004214 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004215
4216 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004217 if (TurnSwitchRangeIntoICmp(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004218 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004219
4220 // Remove unreachable cases.
Hal Finkel60db0582014-09-07 18:57:58 +00004221 if (EliminateDeadSwitchCases(SI, DL, AT))
Jingyue Wufc029672014-09-30 22:23:38 +00004222 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004223
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004224 if (SwitchToSelect(SI, Builder, DL, AT))
4225 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4226
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004227 if (ForwardSwitchConditionToPHI(SI))
Jingyue Wufc029672014-09-30 22:23:38 +00004228 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004229
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004230 if (SwitchToLookupTable(SI, Builder, TTI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004231 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004232
Chris Lattner25c3af32010-12-13 06:25:44 +00004233 return false;
4234}
4235
4236bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4237 BasicBlock *BB = IBI->getParent();
4238 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004239
Chris Lattner25c3af32010-12-13 06:25:44 +00004240 // Eliminate redundant destinations.
4241 SmallPtrSet<Value *, 8> Succs;
4242 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4243 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004244 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004245 Dest->removePredecessor(BB);
4246 IBI->removeDestination(i);
4247 --i; --e;
4248 Changed = true;
4249 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004250 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004251
4252 if (IBI->getNumDestinations() == 0) {
4253 // If the indirectbr has no successors, change it to unreachable.
4254 new UnreachableInst(IBI->getContext(), IBI);
4255 EraseTerminatorInstAndDCECond(IBI);
4256 return true;
4257 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004258
Chris Lattner25c3af32010-12-13 06:25:44 +00004259 if (IBI->getNumDestinations() == 1) {
4260 // If the indirectbr has one successor, change it to a direct branch.
4261 BranchInst::Create(IBI->getDestination(0), IBI);
4262 EraseTerminatorInstAndDCECond(IBI);
4263 return true;
4264 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004265
Chris Lattner25c3af32010-12-13 06:25:44 +00004266 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4267 if (SimplifyIndirectBrOnSelect(IBI, SI))
Jingyue Wufc029672014-09-30 22:23:38 +00004268 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004269 }
4270 return Changed;
4271}
4272
Devang Patel767f6932011-05-18 18:28:48 +00004273bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004274 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004275
Manman Ren93ab6492012-09-20 22:37:36 +00004276 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4277 return true;
4278
Chris Lattner25c3af32010-12-13 06:25:44 +00004279 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004280 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004281 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4282 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4283 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004284
Chris Lattner25c3af32010-12-13 06:25:44 +00004285 // If the only instruction in the block is a seteq/setne comparison
4286 // against a constant, try to simplify the block.
4287 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4288 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4289 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4290 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004291 if (I->isTerminator() &&
Jingyue Wufc029672014-09-30 22:23:38 +00004292 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4293 BonusInstThreshold, DL, AT))
Chris Lattner25c3af32010-12-13 06:25:44 +00004294 return true;
4295 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004296
Manman Rend33f4ef2012-06-13 05:43:29 +00004297 // If this basic block is ONLY a compare and a branch, and if a predecessor
4298 // branches to us and our successor, fold the comparison into the
4299 // predecessor and use logical operations to update the incoming value
4300 // for PHI nodes in common successor.
Jingyue Wufc029672014-09-30 22:23:38 +00004301 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4302 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004303 return false;
4304}
4305
4306
Devang Patela7ec47d2011-05-18 20:35:38 +00004307bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004308 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004309
Chris Lattner25c3af32010-12-13 06:25:44 +00004310 // Conditional branch
4311 if (isValueEqualityComparison(BI)) {
4312 // If we only have one predecessor, and if it is a branch on this value,
4313 // see if that predecessor totally determines the outcome of this
4314 // switch.
4315 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004316 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004317 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004318
Chris Lattner25c3af32010-12-13 06:25:44 +00004319 // This block must be empty, except for the setcond inst, if it exists.
4320 // Ignore dbg intrinsics.
4321 BasicBlock::iterator I = BB->begin();
4322 // Ignore dbg intrinsics.
4323 while (isa<DbgInfoIntrinsic>(I))
4324 ++I;
4325 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004326 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004327 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004328 } else if (&*I == cast<Instruction>(BI->getCondition())){
4329 ++I;
4330 // Ignore dbg intrinsics.
4331 while (isa<DbgInfoIntrinsic>(I))
4332 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004333 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004334 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004335 }
4336 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004337
Chris Lattner25c3af32010-12-13 06:25:44 +00004338 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004339 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004340 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004341
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004342 // If this basic block is ONLY a compare and a branch, and if a predecessor
4343 // branches to us and one of our successors, fold the comparison into the
4344 // predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00004345 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4346 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004347
Chris Lattner25c3af32010-12-13 06:25:44 +00004348 // We have a conditional branch to two blocks that are only reachable
4349 // from BI. We know that the condbr dominates the two blocks, so see if
4350 // there is any identical code in the "then" and "else" blocks. If so, we
4351 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004352 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4353 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Hal Finkela995f922014-07-10 14:41:31 +00004354 if (HoistThenElseCodeToIf(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004355 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004356 } else {
4357 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004358 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004359 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4360 if (Succ0TI->getNumSuccessors() == 1 &&
4361 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Hal Finkela995f922014-07-10 14:41:31 +00004362 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004363 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004364 }
Craig Topperf40110f2014-04-25 05:29:35 +00004365 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004366 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004367 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004368 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4369 if (Succ1TI->getNumSuccessors() == 1 &&
4370 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Hal Finkela995f922014-07-10 14:41:31 +00004371 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004372 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004373 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004374
Chris Lattner25c3af32010-12-13 06:25:44 +00004375 // If this is a branch on a phi node in the current block, thread control
4376 // through this block if any PHI node entries are constants.
4377 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4378 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004379 if (FoldCondBranchOnPHI(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004380 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004381
Chris Lattner25c3af32010-12-13 06:25:44 +00004382 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004383 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4384 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004385 if (PBI != BI && PBI->isConditional())
4386 if (SimplifyCondBranchToCondBranch(PBI, BI))
Jingyue Wufc029672014-09-30 22:23:38 +00004387 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004388
4389 return false;
4390}
4391
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004392/// Check if passing a value to an instruction will cause undefined behavior.
4393static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4394 Constant *C = dyn_cast<Constant>(V);
4395 if (!C)
4396 return false;
4397
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004398 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004399 return false;
4400
4401 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004402 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004403 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004404
4405 // Now make sure that there are no instructions in between that can alter
4406 // control flow (eg. calls)
4407 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004408 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004409 return false;
4410
4411 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4412 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4413 if (GEP->getPointerOperand() == I)
4414 return passingValueIsAlwaysUndefined(V, GEP);
4415
4416 // Look through bitcasts.
4417 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4418 return passingValueIsAlwaysUndefined(V, BC);
4419
Benjamin Kramer0655b782011-08-26 02:25:55 +00004420 // Load from null is undefined.
4421 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004422 if (!LI->isVolatile())
4423 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004424
Benjamin Kramer0655b782011-08-26 02:25:55 +00004425 // Store to null is undefined.
4426 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004427 if (!SI->isVolatile())
4428 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004429 }
4430 return false;
4431}
4432
4433/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004434/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004435static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4436 for (BasicBlock::iterator i = BB->begin();
4437 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4438 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4439 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4440 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4441 IRBuilder<> Builder(T);
4442 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4443 BB->removePredecessor(PHI->getIncomingBlock(i));
4444 // Turn uncoditional branches into unreachables and remove the dead
4445 // destination from conditional branches.
4446 if (BI->isUnconditional())
4447 Builder.CreateUnreachable();
4448 else
4449 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4450 BI->getSuccessor(0));
4451 BI->eraseFromParent();
4452 return true;
4453 }
4454 // TODO: SwitchInst.
4455 }
4456
4457 return false;
4458}
4459
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004460bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004461 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004462
Chris Lattnerd7beca32010-12-14 06:17:25 +00004463 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004464 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004465
Dan Gohman4a63fad2010-08-14 00:29:42 +00004466 // Remove basic blocks that have no predecessors (except the entry block)...
4467 // or that just have themself as a predecessor. These are unreachable.
Chris Lattnerd7beca32010-12-14 06:17:25 +00004468 if ((pred_begin(BB) == pred_end(BB) &&
4469 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004470 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004471 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004472 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004473 return true;
4474 }
4475
Chris Lattner031340a2003-08-17 19:41:53 +00004476 // Check to see if we can constant propagate this terminator instruction
4477 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004478 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004479
Dan Gohman1a951062009-10-30 22:39:04 +00004480 // Check for and eliminate duplicate PHI nodes in this block.
4481 Changed |= EliminateDuplicatePHINodes(BB);
4482
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004483 // Check for and remove branches that will always cause undefined behavior.
4484 Changed |= removeUndefIntroducingPredecessor(BB);
4485
Chris Lattner2e3832d2010-12-13 05:10:48 +00004486 // Merge basic blocks into their predecessor if there is only one distinct
4487 // pred, and if there is only one distinct successor of the predecessor, and
4488 // if there are no PHI nodes.
4489 //
4490 if (MergeBlockIntoPredecessor(BB))
4491 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004492
Devang Patel15ad6762011-05-18 18:01:27 +00004493 IRBuilder<> Builder(BB);
4494
Dan Gohman20af5a02008-03-11 21:53:06 +00004495 // If there is a trivial two-entry PHI node in this basic block, and we can
4496 // eliminate it, do so now.
4497 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4498 if (PN->getNumIncomingValues() == 2)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004499 Changed |= FoldTwoEntryPHINode(PN, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004500
Devang Patela7ec47d2011-05-18 20:35:38 +00004501 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004502 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004503 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004504 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004505 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004506 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004507 }
4508 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004509 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004510 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4511 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004512 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004513 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004514 } else if (UnreachableInst *UI =
4515 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4516 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004517 } else if (IndirectBrInst *IBI =
4518 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4519 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004520 }
4521
Chris Lattner031340a2003-08-17 19:41:53 +00004522 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004523}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004524
4525/// SimplifyCFG - This function is used to do simplification of a CFG. For
4526/// example, it adjusts branches to branches to eliminate the extra hop, it
4527/// eliminates unreachable basic blocks, and does other "peephole" optimization
4528/// of the CFG. It returns true if a modification was made.
4529///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004530bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00004531 unsigned BonusInstThreshold,
Hal Finkel60db0582014-09-07 18:57:58 +00004532 const DataLayout *DL, AssumptionTracker *AT) {
Jingyue Wufc029672014-09-30 22:23:38 +00004533 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004534}