blob: 3248a83636c4a1abb1eca9924fc4f48549637342 [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
James Molloy1b6207e2015-02-13 10:48:30 +000056// Chosen as 2 so as to be cheap, but still to have enough power to fold
57// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
58// To catch this, we need to fold a compare and a select, hence '2' being the
59// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000060static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000061PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
62 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000063
Evan Chengd983eba2011-01-29 04:46:23 +000064static cl::opt<bool>
65DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
66 cl::desc("Duplicate return instructions into unconditional branches"));
67
Manman Ren93ab6492012-09-20 22:37:36 +000068static cl::opt<bool>
69SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
70 cl::desc("Sink common instructions down to the end block"));
71
Alp Tokercb402912014-01-24 17:20:08 +000072static cl::opt<bool> HoistCondStores(
73 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
74 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000075
Hans Wennborg39583b82012-09-26 09:44:49 +000076STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000077STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000078STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000079STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000080STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000081STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000082STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000083
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000084namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000085 // The first field contains the value that the switch produces when a certain
86 // case group is selected, and the second field is a vector containing the cases
87 // composing the case group.
88 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
89 SwitchCaseResultVectorTy;
90 // The first field contains the phi node that generates a result of the switch
91 // and the second field contains the value generated for a certain case in the switch
92 // for that PHI.
93 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
94
Eric Christopherb65acc62012-07-02 23:22:21 +000095 /// ValueEqualityComparisonCase - Represents a case of a switch.
96 struct ValueEqualityComparisonCase {
97 ConstantInt *Value;
98 BasicBlock *Dest;
99
100 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
101 : Value(Value), Dest(Dest) {}
102
103 bool operator<(ValueEqualityComparisonCase RHS) const {
104 // Comparing pointers is ok as we only rely on the order for uniquing.
105 return Value < RHS.Value;
106 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000107
108 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000109 };
110
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000111class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000112 const TargetTransformInfo &TTI;
Jingyue Wufc029672014-09-30 22:23:38 +0000113 unsigned BonusInstThreshold;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000114 const DataLayout *const DL;
Chandler Carruth66b31302015-01-04 12:03:27 +0000115 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000116 Value *isValueEqualityComparison(TerminatorInst *TI);
117 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000118 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000119 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000120 BasicBlock *Pred,
121 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000122 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
123 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000124
Devang Pateldd14e0f2011-05-18 21:33:11 +0000125 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000126 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000127 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000128 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000129 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000130 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000131 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000132
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133public:
Jingyue Wufc029672014-09-30 22:23:38 +0000134 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
Chandler Carruth66b31302015-01-04 12:03:27 +0000135 const DataLayout *DL, AssumptionCache *AC)
136 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000137 bool run(BasicBlock *BB);
138};
139}
140
Chris Lattner76dc2042005-08-03 00:19:45 +0000141/// SafeToMergeTerminators - Return true if it is safe to merge these two
142/// terminator instructions together.
143///
144static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
145 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000146
Chris Lattner76dc2042005-08-03 00:19:45 +0000147 // It is not safe to merge these two switch instructions if they have a common
148 // successor, and if that successor has a PHI node, and if *that* PHI node has
149 // conflicting incoming values from the two switch blocks.
150 BasicBlock *SI1BB = SI1->getParent();
151 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000152 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000153
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000154 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
155 if (SI1Succs.count(*I))
156 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000157 isa<PHINode>(BBI); ++BBI) {
158 PHINode *PN = cast<PHINode>(BBI);
159 if (PN->getIncomingValueForBlock(SI1BB) !=
160 PN->getIncomingValueForBlock(SI2BB))
161 return false;
162 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000163
Chris Lattner76dc2042005-08-03 00:19:45 +0000164 return true;
165}
166
Manman Rend33f4ef2012-06-13 05:43:29 +0000167/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
168/// to merge these two terminator instructions together, where SI1 is an
169/// unconditional branch. PhiNodes will store all PHI nodes in common
170/// successors.
171///
172static bool isProfitableToFoldUnconditional(BranchInst *SI1,
173 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000174 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000175 SmallVectorImpl<PHINode*> &PhiNodes) {
176 if (SI1 == SI2) return false; // Can't merge with self!
177 assert(SI1->isUnconditional() && SI2->isConditional());
178
179 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000180 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000181 // 1> We have a constant incoming value for the conditional branch;
182 // 2> We have "Cond" as the incoming value for the unconditional branch;
183 // 3> SI2->getCondition() and Cond have same operands.
184 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
185 if (!Ci2) return false;
186 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
187 Cond->getOperand(1) == Ci2->getOperand(1)) &&
188 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
189 Cond->getOperand(1) == Ci2->getOperand(0)))
190 return false;
191
192 BasicBlock *SI1BB = SI1->getParent();
193 BasicBlock *SI2BB = SI2->getParent();
194 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000195 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
196 if (SI1Succs.count(*I))
197 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000198 isa<PHINode>(BBI); ++BBI) {
199 PHINode *PN = cast<PHINode>(BBI);
200 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000201 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000202 return false;
203 PhiNodes.push_back(PN);
204 }
205 return true;
206}
207
Chris Lattner76dc2042005-08-03 00:19:45 +0000208/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
209/// now be entries in it from the 'NewPred' block. The values that will be
210/// flowing into the PHI nodes will be the same as those coming in from
211/// ExistPred, an existing predecessor of Succ.
212static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
213 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000214 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000215
Chris Lattner80b03a12008-07-13 22:23:11 +0000216 PHINode *PN;
217 for (BasicBlock::iterator I = Succ->begin();
218 (PN = dyn_cast<PHINode>(I)); ++I)
219 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000220}
221
David Majnemer91142c42013-06-01 19:43:23 +0000222/// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
James Molloy7c336572015-02-11 12:15:41 +0000223/// given instruction, which is assumed to be safe to speculate. TCC_Free means
224/// cheap, TCC_Basic means less cheap, and TCC_Expensive means prohibitively
225/// expensive.
226static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL,
227 const TargetTransformInfo &TTI) {
Hal Finkela995f922014-07-10 14:41:31 +0000228 assert(isSafeToSpeculativelyExecute(I, DL) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000229 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000230 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000231}
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000232/// DominatesMergePoint - If we have a merge point of an "if condition" as
233/// accepted above, return true if the specified value dominates the block. We
234/// don't handle the true generality of domination here, just a special case
235/// which works well enough for us.
236///
237/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000238/// see if V (which must be an instruction) and its recursive operands
239/// that do not dominate BB have a combined cost lower than CostRemaining and
240/// are non-trapping. If both are true, the instruction is inserted into the
241/// set and true is returned.
242///
243/// The cost for most non-trapping instructions is defined as 1 except for
244/// Select whose cost is 2.
245///
246/// After this function returns, CostRemaining is decreased by the cost of
247/// V plus its non-dominating operands. If that cost is greater than
248/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000249static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000250 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000251 unsigned &CostRemaining,
James Molloy7c336572015-02-11 12:15:41 +0000252 const DataLayout *DL,
253 const TargetTransformInfo &TTI) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000254 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000255 if (!I) {
256 // Non-instructions all dominate instructions, but not all constantexprs
257 // can be executed unconditionally.
258 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
259 if (C->canTrap())
260 return false;
261 return true;
262 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000263 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000264
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000265 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000266 // the bottom of this block.
267 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000268
Chris Lattner0aa56562004-04-09 22:50:22 +0000269 // If this instruction is defined in a block that contains an unconditional
270 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000271 // statement". If not, it definitely dominates the region.
272 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000273 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000274 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000275
Chris Lattner9ac168d2010-12-14 07:41:39 +0000276 // If we aren't allowing aggressive promotion anymore, then don't consider
277 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000278 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000279
Peter Collingbournee3511e12011-04-29 18:47:31 +0000280 // If we have seen this instruction before, don't count it again.
281 if (AggressiveInsts->count(I)) return true;
282
Chris Lattner9ac168d2010-12-14 07:41:39 +0000283 // Okay, it looks like the instruction IS in the "condition". Check to
284 // see if it's a cheap instruction to unconditionally compute, and if it
285 // only uses stuff defined outside of the condition. If so, hoist it out.
Hal Finkela995f922014-07-10 14:41:31 +0000286 if (!isSafeToSpeculativelyExecute(I, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000287 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000288
James Molloy7c336572015-02-11 12:15:41 +0000289 unsigned Cost = ComputeSpeculationCost(I, DL, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000290
Peter Collingbournee3511e12011-04-29 18:47:31 +0000291 if (Cost > CostRemaining)
292 return false;
293
294 CostRemaining -= Cost;
295
296 // Okay, we can only really hoist these out if their operands do
297 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000298 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
James Molloy7c336572015-02-11 12:15:41 +0000299 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL, TTI))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000300 return false;
301 // Okay, it's safe to do this! Remember this instruction.
302 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000303 return true;
304}
Chris Lattner466a0492002-05-21 20:50:24 +0000305
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000306/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
307/// and PointerNullValue. Return NULL if value is not a constant int.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000308static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000309 // Normal constant int.
310 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000311 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000312 return CI;
313
314 // This is some kind of pointer constant. Turn it into a pointer-sized
315 // ConstantInt if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000316 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000317
318 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
319 if (isa<ConstantPointerNull>(V))
320 return ConstantInt::get(PtrTy, 0);
321
322 // IntToPtr const int.
323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
324 if (CE->getOpcode() == Instruction::IntToPtr)
325 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
326 // The constant is very likely to have the right type already.
327 if (CI->getType() == PtrTy)
328 return CI;
329 else
330 return cast<ConstantInt>
331 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
332 }
Craig Topperf40110f2014-04-25 05:29:35 +0000333 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000334}
335
Mehdi Aminiffd01002014-11-20 22:40:25 +0000336namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000337
Mehdi Aminiffd01002014-11-20 22:40:25 +0000338/// Given a chain of or (||) or and (&&) comparison of a value against a
339/// constant, this will try to recover the information required for a switch
340/// structure.
341/// It will depth-first traverse the chain of comparison, seeking for patterns
342/// like %a == 12 or %a < 4 and combine them to produce a set of integer
343/// representing the different cases for the switch.
344/// Note that if the chain is composed of '||' it will build the set of elements
345/// that matches the comparisons (i.e. any of this value validate the chain)
346/// while for a chain of '&&' it will build the set elements that make the test
347/// fail.
348struct ConstantComparesGatherer {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000349
Mehdi Aminiffd01002014-11-20 22:40:25 +0000350 Value *CompValue; /// Value found for the switch comparison
351 Value *Extra; /// Extra clause to be checked before the switch
352 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
353 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000354
Mehdi Aminiffd01002014-11-20 22:40:25 +0000355 /// Construct and compute the result for the comparison instruction Cond
356 ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
357 : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
358 gather(Cond, DL);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000359 }
360
Mehdi Aminiffd01002014-11-20 22:40:25 +0000361 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000362 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000363 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000364 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000365
Mehdi Aminiffd01002014-11-20 22:40:25 +0000366private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000367
Mehdi Aminiffd01002014-11-20 22:40:25 +0000368 /// Try to set the current value used for the comparison, it succeeds only if
369 /// it wasn't set before or if the new value is the same as the old one
370 bool setValueOnce(Value *NewVal) {
371 if(CompValue && CompValue != NewVal) return false;
372 CompValue = NewVal;
373 return (CompValue != nullptr);
374 }
375
376 /// Try to match Instruction "I" as a comparison against a constant and
377 /// populates the array Vals with the set of values that match (or do not
378 /// match depending on isEQ).
379 /// Return false on failure. On success, the Value the comparison matched
380 /// against is placed in CompValue.
381 /// If CompValue is already set, the function is expected to fail if a match
382 /// is found but the value compared to is different.
383 bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
384 // If this is an icmp against a constant, handle this as one of the cases.
385 ICmpInst *ICI;
386 ConstantInt *C;
387 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
388 (C = GetConstantInt(I->getOperand(1), DL)))) {
389 return false;
390 }
391
392 Value *RHSVal;
393 ConstantInt *RHSC;
394
395 // Pattern match a special case
396 // (x & ~2^x) == y --> x == y || x == y|2^x
397 // This undoes a transformation done by instcombine to fuse 2 compares.
398 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
399 if (match(ICI->getOperand(0),
400 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
401 APInt Not = ~RHSC->getValue();
402 if (Not.isPowerOf2()) {
403 // If we already have a value for the switch, it has to match!
404 if(!setValueOnce(RHSVal))
405 return false;
406
407 Vals.push_back(C);
408 Vals.push_back(ConstantInt::get(C->getContext(),
409 C->getValue() | Not));
410 UsedICmps++;
411 return true;
412 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000413 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000414
415 // If we already have a value for the switch, it has to match!
416 if(!setValueOnce(ICI->getOperand(0)))
417 return false;
418
419 UsedICmps++;
420 Vals.push_back(C);
421 return ICI->getOperand(0);
422 }
423
424 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
425 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
426 C->getValue());
427
428 // Shift the range if the compare is fed by an add. This is the range
429 // compare idiom as emitted by instcombine.
430 Value *CandidateVal = I->getOperand(0);
431 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
432 Span = Span.subtract(RHSC->getValue());
433 CandidateVal = RHSVal;
434 }
435
436 // If this is an and/!= check, then we are looking to build the set of
437 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
438 // x != 0 && x != 1.
439 if (!isEQ)
440 Span = Span.inverse();
441
442 // If there are a ton of values, we don't want to make a ginormous switch.
443 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
444 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000445 }
446
447 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000448 if(!setValueOnce(CandidateVal))
449 return false;
450
451 // Add all values from the range to the set
452 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
453 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000454
455 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000456 return true;
457
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000458 }
459
Mehdi Aminiffd01002014-11-20 22:40:25 +0000460 /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
461 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
462 /// the value being compared, and stick the list constants into the Vals
463 /// vector.
464 /// One "Extra" case is allowed to differ from the other.
465 void gather(Value *V, const DataLayout *DL) {
466 Instruction *I = dyn_cast<Instruction>(V);
467 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000468
Mehdi Aminiffd01002014-11-20 22:40:25 +0000469 // Keep a stack (SmallVector for efficiency) for depth-first traversal
470 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000471
Mehdi Aminiffd01002014-11-20 22:40:25 +0000472 // Initialize
473 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000474
Mehdi Aminiffd01002014-11-20 22:40:25 +0000475 while(!DFT.empty()) {
476 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000477
Mehdi Aminiffd01002014-11-20 22:40:25 +0000478 if (Instruction *I = dyn_cast<Instruction>(V)) {
479 // If it is a || (or && depending on isEQ), process the operands.
480 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
481 DFT.push_back(I->getOperand(1));
482 DFT.push_back(I->getOperand(0));
483 continue;
484 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000485
Mehdi Aminiffd01002014-11-20 22:40:25 +0000486 // Try to match the current instruction
487 if (matchInstruction(I, DL, isEQ))
488 // Match succeed, continue the loop
489 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000490 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000491
Mehdi Aminiffd01002014-11-20 22:40:25 +0000492 // One element of the sequence of || (or &&) could not be match as a
493 // comparison against the same value as the others.
494 // We allow only one "Extra" case to be checked before the switch
495 if (!Extra) {
496 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000497 continue;
498 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000499 // Failed to parse a proper sequence, abort now
500 CompValue = nullptr;
501 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000502 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000503 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000504};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000505
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000506}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000507
Eli Friedmancb61afb2008-12-16 20:54:32 +0000508static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000509 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000510 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
511 Cond = dyn_cast<Instruction>(SI->getCondition());
512 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
513 if (BI->isConditional())
514 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000515 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
516 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000517 }
518
519 TI->eraseFromParent();
520 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
521}
522
Chris Lattner8e84c122008-11-27 23:25:44 +0000523/// isValueEqualityComparison - Return true if the specified terminator checks
524/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000525Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000526 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000527 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
528 // Do not permit merging of large switch instructions into their
529 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000530 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
531 pred_end(SI->getParent())) <= 128)
532 CV = SI->getCondition();
533 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000534 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000535 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000536 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000537 CV = ICI->getOperand(0);
538
539 // Unwrap any lossless ptrtoint cast.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000540 if (DL && CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000541 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
542 Value *Ptr = PTII->getPointerOperand();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000543 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000544 CV = Ptr;
545 }
546 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000547 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000548}
549
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000550/// GetValueEqualityComparisonCases - Given a value comparison instruction,
551/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000552BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000553GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000554 std::vector<ValueEqualityComparisonCase>
555 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000556 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000557 Cases.reserve(SI->getNumCases());
558 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
559 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
560 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000561 return SI->getDefaultDest();
562 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000563
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000564 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000565 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000566 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
567 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000568 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000569 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000570 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000571}
572
Eric Christopherb65acc62012-07-02 23:22:21 +0000573
574/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
575/// in the list that match the specified block.
576static void EliminateBlockCases(BasicBlock *BB,
577 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000578 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000579}
580
581/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
582/// well.
583static bool
584ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
585 std::vector<ValueEqualityComparisonCase > &C2) {
586 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
587
588 // Make V1 be smaller than V2.
589 if (V1->size() > V2->size())
590 std::swap(V1, V2);
591
592 if (V1->size() == 0) return false;
593 if (V1->size() == 1) {
594 // Just scan V2.
595 ConstantInt *TheVal = (*V1)[0].Value;
596 for (unsigned i = 0, e = V2->size(); i != e; ++i)
597 if (TheVal == (*V2)[i].Value)
598 return true;
599 }
600
601 // Otherwise, just sort both lists and compare element by element.
602 array_pod_sort(V1->begin(), V1->end());
603 array_pod_sort(V2->begin(), V2->end());
604 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
605 while (i1 != e1 && i2 != e2) {
606 if ((*V1)[i1].Value == (*V2)[i2].Value)
607 return true;
608 if ((*V1)[i1].Value < (*V2)[i2].Value)
609 ++i1;
610 else
611 ++i2;
612 }
613 return false;
614}
615
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000616/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
617/// terminator instruction and its block is known to only have a single
618/// predecessor block, check to see if that predecessor is also a value
619/// comparison with the same value, and if that comparison determines the
620/// outcome of this comparison. If so, simplify TI. This does a very limited
621/// form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000622bool SimplifyCFGOpt::
623SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000624 BasicBlock *Pred,
625 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000626 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
627 if (!PredVal) return false; // Not a value comparison in predecessor.
628
629 Value *ThisVal = isValueEqualityComparison(TI);
630 assert(ThisVal && "This isn't a value comparison!!");
631 if (ThisVal != PredVal) return false; // Different predicates.
632
Andrew Trick3051aa12012-08-29 21:46:38 +0000633 // TODO: Preserve branch weight metadata, similarly to how
634 // FoldValueComparisonIntoPredecessors preserves it.
635
Chris Lattner1cca9592005-02-24 06:17:52 +0000636 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000637 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000638 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
639 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000640 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000641
Chris Lattner1cca9592005-02-24 06:17:52 +0000642 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000643 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000644 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000645 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000646
647 // If TI's block is the default block from Pred's comparison, potentially
648 // simplify TI based on this knowledge.
649 if (PredDef == TI->getParent()) {
650 // If we are here, we know that the value is none of those cases listed in
651 // PredCases. If there are any cases in ThisCases that are in PredCases, we
652 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000653 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000654 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000655
Chris Lattner4088e2b2010-12-13 01:47:07 +0000656 if (isa<BranchInst>(TI)) {
657 // Okay, one of the successors of this condbr is dead. Convert it to a
658 // uncond br.
659 assert(ThisCases.size() == 1 && "Branch can only have one case!");
660 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000661 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000662 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000663
Chris Lattner4088e2b2010-12-13 01:47:07 +0000664 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000665 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000666
Chris Lattner4088e2b2010-12-13 01:47:07 +0000667 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
668 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000669
Chris Lattner4088e2b2010-12-13 01:47:07 +0000670 EraseTerminatorInstAndDCECond(TI);
671 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000672 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000673
Chris Lattner4088e2b2010-12-13 01:47:07 +0000674 SwitchInst *SI = cast<SwitchInst>(TI);
675 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000676 SmallPtrSet<Constant*, 16> DeadCases;
677 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
678 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000679
David Greene725c7c32010-01-05 01:26:52 +0000680 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000681 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000682
Manman Ren8691e522012-09-14 21:53:06 +0000683 // Collect branch weights into a vector.
684 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000685 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000686 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
687 if (HasWeight)
688 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
689 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000690 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000691 Weights.push_back(CI->getValue().getZExtValue());
692 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000693 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
694 --i;
695 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000696 if (HasWeight) {
697 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
698 Weights.pop_back();
699 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000700 i.getCaseSuccessor()->removePredecessor(TI->getParent());
701 SI->removeCase(i);
702 }
703 }
Manman Ren97c18762012-10-11 22:28:34 +0000704 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000705 SI->setMetadata(LLVMContext::MD_prof,
706 MDBuilder(SI->getParent()->getContext()).
707 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000708
709 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000710 return true;
711 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000712
Chris Lattner4088e2b2010-12-13 01:47:07 +0000713 // Otherwise, TI's block must correspond to some matched value. Find out
714 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000715 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000716 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000717 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
718 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000719 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000720 return false; // Cannot handle multiple values coming to this block.
721 TIV = PredCases[i].Value;
722 }
723 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000724
725 // Okay, we found the one constant that our value can be if we get into TI's
726 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000727 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000728 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
729 if (ThisCases[i].Value == TIV) {
730 TheRealDest = ThisCases[i].Dest;
731 break;
732 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000733
734 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000735 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000736
737 // Remove PHI node entries for dead edges.
738 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000739 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
740 if (*SI != CheckEdge)
741 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000742 else
Craig Topperf40110f2014-04-25 05:29:35 +0000743 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000744
745 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000746 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000747 (void) NI;
748
749 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
750 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
751
752 EraseTerminatorInstAndDCECond(TI);
753 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000754}
755
Dale Johannesen7f99d222009-03-12 21:01:11 +0000756namespace {
757 /// ConstantIntOrdering - This class implements a stable ordering of constant
758 /// integers that does not depend on their address. This is important for
759 /// applications that sort ConstantInt's to ensure uniqueness.
760 struct ConstantIntOrdering {
761 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
762 return LHS->getValue().ult(RHS->getValue());
763 }
764 };
765}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000766
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000767static int ConstantIntSortPredicate(ConstantInt *const *P1,
768 ConstantInt *const *P2) {
769 const ConstantInt *LHS = *P1;
770 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000771 if (LHS->getValue().ult(RHS->getValue()))
772 return 1;
773 if (LHS->getValue() == RHS->getValue())
774 return 0;
775 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000776}
777
Andrew Trick3051aa12012-08-29 21:46:38 +0000778static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000779 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000780 if (ProfMD && ProfMD->getOperand(0))
781 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
782 return MDS->getString().equals("branch_weights");
783
784 return false;
785}
786
Manman Ren571d9e42012-09-11 17:43:35 +0000787/// Get Weights of a given TerminatorInst, the default weight is at the front
788/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
789/// metadata.
790static void GetBranchWeights(TerminatorInst *TI,
791 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000792 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000793 assert(MD);
794 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000795 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000796 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000797 }
798
Manman Ren571d9e42012-09-11 17:43:35 +0000799 // If TI is a conditional eq, the default case is the false case,
800 // and the corresponding branch-weight data is at index 2. We swap the
801 // default weight to be the first entry.
802 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
803 assert(Weights.size() == 2);
804 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
805 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
806 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000807 }
808}
809
Manman Renf1cb16e2014-01-27 23:39:03 +0000810/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000811static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000812 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
813 if (Max > UINT_MAX) {
814 unsigned Offset = 32 - countLeadingZeros(Max);
815 for (uint64_t &I : Weights)
816 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000817 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000818}
819
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000820/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
821/// equality comparison instruction (either a switch or a branch on "X == c").
822/// See if any of the predecessors of the terminator block are value comparisons
823/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000824bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
825 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000826 BasicBlock *BB = TI->getParent();
827 Value *CV = isValueEqualityComparison(TI); // CondVal
828 assert(CV && "Not a comparison?");
829 bool Changed = false;
830
Chris Lattner6b39cb92008-02-18 07:42:56 +0000831 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000832 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000833 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000834
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000835 // See if the predecessor is a comparison with the same value.
836 TerminatorInst *PTI = Pred->getTerminator();
837 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
838
839 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
840 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000841 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000842 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
843
Eric Christopherb65acc62012-07-02 23:22:21 +0000844 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000845 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
846
847 // Based on whether the default edge from PTI goes to BB or not, fill in
848 // PredCases and PredDefault with the new switch cases we would like to
849 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000850 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000851
Andrew Trick3051aa12012-08-29 21:46:38 +0000852 // Update the branch weight metadata along the way
853 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000854 bool PredHasWeights = HasBranchWeights(PTI);
855 bool SuccHasWeights = HasBranchWeights(TI);
856
Manman Ren5e5049d2012-09-14 19:05:19 +0000857 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000858 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000859 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000860 if (Weights.size() != 1 + PredCases.size())
861 PredHasWeights = SuccHasWeights = false;
862 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000863 // If there are no predecessor weights but there are successor weights,
864 // populate Weights with 1, which will later be scaled to the sum of
865 // successor's weights
866 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000867
Manman Ren571d9e42012-09-11 17:43:35 +0000868 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000869 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000870 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000871 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000872 if (SuccWeights.size() != 1 + BBCases.size())
873 PredHasWeights = SuccHasWeights = false;
874 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000875 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000876
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000877 if (PredDefault == BB) {
878 // If this is the default destination from PTI, only the edges in TI
879 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000880 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
881 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
882 if (PredCases[i].Dest != BB)
883 PTIHandled.insert(PredCases[i].Value);
884 else {
885 // The default destination is BB, we don't need explicit targets.
886 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000887
Manman Ren571d9e42012-09-11 17:43:35 +0000888 if (PredHasWeights || SuccHasWeights) {
889 // Increase weight for the default case.
890 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000891 std::swap(Weights[i+1], Weights.back());
892 Weights.pop_back();
893 }
894
Eric Christopherb65acc62012-07-02 23:22:21 +0000895 PredCases.pop_back();
896 --i; --e;
897 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000898
Eric Christopherb65acc62012-07-02 23:22:21 +0000899 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000900 if (PredDefault != BBDefault) {
901 PredDefault->removePredecessor(Pred);
902 PredDefault = BBDefault;
903 NewSuccessors.push_back(BBDefault);
904 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000905
Manman Ren571d9e42012-09-11 17:43:35 +0000906 unsigned CasesFromPred = Weights.size();
907 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000908 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
909 if (!PTIHandled.count(BBCases[i].Value) &&
910 BBCases[i].Dest != BBDefault) {
911 PredCases.push_back(BBCases[i]);
912 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000913 if (SuccHasWeights || PredHasWeights) {
914 // The default weight is at index 0, so weight for the ith case
915 // should be at index i+1. Scale the cases from successor by
916 // PredDefaultWeight (Weights[0]).
917 Weights.push_back(Weights[0] * SuccWeights[i+1]);
918 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000919 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000920 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000921
Manman Ren571d9e42012-09-11 17:43:35 +0000922 if (SuccHasWeights || PredHasWeights) {
923 ValidTotalSuccWeight += SuccWeights[0];
924 // Scale the cases from predecessor by ValidTotalSuccWeight.
925 for (unsigned i = 1; i < CasesFromPred; ++i)
926 Weights[i] *= ValidTotalSuccWeight;
927 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
928 Weights[0] *= SuccWeights[0];
929 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000930 } else {
931 // If this is not the default destination from PSI, only the edges
932 // in SI that occur in PSI with a destination of BB will be
933 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000934 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000935 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000936 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
937 if (PredCases[i].Dest == BB) {
938 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000939
940 if (PredHasWeights || SuccHasWeights) {
941 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
942 std::swap(Weights[i+1], Weights.back());
943 Weights.pop_back();
944 }
945
Eric Christopherb65acc62012-07-02 23:22:21 +0000946 std::swap(PredCases[i], PredCases.back());
947 PredCases.pop_back();
948 --i; --e;
949 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000950
951 // Okay, now we know which constants were sent to BB from the
952 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000953 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
954 if (PTIHandled.count(BBCases[i].Value)) {
955 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000956 if (PredHasWeights || SuccHasWeights)
957 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000958 PredCases.push_back(BBCases[i]);
959 NewSuccessors.push_back(BBCases[i].Dest);
960 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
961 }
962
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000963 // If there are any constants vectored to BB that TI doesn't handle,
964 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000965 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000966 PTIHandled.begin(),
967 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000968 if (PredHasWeights || SuccHasWeights)
969 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000970 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000971 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000972 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000973 }
974
975 // Okay, at this point, we know which new successor Pred will get. Make
976 // sure we update the number of entries in the PHI nodes for these
977 // successors.
978 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
979 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
980
Devang Patel58380552011-05-18 20:53:17 +0000981 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000982 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000983 if (CV->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000984 assert(DL && "Cannot switch on pointer without DataLayout");
985 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000986 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000987 }
988
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000989 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000990 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
991 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000992 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +0000993 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
994 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000995
Andrew Trick3051aa12012-08-29 21:46:38 +0000996 if (PredHasWeights || SuccHasWeights) {
997 // Halve the weights if any of them cannot fit in an uint32_t
998 FitWeights(Weights);
999
1000 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1001
1002 NewSI->setMetadata(LLVMContext::MD_prof,
1003 MDBuilder(BB->getContext()).
1004 createBranchWeights(MDWeights));
1005 }
1006
Eli Friedmancb61afb2008-12-16 20:54:32 +00001007 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001008
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001009 // Okay, last check. If BB is still a successor of PSI, then we must
1010 // have an infinite loop case. If so, add an infinitely looping block
1011 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001012 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001013 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1014 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001015 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001016 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001017 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001018 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1019 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001020 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001021 }
1022 NewSI->setSuccessor(i, InfLoopBlock);
1023 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001024
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001025 Changed = true;
1026 }
1027 }
1028 return Changed;
1029}
1030
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001031// isSafeToHoistInvoke - If we would need to insert a select that uses the
1032// value of this invoke (comments in HoistThenElseCodeToIf explain why we
1033// would need to do this), we can't hoist the invoke, as there is nowhere
1034// to put the select in this case.
1035static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1036 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001037 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001038 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001039 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001040 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1041 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1042 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1043 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1044 return false;
1045 }
1046 }
1047 }
1048 return true;
1049}
1050
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001051static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1052
Chris Lattnerd683bdd2005-08-03 17:59:45 +00001053/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +00001054/// BB2, hoist any common code in the two blocks up into the branch block. The
1055/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Chad Rosier54390052015-02-23 19:15:16 +00001056static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL,
1057 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001058 // This does very trivial matching, with limited scanning, to find identical
1059 // instructions in the two blocks. In particular, we don't want to get into
1060 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1061 // such, we currently just scan for obviously identical instructions in an
1062 // identical order.
1063 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1064 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1065
Devang Patelf10e2872009-02-04 00:03:08 +00001066 BasicBlock::iterator BB1_Itr = BB1->begin();
1067 BasicBlock::iterator BB2_Itr = BB2->begin();
1068
1069 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001070 // Skip debug info if it is not identical.
1071 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1072 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1073 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1074 while (isa<DbgInfoIntrinsic>(I1))
1075 I1 = BB1_Itr++;
1076 while (isa<DbgInfoIntrinsic>(I2))
1077 I2 = BB2_Itr++;
1078 }
Devang Patele48ddf82011-04-07 00:30:15 +00001079 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001080 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001081 return false;
1082
Chris Lattner389cfac2004-11-30 00:29:14 +00001083 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001084
David Majnemerc82f27a2013-06-03 20:43:12 +00001085 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001086 do {
1087 // If we are hoisting the terminator instruction, don't move one (making a
1088 // broken BB), instead clone it, and remove BI.
1089 if (isa<TerminatorInst>(I1))
1090 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001091
Chad Rosier54390052015-02-23 19:15:16 +00001092 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1093 return Changed;
1094
Chris Lattner389cfac2004-11-30 00:29:14 +00001095 // For a normal instruction, we just move one to right before the branch,
1096 // then replace all uses of the other with the first. Finally, we remove
1097 // the now redundant second instruction.
1098 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1099 if (!I2->use_empty())
1100 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001101 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001102 unsigned KnownIDs[] = {
1103 LLVMContext::MD_tbaa,
1104 LLVMContext::MD_range,
1105 LLVMContext::MD_fpmath,
Philip Reamesd92c2a72014-10-22 16:37:13 +00001106 LLVMContext::MD_invariant_load,
1107 LLVMContext::MD_nonnull
Rafael Espindolaea46c322014-08-15 15:46:38 +00001108 };
1109 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001110 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001111 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001112
Devang Patelf10e2872009-02-04 00:03:08 +00001113 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001114 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001115 // Skip debug info if it is not identical.
1116 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1117 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1118 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1119 while (isa<DbgInfoIntrinsic>(I1))
1120 I1 = BB1_Itr++;
1121 while (isa<DbgInfoIntrinsic>(I2))
1122 I2 = BB2_Itr++;
1123 }
Devang Patele48ddf82011-04-07 00:30:15 +00001124 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001125
1126 return true;
1127
1128HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001129 // It may not be possible to hoist an invoke.
1130 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001131 return Changed;
1132
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001133 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001134 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001135 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001136 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1137 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1138 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1139 if (BB1V == BB2V)
1140 continue;
1141
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001142 // Check for passingValueIsAlwaysUndefined here because we would rather
1143 // eliminate undefined control flow then converting it to a select.
1144 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1145 passingValueIsAlwaysUndefined(BB2V, PN))
1146 return Changed;
1147
Hal Finkela995f922014-07-10 14:41:31 +00001148 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001149 return Changed;
Hal Finkela995f922014-07-10 14:41:31 +00001150 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001151 return Changed;
1152 }
1153 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001154
Chris Lattner389cfac2004-11-30 00:29:14 +00001155 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001156 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001157 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001158 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001159 I1->replaceAllUsesWith(NT);
1160 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001161 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001162 }
1163
Devang Patel1407fb42011-05-19 20:52:46 +00001164 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001165 // Hoisting one of the terminators from our successor is a great thing.
1166 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1167 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1168 // nodes, so we insert select instruction to compute the final result.
1169 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001170 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001171 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001172 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001173 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001174 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1175 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001176 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001177
Chris Lattner4088e2b2010-12-13 01:47:07 +00001178 // These values do not agree. Insert a select instruction before NT
1179 // that determines the right value.
1180 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001181 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001182 SI = cast<SelectInst>
1183 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1184 BB1V->getName()+"."+BB2V->getName()));
1185
Chris Lattner4088e2b2010-12-13 01:47:07 +00001186 // Make the PHI node use the select for all incoming values for BB1/BB2
1187 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1188 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1189 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001190 }
1191 }
1192
1193 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001194 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1195 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001196
Eli Friedmancb61afb2008-12-16 20:54:32 +00001197 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001198 return true;
1199}
1200
Manman Ren93ab6492012-09-20 22:37:36 +00001201/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1202/// check whether BBEnd has only two predecessors and the other predecessor
1203/// ends with an unconditional branch. If it is true, sink any common code
1204/// in the two predecessors to BBEnd.
1205static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1206 assert(BI1->isUnconditional());
1207 BasicBlock *BB1 = BI1->getParent();
1208 BasicBlock *BBEnd = BI1->getSuccessor(0);
1209
1210 // Check that BBEnd has two predecessors and the other predecessor ends with
1211 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001212 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1213 BasicBlock *Pred0 = *PI++;
1214 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001215 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001216 BasicBlock *Pred1 = *PI++;
1217 if (PI != PE) // More than two predecessors.
1218 return false;
1219 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001220 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1221 if (!BI2 || !BI2->isUnconditional())
1222 return false;
1223
1224 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001225 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001226 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001227 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001228 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1229 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001230 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001231 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001232 } else {
1233 FirstNonPhiInBBEnd = &*I;
1234 break;
1235 }
1236 }
1237 if (!FirstNonPhiInBBEnd)
1238 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001239
Manman Ren93ab6492012-09-20 22:37:36 +00001240 // This does very trivial matching, with limited scanning, to find identical
1241 // instructions in the two blocks. We scan backward for obviously identical
1242 // instructions in an identical order.
1243 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001244 RE1 = BB1->getInstList().rend(),
1245 RI2 = BB2->getInstList().rbegin(),
1246 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001247 // Skip debug info.
1248 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1249 if (RI1 == RE1)
1250 return false;
1251 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1252 if (RI2 == RE2)
1253 return false;
1254 // Skip the unconditional branches.
1255 ++RI1;
1256 ++RI2;
1257
1258 bool Changed = false;
1259 while (RI1 != RE1 && RI2 != RE2) {
1260 // Skip debug info.
1261 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1262 if (RI1 == RE1)
1263 return Changed;
1264 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1265 if (RI2 == RE2)
1266 return Changed;
1267
1268 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001269 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001270 // I1 and I2 should have a single use in the same PHI node, and they
1271 // perform the same operation.
1272 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1273 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1274 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1275 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1276 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1277 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1278 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1279 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001280 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001281 return Changed;
1282
1283 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001284 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001285 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1286 bool SwapOpnds = false;
1287 if (ICmp1 && ICmp2 &&
1288 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1289 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1290 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1291 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1292 ICmp2->swapOperands();
1293 SwapOpnds = true;
1294 }
1295 if (!I1->isSameOperationAs(I2)) {
1296 if (SwapOpnds)
1297 ICmp2->swapOperands();
1298 return Changed;
1299 }
1300
1301 // The operands should be either the same or they need to be generated
1302 // with a PHI node after sinking. We only handle the case where there is
1303 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001304 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001305 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001306 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1307 if (I1->getOperand(I) == I2->getOperand(I))
1308 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001309 // Early exit if we have more-than one pair of different operands or if
1310 // we need a PHI node to replace a constant.
1311 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001312 isa<Constant>(I1->getOperand(I)) ||
1313 isa<Constant>(I2->getOperand(I))) {
1314 // If we can't sink the instructions, undo the swapping.
1315 if (SwapOpnds)
1316 ICmp2->swapOperands();
1317 return Changed;
1318 }
1319 DifferentOp1 = I1->getOperand(I);
1320 Op1Idx = I;
1321 DifferentOp2 = I2->getOperand(I);
1322 }
1323
Michael Liao5313da32014-12-23 08:26:55 +00001324 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1325 DEBUG(dbgs() << " " << *I2 << "\n");
1326
1327 // We insert the pair of different operands to JointValueMap and
1328 // remove (I1, I2) from JointValueMap.
1329 if (Op1Idx != ~0U) {
1330 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1331 if (!NewPN) {
1332 NewPN =
1333 PHINode::Create(DifferentOp1->getType(), 2,
1334 DifferentOp1->getName() + ".sink", BBEnd->begin());
1335 NewPN->addIncoming(DifferentOp1, BB1);
1336 NewPN->addIncoming(DifferentOp2, BB2);
1337 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1338 }
Manman Ren93ab6492012-09-20 22:37:36 +00001339 // I1 should use NewPN instead of DifferentOp1.
1340 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001341 }
Michael Liao5313da32014-12-23 08:26:55 +00001342 PHINode *OldPN = JointValueMap[InstPair];
1343 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001344
Manman Ren93ab6492012-09-20 22:37:36 +00001345 // We need to update RE1 and RE2 if we are going to sink the first
1346 // instruction in the basic block down.
1347 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1348 // Sink the instruction.
1349 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1350 if (!OldPN->use_empty())
1351 OldPN->replaceAllUsesWith(I1);
1352 OldPN->eraseFromParent();
1353
1354 if (!I2->use_empty())
1355 I2->replaceAllUsesWith(I1);
1356 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001357 // TODO: Use combineMetadata here to preserve what metadata we can
1358 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001359 I2->eraseFromParent();
1360
1361 if (UpdateRE1)
1362 RE1 = BB1->getInstList().rend();
1363 if (UpdateRE2)
1364 RE2 = BB2->getInstList().rend();
1365 FirstNonPhiInBBEnd = I1;
1366 NumSinkCommons++;
1367 Changed = true;
1368 }
1369 return Changed;
1370}
1371
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001372/// \brief Determine if we can hoist sink a sole store instruction out of a
1373/// conditional block.
1374///
1375/// We are looking for code like the following:
1376/// BrBB:
1377/// store i32 %add, i32* %arrayidx2
1378/// ... // No other stores or function calls (we could be calling a memory
1379/// ... // function).
1380/// %cmp = icmp ult %x, %y
1381/// br i1 %cmp, label %EndBB, label %ThenBB
1382/// ThenBB:
1383/// store i32 %add5, i32* %arrayidx2
1384/// br label EndBB
1385/// EndBB:
1386/// ...
1387/// We are going to transform this into:
1388/// BrBB:
1389/// store i32 %add, i32* %arrayidx2
1390/// ... //
1391/// %cmp = icmp ult %x, %y
1392/// %add.add5 = select i1 %cmp, i32 %add, %add5
1393/// store i32 %add.add5, i32* %arrayidx2
1394/// ...
1395///
1396/// \return The pointer to the value of the previous store if the store can be
1397/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001398static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1399 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001400 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1401 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001402 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001403
1404 // Volatile or atomic.
1405 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001406 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001407
1408 Value *StorePtr = StoreToHoist->getPointerOperand();
1409
1410 // Look for a store to the same pointer in BrBB.
1411 unsigned MaxNumInstToLookAt = 10;
1412 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1413 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1414 Instruction *CurI = &*RI;
1415
1416 // Could be calling an instruction that effects memory like free().
1417 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001418 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001419
1420 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1421 // Found the previous store make sure it stores to the same location.
1422 if (SI && SI->getPointerOperand() == StorePtr)
1423 // Found the previous store, return its value operand.
1424 return SI->getValueOperand();
1425 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001426 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001427 }
1428
Craig Topperf40110f2014-04-25 05:29:35 +00001429 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001430}
1431
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001432/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001433///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001434/// Note that this is a very risky transform currently. Speculating
1435/// instructions like this is most often not desirable. Instead, there is an MI
1436/// pass which can do it with full awareness of the resource constraints.
1437/// However, some cases are "obvious" and we should do directly. An example of
1438/// this is speculating a single, reasonably cheap instruction.
1439///
1440/// There is only one distinct advantage to flattening the CFG at the IR level:
1441/// it makes very common but simplistic optimizations such as are common in
1442/// instcombine and the DAG combiner more powerful by removing CFG edges and
1443/// modeling their effects with easier to reason about SSA value graphs.
1444///
1445///
1446/// An illustration of this transform is turning this IR:
1447/// \code
1448/// BB:
1449/// %cmp = icmp ult %x, %y
1450/// br i1 %cmp, label %EndBB, label %ThenBB
1451/// ThenBB:
1452/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001453/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001454/// EndBB:
1455/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1456/// ...
1457/// \endcode
1458///
1459/// Into this IR:
1460/// \code
1461/// BB:
1462/// %cmp = icmp ult %x, %y
1463/// %sub = sub %x, %y
1464/// %cond = select i1 %cmp, 0, %sub
1465/// ...
1466/// \endcode
1467///
1468/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001469static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001470 const DataLayout *DL,
1471 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001472 // Be conservative for now. FP select instruction can often be expensive.
1473 Value *BrCond = BI->getCondition();
1474 if (isa<FCmpInst>(BrCond))
1475 return false;
1476
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001477 BasicBlock *BB = BI->getParent();
1478 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1479
1480 // If ThenBB is actually on the false edge of the conditional branch, remember
1481 // to swap the select operands later.
1482 bool Invert = false;
1483 if (ThenBB != BI->getSuccessor(0)) {
1484 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1485 Invert = true;
1486 }
1487 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1488
Chandler Carruthceff2222013-01-25 05:40:09 +00001489 // Keep a count of how many times instructions are used within CondBB when
1490 // they are candidates for sinking into CondBB. Specifically:
1491 // - They are defined in BB, and
1492 // - They have no side effects, and
1493 // - All of their uses are in CondBB.
1494 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1495
Chandler Carruth7481ca82013-01-24 11:52:58 +00001496 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001497 Value *SpeculatedStoreValue = nullptr;
1498 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001499 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001500 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001501 BBI != BBE; ++BBI) {
1502 Instruction *I = BBI;
1503 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001504 if (isa<DbgInfoIntrinsic>(I))
1505 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001506
Chandler Carruth7481ca82013-01-24 11:52:58 +00001507 // Only speculatively execution a single instruction (not counting the
1508 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001509 ++SpeculationCost;
1510 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001511 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001512
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001513 // Don't hoist the instruction if it's unsafe or expensive.
Hal Finkela995f922014-07-10 14:41:31 +00001514 if (!isSafeToSpeculativelyExecute(I, DL) &&
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001515 !(HoistCondStores &&
1516 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1517 EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001518 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001519 if (!SpeculatedStoreValue &&
James Molloy7c336572015-02-11 12:15:41 +00001520 ComputeSpeculationCost(I, DL, TTI) > PHINodeFoldingThreshold *
1521 TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001522 return false;
1523
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001524 // Store the store speculation candidate.
1525 if (SpeculatedStoreValue)
1526 SpeculatedStore = cast<StoreInst>(I);
1527
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001528 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001529 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001530 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001531 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001532 i != e; ++i) {
1533 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001534 if (!OpI || OpI->getParent() != BB ||
1535 OpI->mayHaveSideEffects())
1536 continue; // Not a candidate for sinking.
1537
1538 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001539 }
1540 }
Evan Cheng89200c92008-06-07 08:52:29 +00001541
Chandler Carruthceff2222013-01-25 05:40:09 +00001542 // Consider any sink candidates which are only used in CondBB as costs for
1543 // speculation. Note, while we iterate over a DenseMap here, we are summing
1544 // and so iteration order isn't significant.
1545 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1546 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1547 I != E; ++I)
1548 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001549 ++SpeculationCost;
1550 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001551 return false;
1552 }
1553
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001554 // Check that the PHI nodes can be converted to selects.
1555 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001556 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001557 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001558 Value *OrigV = PN->getIncomingValueForBlock(BB);
1559 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001560
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001561 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001562 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001563 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001564 continue;
1565
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001566 // Don't convert to selects if we could remove undefined behavior instead.
1567 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1568 passingValueIsAlwaysUndefined(ThenV, PN))
1569 return false;
1570
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001571 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001572 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1573 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1574 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001575 continue; // Known safe and cheap.
1576
Hal Finkela995f922014-07-10 14:41:31 +00001577 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1578 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001579 return false;
James Molloy7c336572015-02-11 12:15:41 +00001580 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL, TTI) : 0;
1581 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL, TTI) : 0;
1582 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1583 TargetTransformInfo::TCC_Basic;
1584 if (OrigCost + ThenCost > MaxCost)
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.
James Molloy7c336572015-02-11 12:15:41 +00001789static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL,
1790 const TargetTransformInfo &TTI) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001791 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1792 // statement", which has a very simple dominance structure. Basically, we
1793 // are trying to find the condition that is being branched on, which
1794 // subsequently causes this merge to happen. We really want control
1795 // dependence information for this check, but simplifycfg can't keep it up
1796 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001797 BasicBlock *BB = PN->getParent();
1798 BasicBlock *IfTrue, *IfFalse;
1799 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001800 if (!IfCond ||
1801 // Don't bother if the branch will be constant folded trivially.
1802 isa<ConstantInt>(IfCond))
1803 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001804
Chris Lattner95adf8f12006-11-18 19:19:36 +00001805 // Okay, we found that we can merge this two-entry phi node into a select.
1806 // Doing so would require us to fold *all* two entry phi nodes in this block.
1807 // At some point this becomes non-profitable (particularly if the target
1808 // doesn't support cmov's). Only do this transformation if there are two or
1809 // fewer PHI nodes in this block.
1810 unsigned NumPhis = 0;
1811 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1812 if (NumPhis > 2)
1813 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001814
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001815 // Loop over the PHI's seeing if we can promote them all to select
1816 // instructions. While we are at it, keep track of the instructions
1817 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001818 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001819 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1820 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001821 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1822 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001823
Chris Lattner7499b452010-12-14 08:46:09 +00001824 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1825 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001826 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001827 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001828 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001829 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001830 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001831
Peter Collingbournee3511e12011-04-29 18:47:31 +00001832 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
James Molloy7c336572015-02-11 12:15:41 +00001833 MaxCostVal0, DL, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001834 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
James Molloy7c336572015-02-11 12:15:41 +00001835 MaxCostVal1, DL, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001836 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001837 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001838
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001839 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001840 // we ran out of PHIs then we simplified them all.
1841 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001842 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001843
Chris Lattner7499b452010-12-14 08:46:09 +00001844 // Don't fold i1 branches on PHIs which contain binary operators. These can
1845 // often be turned into switches and other things.
1846 if (PN->getType()->isIntegerTy(1) &&
1847 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1848 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1849 isa<BinaryOperator>(IfCond)))
1850 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001851
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001852 // If we all PHI nodes are promotable, check to make sure that all
1853 // instructions in the predecessor blocks can be promoted as well. If
1854 // not, we won't be able to get rid of the control flow, so it's not
1855 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001856 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001857 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1858 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1859 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001860 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001861 } else {
1862 DomBlock = *pred_begin(IfBlock1);
1863 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001864 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001865 // This is not an aggressive instruction that we can promote.
1866 // Because of this, we won't be able to get rid of the control
1867 // flow, so the xform is not worth it.
1868 return false;
1869 }
1870 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001871
Chris Lattner9ac168d2010-12-14 07:41:39 +00001872 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001873 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001874 } else {
1875 DomBlock = *pred_begin(IfBlock2);
1876 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001877 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001878 // This is not an aggressive instruction that we can promote.
1879 // Because of this, we won't be able to get rid of the control
1880 // flow, so the xform is not worth it.
1881 return false;
1882 }
1883 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001884
Chris Lattner9fd838d2010-12-14 07:23:10 +00001885 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001886 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001887
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001888 // If we can still promote the PHI nodes after this gauntlet of tests,
1889 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001890 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001891 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001892
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001893 // Move all 'aggressive' instructions, which are defined in the
1894 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001895 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001896 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001897 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001898 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001899 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001900 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001901 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001902 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001903
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001904 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1905 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001906 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1907 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001908
1909 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001910 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001911 PN->replaceAllUsesWith(NV);
1912 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001913 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001914 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001915
Chris Lattner335f0e42010-12-14 08:01:53 +00001916 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1917 // has been flattened. Change DomBlock to jump directly to our new block to
1918 // avoid other simplifycfg's kicking in on the diamond.
1919 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001920 Builder.SetInsertPoint(OldTI);
1921 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001922 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001923 return true;
1924}
Chris Lattner748f9032005-09-19 23:49:37 +00001925
Chris Lattner86bbf332008-04-24 00:01:19 +00001926/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1927/// to two returning blocks, try to merge them together into one return,
1928/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001929static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001930 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001931 assert(BI->isConditional() && "Must be a conditional branch");
1932 BasicBlock *TrueSucc = BI->getSuccessor(0);
1933 BasicBlock *FalseSucc = BI->getSuccessor(1);
1934 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1935 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001936
Chris Lattner86bbf332008-04-24 00:01:19 +00001937 // Check to ensure both blocks are empty (just a return) or optionally empty
1938 // with PHI nodes. If there are other instructions, merging would cause extra
1939 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001940 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001941 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001942 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001943 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001944
Devang Pateldd14e0f2011-05-18 21:33:11 +00001945 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001946 // Okay, we found a branch that is going to two return nodes. If
1947 // there is no return value for this function, just change the
1948 // branch into a return.
1949 if (FalseRet->getNumOperands() == 0) {
1950 TrueSucc->removePredecessor(BI->getParent());
1951 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001952 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001953 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001954 return true;
1955 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001956
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001957 // Otherwise, figure out what the true and false return values are
1958 // so we can insert a new select instruction.
1959 Value *TrueValue = TrueRet->getReturnValue();
1960 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001961
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001962 // Unwrap any PHI nodes in the return blocks.
1963 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1964 if (TVPN->getParent() == TrueSucc)
1965 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1966 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1967 if (FVPN->getParent() == FalseSucc)
1968 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001969
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001970 // In order for this transformation to be safe, we must be able to
1971 // unconditionally execute both operands to the return. This is
1972 // normally the case, but we could have a potentially-trapping
1973 // constant expression that prevents this transformation from being
1974 // safe.
1975 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1976 if (TCV->canTrap())
1977 return false;
1978 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1979 if (FCV->canTrap())
1980 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001981
Chris Lattner86bbf332008-04-24 00:01:19 +00001982 // Okay, we collected all the mapped values and checked them for sanity, and
1983 // defined to really do this transformation. First, update the CFG.
1984 TrueSucc->removePredecessor(BI->getParent());
1985 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001986
Chris Lattner86bbf332008-04-24 00:01:19 +00001987 // Insert select instructions where needed.
1988 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001989 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001990 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001991 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1992 } else if (isa<UndefValue>(TrueValue)) {
1993 TrueValue = FalseValue;
1994 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001995 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1996 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001997 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001998 }
1999
Andrew Trickf3cf1932012-08-29 21:46:36 +00002000 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002001 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2002
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002003 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002004
David Greene725c7c32010-01-05 01:26:52 +00002005 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002006 << "\n " << *BI << "NewRet = " << *RI
2007 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002008
Eli Friedmancb61afb2008-12-16 20:54:32 +00002009 EraseTerminatorInstAndDCECond(BI);
2010
Chris Lattner86bbf332008-04-24 00:01:19 +00002011 return true;
2012}
2013
Juergen Ributzka194350a2014-12-09 17:32:12 +00002014/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2015/// probabilities of the branch taking each edge. Fills in the two APInt
2016/// parameters and return true, or returns false if no or invalid metadata was
2017/// found.
2018static bool ExtractBranchMetadata(BranchInst *BI,
2019 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2020 assert(BI->isConditional() &&
2021 "Looking for probabilities on unconditional branch?");
2022 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2023 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002024 ConstantInt *CITrue =
2025 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2026 ConstantInt *CIFalse =
2027 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002028 if (!CITrue || !CIFalse) return false;
2029 ProbTrue = CITrue->getValue().getZExtValue();
2030 ProbFalse = CIFalse->getValue().getZExtValue();
2031 return true;
2032}
2033
Manman Rend33f4ef2012-06-13 05:43:29 +00002034/// checkCSEInPredecessor - Return true if the given instruction is available
2035/// in its predecessor block. If yes, the instruction will be removed.
2036///
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002037static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002038 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2039 return false;
2040 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2041 Instruction *PBI = &*I;
2042 // Check whether Inst and PBI generate the same value.
2043 if (Inst->isIdenticalTo(PBI)) {
2044 Inst->replaceAllUsesWith(PBI);
2045 Inst->eraseFromParent();
2046 return true;
2047 }
2048 }
2049 return false;
2050}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002051
Chris Lattner7d4cdae2011-04-11 23:24:57 +00002052/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2053/// predecessor branches to us and one of our successors, fold the block into
2054/// the predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00002055bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2056 unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002057 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002058
Craig Topperf40110f2014-04-25 05:29:35 +00002059 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002060 if (BI->isConditional())
2061 Cond = dyn_cast<Instruction>(BI->getCondition());
2062 else {
2063 // For unconditional branch, check for a simple CFG pattern, where
2064 // BB has a single predecessor and BB's successor is also its predecessor's
2065 // successor. If such pattern exisits, check for CSE between BB and its
2066 // predecessor.
2067 if (BasicBlock *PB = BB->getSinglePredecessor())
2068 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2069 if (PBI->isConditional() &&
2070 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2071 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2072 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2073 I != E; ) {
2074 Instruction *Curr = I++;
2075 if (isa<CmpInst>(Curr)) {
2076 Cond = Curr;
2077 break;
2078 }
2079 // Quit if we can't remove this instruction.
2080 if (!checkCSEInPredecessor(Curr, PB))
2081 return false;
2082 }
2083 }
2084
Craig Topperf40110f2014-04-25 05:29:35 +00002085 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002086 return false;
2087 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002088
Craig Topperf40110f2014-04-25 05:29:35 +00002089 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2090 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002091 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002092
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002093 // Make sure the instruction after the condition is the cond branch.
2094 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002095
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002096 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002097 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002098
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002099 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002100 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002101
Jingyue Wufc029672014-09-30 22:23:38 +00002102 // Only allow this transformation if computing the condition doesn't involve
2103 // too many instructions and these involved instructions can be executed
2104 // unconditionally. We denote all involved instructions except the condition
2105 // as "bonus instructions", and only allow this transformation when the
2106 // number of the bonus instructions does not exceed a certain threshold.
2107 unsigned NumBonusInsts = 0;
2108 for (auto I = BB->begin(); Cond != I; ++I) {
2109 // Ignore dbg intrinsics.
2110 if (isa<DbgInfoIntrinsic>(I))
2111 continue;
2112 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2113 return false;
2114 // I has only one use and can be executed unconditionally.
2115 Instruction *User = dyn_cast<Instruction>(I->user_back());
2116 if (User == nullptr || User->getParent() != BB)
2117 return false;
2118 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2119 // to use any other instruction, User must be an instruction between next(I)
2120 // and Cond.
2121 ++NumBonusInsts;
2122 // Early exits once we reach the limit.
2123 if (NumBonusInsts > BonusInstThreshold)
2124 return false;
2125 }
2126
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002127 // Cond is known to be a compare or binary operator. Check to make sure that
2128 // neither operand is a potentially-trapping constant expression.
2129 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2130 if (CE->canTrap())
2131 return false;
2132 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2133 if (CE->canTrap())
2134 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002135
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002136 // Finally, don't infinitely unroll conditional loops.
2137 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002138 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002139 if (TrueDest == BB || FalseDest == BB)
2140 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002141
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002142 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2143 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002144 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002145
Chris Lattner80b03a12008-07-13 22:23:11 +00002146 // Check that we have two conditional branches. If there is a PHI node in
2147 // the common successor, verify that the same value flows in from both
2148 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002149 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002150 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002151 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002152 !SafeToMergeTerminators(BI, PBI)) ||
2153 (!BI->isConditional() &&
2154 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002155 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002156
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002157 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002158 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002159 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002160
Manman Rend33f4ef2012-06-13 05:43:29 +00002161 if (BI->isConditional()) {
2162 if (PBI->getSuccessor(0) == TrueDest)
2163 Opc = Instruction::Or;
2164 else if (PBI->getSuccessor(1) == FalseDest)
2165 Opc = Instruction::And;
2166 else if (PBI->getSuccessor(0) == FalseDest)
2167 Opc = Instruction::And, InvertPredCond = true;
2168 else if (PBI->getSuccessor(1) == TrueDest)
2169 Opc = Instruction::Or, InvertPredCond = true;
2170 else
2171 continue;
2172 } else {
2173 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2174 continue;
2175 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002176
David Greene725c7c32010-01-05 01:26:52 +00002177 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002179
Chris Lattner55eaae12008-07-13 21:20:19 +00002180 // If we need to invert the condition in the pred block to match, do so now.
2181 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002182 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002183
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002184 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2185 CmpInst *CI = cast<CmpInst>(NewCond);
2186 CI->setPredicate(CI->getInversePredicate());
2187 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002188 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002189 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002190 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002191
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002192 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002193 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002194 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002195
Jingyue Wufc029672014-09-30 22:23:38 +00002196 // If we have bonus instructions, clone them into the predecessor block.
2197 // Note that there may be mutliple predecessor blocks, so we cannot move
2198 // bonus instructions to a predecessor block.
2199 ValueToValueMapTy VMap; // maps original values to cloned values
2200 // We already make sure Cond is the last instruction before BI. Therefore,
2201 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2202 // instructions.
2203 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2204 if (isa<DbgInfoIntrinsic>(BonusInst))
2205 continue;
2206 Instruction *NewBonusInst = BonusInst->clone();
2207 RemapInstruction(NewBonusInst, VMap,
2208 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2209 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002210
2211 // If we moved a load, we cannot any longer claim any knowledge about
2212 // its potential value. The previous information might have been valid
2213 // only given the branch precondition.
2214 // For an analogous reason, we must also drop all the metadata whose
2215 // semantics we don't understand.
Jingyue Wufc029672014-09-30 22:23:38 +00002216 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
Rafael Espindolaab73c492014-01-28 16:56:46 +00002217
Jingyue Wufc029672014-09-30 22:23:38 +00002218 PredBlock->getInstList().insert(PBI, NewBonusInst);
2219 NewBonusInst->takeName(BonusInst);
2220 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002221 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002222
Chris Lattner55eaae12008-07-13 21:20:19 +00002223 // Clone Cond into the predecessor basic block, and or/and the
2224 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002225 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002226 RemapInstruction(New, VMap,
2227 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002228 PredBlock->getInstList().insert(PBI, New);
2229 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002230 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002231
Manman Rend33f4ef2012-06-13 05:43:29 +00002232 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002233 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002234 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002235 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002236 PBI->setCondition(NewCond);
2237
Manman Renbfb9d432012-09-15 00:39:57 +00002238 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002239 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2240 PredFalseWeight);
2241 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2242 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002243 SmallVector<uint64_t, 8> NewWeights;
2244
Manman Rend33f4ef2012-06-13 05:43:29 +00002245 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002246 if (PredHasWeights && SuccHasWeights) {
2247 // PBI: br i1 %x, BB, FalseDest
2248 // BI: br i1 %y, TrueDest, FalseDest
2249 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2250 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2251 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2252 // TrueWeight for PBI * FalseWeight for BI.
2253 // We assume that total weights of a BranchInst can fit into 32 bits.
2254 // Therefore, we will not have overflow using 64-bit arithmetic.
2255 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2256 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2257 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002258 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2259 PBI->setSuccessor(0, TrueDest);
2260 }
2261 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002262 if (PredHasWeights && SuccHasWeights) {
2263 // PBI: br i1 %x, TrueDest, BB
2264 // BI: br i1 %y, TrueDest, FalseDest
2265 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2266 // FalseWeight for PBI * TrueWeight for BI.
2267 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2268 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2269 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2270 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2271 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002272 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2273 PBI->setSuccessor(1, FalseDest);
2274 }
Manman Renbfb9d432012-09-15 00:39:57 +00002275 if (NewWeights.size() == 2) {
2276 // Halve the weights if any of them cannot fit in an uint32_t
2277 FitWeights(NewWeights);
2278
2279 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2280 PBI->setMetadata(LLVMContext::MD_prof,
2281 MDBuilder(BI->getContext()).
2282 createBranchWeights(MDWeights));
2283 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002284 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002285 } else {
2286 // Update PHI nodes in the common successors.
2287 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002288 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002289 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2290 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002291 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002292 if (PBI->getSuccessor(0) == TrueDest) {
2293 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2294 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2295 // is false: !PBI_Cond and BI_Value
2296 Instruction *NotCond =
2297 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2298 "not.cond"));
2299 MergedCond =
2300 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2301 NotCond, New,
2302 "and.cond"));
2303 if (PBI_C->isOne())
2304 MergedCond =
2305 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2306 PBI->getCondition(), MergedCond,
2307 "or.cond"));
2308 } else {
2309 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2310 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2311 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002312 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002313 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2314 PBI->getCondition(), New,
2315 "and.cond"));
2316 if (PBI_C->isOne()) {
2317 Instruction *NotCond =
2318 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2319 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002320 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002321 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2322 NotCond, MergedCond,
2323 "or.cond"));
2324 }
2325 }
2326 // Update PHI Node.
2327 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2328 MergedCond);
2329 }
2330 // Change PBI from Conditional to Unconditional.
2331 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2332 EraseTerminatorInstAndDCECond(PBI);
2333 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002334 }
Devang Pateld715ec82011-04-06 22:37:20 +00002335
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002336 // TODO: If BB is reachable from all paths through PredBlock, then we
2337 // could replace PBI's branch probabilities with BI's.
2338
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002339 // Copy any debug value intrinsics into the end of PredBlock.
2340 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2341 if (isa<DbgInfoIntrinsic>(*I))
2342 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002343
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002344 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002345 }
2346 return false;
2347}
2348
Chris Lattner9aada1d2008-07-13 21:53:26 +00002349/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2350/// predecessor of another block, this function tries to simplify it. We know
2351/// that PBI and BI are both conditional branches, and BI is in one of the
2352/// successor blocks of PBI - PBI branches to BI.
2353static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2354 assert(PBI->isConditional() && BI->isConditional());
2355 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002356
Chris Lattner9aada1d2008-07-13 21:53:26 +00002357 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002358 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002359 // this conditional branch redundant.
2360 if (PBI->getCondition() == BI->getCondition() &&
2361 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2362 // Okay, the outcome of this conditional branch is statically
2363 // knowable. If this block had a single pred, handle specially.
2364 if (BB->getSinglePredecessor()) {
2365 // Turn this into a branch on constant.
2366 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002367 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002368 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002369 return true; // Nuke the branch on constant.
2370 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002371
Chris Lattner9aada1d2008-07-13 21:53:26 +00002372 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2373 // in the constant and simplify the block result. Subsequent passes of
2374 // simplifycfg will thread the block.
2375 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002376 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002377 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002378 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002379 BI->getCondition()->getName() + ".pr",
2380 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002381 // Okay, we're going to insert the PHI node. Since PBI is not the only
2382 // predecessor, compute the PHI'd conditional value for all of the preds.
2383 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002384 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002385 BasicBlock *P = *PI;
2386 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002387 PBI != BI && PBI->isConditional() &&
2388 PBI->getCondition() == BI->getCondition() &&
2389 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2390 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002391 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002392 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002393 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002394 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002395 }
Gabor Greif8629f122010-07-12 10:59:23 +00002396 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002397
Chris Lattner9aada1d2008-07-13 21:53:26 +00002398 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002399 return true;
2400 }
2401 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002402
Chris Lattner9aada1d2008-07-13 21:53:26 +00002403 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002404 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002405 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002406 BasicBlock::iterator BBI = BB->begin();
2407 // Ignore dbg intrinsics.
2408 while (isa<DbgInfoIntrinsic>(BBI))
2409 ++BBI;
2410 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002411 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002412
Andrew Trickf3cf1932012-08-29 21:46:36 +00002413
Chris Lattnerc59945b2009-01-20 01:15:41 +00002414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2415 if (CE->canTrap())
2416 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002417
Chris Lattner834ab4e2008-07-13 22:04:41 +00002418 int PBIOp, BIOp;
2419 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2420 PBIOp = BIOp = 0;
2421 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2422 PBIOp = 0, BIOp = 1;
2423 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2424 PBIOp = 1, BIOp = 0;
2425 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2426 PBIOp = BIOp = 1;
2427 else
2428 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002429
Chris Lattner834ab4e2008-07-13 22:04:41 +00002430 // Check to make sure that the other destination of this branch
2431 // isn't BB itself. If so, this is an infinite loop that will
2432 // keep getting unwound.
2433 if (PBI->getSuccessor(PBIOp) == BB)
2434 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002435
2436 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002437 // insertion of a large number of select instructions. For targets
2438 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002439
Sanjay Patela932da82014-07-07 21:19:00 +00002440 // Also do not perform this transformation if any phi node in the common
2441 // destination block can trap when reached by BB or PBB (PR17073). In that
2442 // case, it would be unsafe to hoist the operation into a select instruction.
2443
2444 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002445 unsigned NumPhis = 0;
2446 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002447 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002448 if (NumPhis > 2) // Disable this xform.
2449 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002450
Sanjay Patela932da82014-07-07 21:19:00 +00002451 PHINode *PN = cast<PHINode>(II);
2452 Value *BIV = PN->getIncomingValueForBlock(BB);
2453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2454 if (CE->canTrap())
2455 return false;
2456
2457 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2458 Value *PBIV = PN->getIncomingValue(PBBIdx);
2459 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2460 if (CE->canTrap())
2461 return false;
2462 }
2463
Chris Lattner834ab4e2008-07-13 22:04:41 +00002464 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002465 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002466
David Greene725c7c32010-01-05 01:26:52 +00002467 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002468 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002469
2470
Chris Lattner80b03a12008-07-13 22:23:11 +00002471 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2472 // branch in it, where one edge (OtherDest) goes back to itself but the other
2473 // exits. We don't *know* that the program avoids the infinite loop
2474 // (even though that seems likely). If we do this xform naively, we'll end up
2475 // recursively unpeeling the loop. Since we know that (after the xform is
2476 // done) that the block *is* infinite if reached, we just make it an obviously
2477 // infinite loop with no cond branch.
2478 if (OtherDest == BB) {
2479 // Insert it at the end of the function, because it's either code,
2480 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002481 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2482 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002483 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2484 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002485 }
2486
David Greene725c7c32010-01-05 01:26:52 +00002487 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002488
Chris Lattner834ab4e2008-07-13 22:04:41 +00002489 // BI may have other predecessors. Because of this, we leave
2490 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002491
Chris Lattner834ab4e2008-07-13 22:04:41 +00002492 // Make sure we get to CommonDest on True&True directions.
2493 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002494 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002495 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002496 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2497
Chris Lattner834ab4e2008-07-13 22:04:41 +00002498 Value *BICond = BI->getCondition();
2499 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002500 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2501
Chris Lattner834ab4e2008-07-13 22:04:41 +00002502 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002503 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002504
Chris Lattner834ab4e2008-07-13 22:04:41 +00002505 // Modify PBI to branch on the new condition to the new dests.
2506 PBI->setCondition(Cond);
2507 PBI->setSuccessor(0, CommonDest);
2508 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002509
Manman Ren2d4c10f2012-09-17 21:30:40 +00002510 // Update branch weight for PBI.
2511 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002512 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2513 PredFalseWeight);
2514 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2515 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002516 if (PredHasWeights && SuccHasWeights) {
2517 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2518 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2519 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2520 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2521 // The weight to CommonDest should be PredCommon * SuccTotal +
2522 // PredOther * SuccCommon.
2523 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002524 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2525 PredOther * SuccCommon,
2526 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002527 // Halve the weights if any of them cannot fit in an uint32_t
2528 FitWeights(NewWeights);
2529
Manman Ren2d4c10f2012-09-17 21:30:40 +00002530 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002531 MDBuilder(BI->getContext())
2532 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002533 }
2534
Chris Lattner834ab4e2008-07-13 22:04:41 +00002535 // OtherDest may have phi nodes. If so, add an entry from PBI's
2536 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002537 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002538
Chris Lattner834ab4e2008-07-13 22:04:41 +00002539 // We know that the CommonDest already had an edge from PBI to
2540 // it. If it has PHIs though, the PHIs may have different
2541 // entries for BB and PBI's BB. If so, insert a select to make
2542 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002543 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002544 for (BasicBlock::iterator II = CommonDest->begin();
2545 (PN = dyn_cast<PHINode>(II)); ++II) {
2546 Value *BIV = PN->getIncomingValueForBlock(BB);
2547 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2548 Value *PBIV = PN->getIncomingValue(PBBIdx);
2549 if (BIV != PBIV) {
2550 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002551 Value *NV = cast<SelectInst>
2552 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002553 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002554 }
2555 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002556
David Greene725c7c32010-01-05 01:26:52 +00002557 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2558 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002559
Chris Lattner834ab4e2008-07-13 22:04:41 +00002560 // This basic block is probably dead. We know it has at least
2561 // one fewer predecessor.
2562 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002563}
2564
Frits van Bommel8e158492011-01-11 12:52:11 +00002565// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2566// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2567// Takes care of updating the successors and removing the old terminator.
2568// Also makes sure not to introduce new successors by assuming that edges to
2569// non-successor TrueBBs and FalseBBs aren't reachable.
2570static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002571 BasicBlock *TrueBB, BasicBlock *FalseBB,
2572 uint32_t TrueWeight,
2573 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002574 // Remove any superfluous successor edges from the CFG.
2575 // First, figure out which successors to preserve.
2576 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2577 // successor.
2578 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002579 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002580
2581 // Then remove the rest.
2582 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2583 BasicBlock *Succ = OldTerm->getSuccessor(I);
2584 // Make sure only to keep exactly one copy of each edge.
2585 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002586 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002587 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002588 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002589 else
2590 Succ->removePredecessor(OldTerm->getParent());
2591 }
2592
Devang Patel2c2ea222011-05-18 18:43:31 +00002593 IRBuilder<> Builder(OldTerm);
2594 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2595
Frits van Bommel8e158492011-01-11 12:52:11 +00002596 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002597 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002598 if (TrueBB == FalseBB)
2599 // We were only looking for one successor, and it was present.
2600 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002601 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002602 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002603 // We found both of the successors we were looking for.
2604 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002605 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2606 if (TrueWeight != FalseWeight)
2607 NewBI->setMetadata(LLVMContext::MD_prof,
2608 MDBuilder(OldTerm->getContext()).
2609 createBranchWeights(TrueWeight, FalseWeight));
2610 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002611 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2612 // Neither of the selected blocks were successors, so this
2613 // terminator must be unreachable.
2614 new UnreachableInst(OldTerm->getContext(), OldTerm);
2615 } else {
2616 // One of the selected values was a successor, but the other wasn't.
2617 // Insert an unconditional branch to the one that was found;
2618 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002619 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002620 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002621 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002622 else
2623 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002624 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002625 }
2626
2627 EraseTerminatorInstAndDCECond(OldTerm);
2628 return true;
2629}
2630
Frits van Bommel8ae07992011-02-28 09:44:07 +00002631// SimplifySwitchOnSelect - Replaces
2632// (switch (select cond, X, Y)) on constant X, Y
2633// with a branch - conditional if X and Y lead to distinct BBs,
2634// unconditional otherwise.
2635static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2636 // Check for constant integer values in the select.
2637 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2638 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2639 if (!TrueVal || !FalseVal)
2640 return false;
2641
2642 // Find the relevant condition and destinations.
2643 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002644 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2645 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002646
Manman Ren774246a2012-09-17 22:28:55 +00002647 // Get weight for TrueBB and FalseBB.
2648 uint32_t TrueWeight = 0, FalseWeight = 0;
2649 SmallVector<uint64_t, 8> Weights;
2650 bool HasWeights = HasBranchWeights(SI);
2651 if (HasWeights) {
2652 GetBranchWeights(SI, Weights);
2653 if (Weights.size() == 1 + SI->getNumCases()) {
2654 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2655 getSuccessorIndex()];
2656 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2657 getSuccessorIndex()];
2658 }
2659 }
2660
Frits van Bommel8ae07992011-02-28 09:44:07 +00002661 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002662 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2663 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002664}
2665
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002666// SimplifyIndirectBrOnSelect - Replaces
2667// (indirectbr (select cond, blockaddress(@fn, BlockA),
2668// blockaddress(@fn, BlockB)))
2669// with
2670// (br cond, BlockA, BlockB).
2671static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2672 // Check that both operands of the select are block addresses.
2673 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2674 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2675 if (!TBA || !FBA)
2676 return false;
2677
2678 // Extract the actual blocks.
2679 BasicBlock *TrueBB = TBA->getBasicBlock();
2680 BasicBlock *FalseBB = FBA->getBasicBlock();
2681
Frits van Bommel8e158492011-01-11 12:52:11 +00002682 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002683 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2684 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002685}
2686
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002687/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2688/// instruction (a seteq/setne with a constant) as the only instruction in a
2689/// block that ends with an uncond branch. We are looking for a very specific
2690/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2691/// this case, we merge the first two "or's of icmp" into a switch, but then the
2692/// default value goes to an uncond block with a seteq in it, we get something
2693/// like:
2694///
2695/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2696/// DEFAULT:
2697/// %tmp = icmp eq i8 %A, 92
2698/// br label %end
2699/// end:
2700/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002701///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002702/// We prefer to split the edge to 'end' so that there is a true/false entry to
2703/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002704static bool TryToSimplifyUncondBranchWithICmpInIt(
2705 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +00002706 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002707 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002708
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002709 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2710 // complex.
2711 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2712
2713 Value *V = ICI->getOperand(0);
2714 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002715
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002716 // The pattern we're looking for is where our only predecessor is a switch on
2717 // 'V' and this block is the default case for the switch. In this case we can
2718 // fold the compared value into the switch to simplify things.
2719 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002720 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002721
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002722 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2723 if (SI->getCondition() != V)
2724 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002725
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002726 // If BB is reachable on a non-default case, then we simply know the value of
2727 // V in this block. Substitute it and constant fold the icmp instruction
2728 // away.
2729 if (SI->getDefaultDest() != BB) {
2730 ConstantInt *VVal = SI->findCaseDest(BB);
2731 assert(VVal && "Should have a unique destination value");
2732 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002733
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002734 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002735 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002736 ICI->eraseFromParent();
2737 }
2738 // BB is now empty, so it is likely to simplify away.
Chandler Carruth66b31302015-01-04 12:03:27 +00002739 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002740 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002741
Chris Lattner62cc76e2010-12-13 03:43:57 +00002742 // Ok, the block is reachable from the default dest. If the constant we're
2743 // comparing exists in one of the other edges, then we can constant fold ICI
2744 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002745 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002746 Value *V;
2747 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2748 V = ConstantInt::getFalse(BB->getContext());
2749 else
2750 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002751
Chris Lattner62cc76e2010-12-13 03:43:57 +00002752 ICI->replaceAllUsesWith(V);
2753 ICI->eraseFromParent();
2754 // BB is now empty, so it is likely to simplify away.
Chandler Carruth66b31302015-01-04 12:03:27 +00002755 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002756 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002757
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002758 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2759 // the block.
2760 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002761 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002762 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002763 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2764 return false;
2765
2766 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2767 // true in the PHI.
2768 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2769 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2770
2771 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2772 std::swap(DefaultCst, NewCst);
2773
2774 // Replace ICI (which is used by the PHI for the default value) with true or
2775 // false depending on if it is EQ or NE.
2776 ICI->replaceAllUsesWith(DefaultCst);
2777 ICI->eraseFromParent();
2778
2779 // Okay, the switch goes to this block on a default value. Add an edge from
2780 // the switch to the merge point on the compared value.
2781 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2782 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002783 SmallVector<uint64_t, 8> Weights;
2784 bool HasWeights = HasBranchWeights(SI);
2785 if (HasWeights) {
2786 GetBranchWeights(SI, Weights);
2787 if (Weights.size() == 1 + SI->getNumCases()) {
2788 // Split weight for default case to case for "Cst".
2789 Weights[0] = (Weights[0]+1) >> 1;
2790 Weights.push_back(Weights[0]);
2791
2792 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2793 SI->setMetadata(LLVMContext::MD_prof,
2794 MDBuilder(SI->getContext()).
2795 createBranchWeights(MDWeights));
2796 }
2797 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002798 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002799
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002800 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002801 Builder.SetInsertPoint(NewBB);
2802 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2803 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002804 PHIUse->addIncoming(NewCst, NewBB);
2805 return true;
2806}
2807
Chris Lattnera69c4432010-12-13 05:03:41 +00002808/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2809/// Check to see if it is branching on an or/and chain of icmp instructions, and
2810/// fold it into a switch instruction if so.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002811static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
Devang Patel7de6c4b2011-05-18 23:18:47 +00002812 IRBuilder<> &Builder) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002813 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002814 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002815
Chris Lattnera69c4432010-12-13 05:03:41 +00002816 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2817 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2818 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002819
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002820 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00002821 ConstantComparesGatherer ConstantCompare(Cond, DL);
2822 // Unpack the result
2823 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2824 Value *CompVal = ConstantCompare.CompValue;
2825 unsigned UsedICmps = ConstantCompare.UsedICmps;
2826 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002827
Chris Lattnera69c4432010-12-13 05:03:41 +00002828 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002829 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002830
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002831 // Avoid turning single icmps into a switch.
2832 if (UsedICmps <= 1)
2833 return false;
2834
Mehdi Aminiffd01002014-11-20 22:40:25 +00002835 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2836
Chris Lattnera69c4432010-12-13 05:03:41 +00002837 // There might be duplicate constants in the list, which the switch
2838 // instruction can't handle, remove them now.
2839 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2840 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002841
Chris Lattnera69c4432010-12-13 05:03:41 +00002842 // If Extra was used, we require at least two switch values to do the
2843 // transformation. A switch with one value is just an cond branch.
2844 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002845
Andrew Trick3051aa12012-08-29 21:46:38 +00002846 // TODO: Preserve branch weight metadata, similarly to how
2847 // FoldValueComparisonIntoPredecessors preserves it.
2848
Chris Lattnera69c4432010-12-13 05:03:41 +00002849 // Figure out which block is which destination.
2850 BasicBlock *DefaultBB = BI->getSuccessor(1);
2851 BasicBlock *EdgeBB = BI->getSuccessor(0);
2852 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002853
Chris Lattnera69c4432010-12-13 05:03:41 +00002854 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002855
Chris Lattnerd7beca32010-12-14 06:17:25 +00002856 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002857 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002858
Chris Lattnera69c4432010-12-13 05:03:41 +00002859 // If there are any extra values that couldn't be folded into the switch
2860 // then we evaluate them with an explicit branch first. Split the block
2861 // right before the condbr to handle it.
2862 if (ExtraCase) {
2863 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2864 // Remove the uncond branch added to the old block.
2865 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002866 Builder.SetInsertPoint(OldTI);
2867
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002868 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002869 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002870 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002871 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002872
Chris Lattnera69c4432010-12-13 05:03:41 +00002873 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002874
Chris Lattnercb570f82010-12-13 05:34:18 +00002875 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2876 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002877 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002878
Chris Lattnerd7beca32010-12-14 06:17:25 +00002879 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2880 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002881 BB = NewBB;
2882 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002883
2884 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002885 // Convert pointer to int before we switch.
2886 if (CompVal->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002887 assert(DL && "Cannot switch on pointer without DataLayout");
Devang Patel7de6c4b2011-05-18 23:18:47 +00002888 CompVal = Builder.CreatePtrToInt(CompVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002889 DL->getIntPtrType(CompVal->getType()),
Devang Patel7de6c4b2011-05-18 23:18:47 +00002890 "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002891 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002892
Chris Lattnera69c4432010-12-13 05:03:41 +00002893 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002894 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002895
Chris Lattnera69c4432010-12-13 05:03:41 +00002896 // Add all of the 'cases' to the switch instruction.
2897 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2898 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002899
Chris Lattnera69c4432010-12-13 05:03:41 +00002900 // We added edges from PI to the EdgeBB. As such, if there were any
2901 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2902 // the number of edges added.
2903 for (BasicBlock::iterator BBI = EdgeBB->begin();
2904 isa<PHINode>(BBI); ++BBI) {
2905 PHINode *PN = cast<PHINode>(BBI);
2906 Value *InVal = PN->getIncomingValueForBlock(BB);
2907 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2908 PN->addIncoming(InVal, BB);
2909 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002910
Chris Lattnera69c4432010-12-13 05:03:41 +00002911 // Erase the old branch instruction.
2912 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002913
Chris Lattnerd7beca32010-12-14 06:17:25 +00002914 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002915 return true;
2916}
2917
Duncan Sands29192d02011-09-05 12:57:57 +00002918bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2919 // If this is a trivial landing pad that just continues unwinding the caught
2920 // exception then zap the landing pad, turning its invokes into calls.
2921 BasicBlock *BB = RI->getParent();
2922 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2923 if (RI->getValue() != LPInst)
2924 // Not a landing pad, or the resume is not unwinding the exception that
2925 // caused control to branch here.
2926 return false;
2927
2928 // Check that there are no other instructions except for debug intrinsics.
2929 BasicBlock::iterator I = LPInst, E = RI;
2930 while (++I != E)
2931 if (!isa<DbgInfoIntrinsic>(I))
2932 return false;
2933
2934 // Turn all invokes that unwind here into calls and delete the basic block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002935 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2936 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Duncan Sands29192d02011-09-05 12:57:57 +00002937 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2938 // Insert a call instruction before the invoke.
2939 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2940 Call->takeName(II);
2941 Call->setCallingConv(II->getCallingConv());
2942 Call->setAttributes(II->getAttributes());
2943 Call->setDebugLoc(II->getDebugLoc());
2944
2945 // Anything that used the value produced by the invoke instruction now uses
2946 // the value produced by the call instruction. Note that we do this even
2947 // for void functions and calls with no uses so that the callgraph edge is
2948 // updated.
2949 II->replaceAllUsesWith(Call);
2950 BB->removePredecessor(II->getParent());
2951
2952 // Insert a branch to the normal destination right before the invoke.
2953 BranchInst::Create(II->getNormalDest(), II);
2954
2955 // Finally, delete the invoke instruction!
2956 II->eraseFromParent();
2957 }
2958
Reid Klecknerf12b3342015-01-22 19:29:46 +00002959 // The landingpad is now unreachable. Zap it.
2960 BB->eraseFromParent();
2961 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00002962}
2963
Devang Pateldd14e0f2011-05-18 21:33:11 +00002964bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002965 BasicBlock *BB = RI->getParent();
2966 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002967
Chris Lattner25c3af32010-12-13 06:25:44 +00002968 // Find predecessors that end with branches.
2969 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2970 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002971 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2972 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00002973 TerminatorInst *PTI = P->getTerminator();
2974 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2975 if (BI->isUnconditional())
2976 UncondBranchPreds.push_back(P);
2977 else
2978 CondBranchPreds.push_back(BI);
2979 }
2980 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002981
Chris Lattner25c3af32010-12-13 06:25:44 +00002982 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00002983 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002984 while (!UncondBranchPreds.empty()) {
2985 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2986 DEBUG(dbgs() << "FOLDING: " << *BB
2987 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00002988 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00002989 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002990
Chris Lattner25c3af32010-12-13 06:25:44 +00002991 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00002992 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00002993 // We know there are no successors, so just nuke the block.
2994 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002995
Chris Lattner25c3af32010-12-13 06:25:44 +00002996 return true;
2997 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002998
Chris Lattner25c3af32010-12-13 06:25:44 +00002999 // Check out all of the conditional branches going to this return
3000 // instruction. If any of them just select between returns, change the
3001 // branch itself into a select/return pair.
3002 while (!CondBranchPreds.empty()) {
3003 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003004
Chris Lattner25c3af32010-12-13 06:25:44 +00003005 // Check to see if the non-BB successor is also a return block.
3006 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3007 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003008 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003009 return true;
3010 }
3011 return false;
3012}
3013
Chris Lattner25c3af32010-12-13 06:25:44 +00003014bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3015 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003016
Chris Lattner25c3af32010-12-13 06:25:44 +00003017 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003018
Chris Lattner25c3af32010-12-13 06:25:44 +00003019 // If there are any instructions immediately before the unreachable that can
3020 // be removed, do so.
3021 while (UI != BB->begin()) {
3022 BasicBlock::iterator BBI = UI;
3023 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003024 // Do not delete instructions that can have side effects which might cause
3025 // the unreachable to not be reachable; specifically, calls and volatile
3026 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003027 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003028
3029 if (BBI->mayHaveSideEffects()) {
3030 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3031 if (SI->isVolatile())
3032 break;
3033 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3034 if (LI->isVolatile())
3035 break;
3036 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3037 if (RMWI->isVolatile())
3038 break;
3039 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3040 if (CXI->isVolatile())
3041 break;
3042 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3043 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003044 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003045 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003046 // Note that deleting LandingPad's here is in fact okay, although it
3047 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3048 // all the predecessors of this block will be the unwind edges of Invokes,
3049 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003050 }
3051
Eli Friedmanaac35b32011-03-09 00:48:33 +00003052 // Delete this instruction (any uses are guaranteed to be dead)
3053 if (!BBI->use_empty())
3054 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003055 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003056 Changed = true;
3057 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003058
Chris Lattner25c3af32010-12-13 06:25:44 +00003059 // If the unreachable instruction is the first in the block, take a gander
3060 // at all of the predecessors of this instruction, and simplify them.
3061 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003062
Chris Lattner25c3af32010-12-13 06:25:44 +00003063 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3064 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3065 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003066 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003067 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3068 if (BI->isUnconditional()) {
3069 if (BI->getSuccessor(0) == BB) {
3070 new UnreachableInst(TI->getContext(), TI);
3071 TI->eraseFromParent();
3072 Changed = true;
3073 }
3074 } else {
3075 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003076 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003077 EraseTerminatorInstAndDCECond(BI);
3078 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003079 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003080 EraseTerminatorInstAndDCECond(BI);
3081 Changed = true;
3082 }
3083 }
3084 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003085 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003086 i != e; ++i)
3087 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003088 BB->removePredecessor(SI->getParent());
3089 SI->removeCase(i);
3090 --i; --e;
3091 Changed = true;
3092 }
Chris Lattner25c3af32010-12-13 06:25:44 +00003093 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3094 if (II->getUnwindDest() == BB) {
3095 // Convert the invoke to a call instruction. This would be a good
3096 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003097 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003098 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003099
Chris Lattner25c3af32010-12-13 06:25:44 +00003100 // Insert the call now...
3101 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003102 Builder.SetInsertPoint(BI);
3103 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003104 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003105 CI->setCallingConv(II->getCallingConv());
3106 CI->setAttributes(II->getAttributes());
3107 // If the invoke produced a value, the call does now instead.
3108 II->replaceAllUsesWith(CI);
3109 delete II;
3110 Changed = true;
3111 }
3112 }
3113 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003114
Chris Lattner25c3af32010-12-13 06:25:44 +00003115 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003116 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003117 BB != &BB->getParent()->getEntryBlock()) {
3118 // We know there are no successors, so just nuke the block.
3119 BB->eraseFromParent();
3120 return true;
3121 }
3122
3123 return Changed;
3124}
3125
Hans Wennborg68000082015-01-26 19:52:32 +00003126static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3127 assert(Cases.size() >= 1);
3128
3129 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3130 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3131 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3132 return false;
3133 }
3134 return true;
3135}
3136
3137/// Turn a switch with two reachable destinations into an integer range
3138/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003139static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003140 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003141
Hans Wennborg68000082015-01-26 19:52:32 +00003142 bool HasDefault =
3143 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003144
Hans Wennborg68000082015-01-26 19:52:32 +00003145 // Partition the cases into two sets with different destinations.
3146 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3147 BasicBlock *DestB = nullptr;
3148 SmallVector <ConstantInt *, 16> CasesA;
3149 SmallVector <ConstantInt *, 16> CasesB;
3150
3151 for (SwitchInst::CaseIt I : SI->cases()) {
3152 BasicBlock *Dest = I.getCaseSuccessor();
3153 if (!DestA) DestA = Dest;
3154 if (Dest == DestA) {
3155 CasesA.push_back(I.getCaseValue());
3156 continue;
3157 }
3158 if (!DestB) DestB = Dest;
3159 if (Dest == DestB) {
3160 CasesB.push_back(I.getCaseValue());
3161 continue;
3162 }
3163 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003164 }
3165
Hans Wennborg68000082015-01-26 19:52:32 +00003166 assert(DestA && DestB && "Single-destination switch should have been folded.");
3167 assert(DestA != DestB);
3168 assert(DestB != SI->getDefaultDest());
3169 assert(!CasesB.empty() && "There must be non-default cases.");
3170 assert(!CasesA.empty() || HasDefault);
3171
3172 // Figure out if one of the sets of cases form a contiguous range.
3173 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3174 BasicBlock *ContiguousDest = nullptr;
3175 BasicBlock *OtherDest = nullptr;
3176 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3177 ContiguousCases = &CasesA;
3178 ContiguousDest = DestA;
3179 OtherDest = DestB;
3180 } else if (CasesAreContiguous(CasesB)) {
3181 ContiguousCases = &CasesB;
3182 ContiguousDest = DestB;
3183 OtherDest = DestA;
3184 } else
3185 return false;
3186
3187 // Start building the compare and branch.
3188
3189 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3190 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003191
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003192 Value *Sub = SI->getCondition();
3193 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003194 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3195
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003196 Value *Cmp;
3197 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003198 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003199 Cmp = ConstantInt::getTrue(SI->getContext());
3200 else
3201 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003202 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003203
Manman Ren56575552012-09-18 00:47:33 +00003204 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003205 if (HasBranchWeights(SI)) {
3206 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003207 GetBranchWeights(SI, Weights);
3208 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003209 uint64_t TrueWeight = 0;
3210 uint64_t FalseWeight = 0;
3211 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3212 if (SI->getSuccessor(I) == ContiguousDest)
3213 TrueWeight += Weights[I];
3214 else
3215 FalseWeight += Weights[I];
3216 }
3217 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3218 TrueWeight /= 2;
3219 FalseWeight /= 2;
3220 }
Manman Ren56575552012-09-18 00:47:33 +00003221 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003222 MDBuilder(SI->getContext()).createBranchWeights(
3223 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003224 }
3225 }
3226
Hans Wennborg68000082015-01-26 19:52:32 +00003227 // Prune obsolete incoming values off the successors' PHI nodes.
3228 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3229 unsigned PreviousEdges = ContiguousCases->size();
3230 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3231 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003232 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3233 }
Hans Wennborg68000082015-01-26 19:52:32 +00003234 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3235 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3236 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3237 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3238 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3239 }
3240
3241 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003242 SI->eraseFromParent();
3243
3244 return true;
3245}
Chris Lattner25c3af32010-12-13 06:25:44 +00003246
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003247/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3248/// and use it to remove dead cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003249static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003250 AssumptionCache *AC) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003251 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003252 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003253 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003254 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003255
3256 // Gather dead cases.
3257 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003258 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003259 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3260 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3261 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003262 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003263 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003264 }
3265 }
3266
Manman Ren56575552012-09-18 00:47:33 +00003267 SmallVector<uint64_t, 8> Weights;
3268 bool HasWeight = HasBranchWeights(SI);
3269 if (HasWeight) {
3270 GetBranchWeights(SI, Weights);
3271 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3272 }
3273
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003274 // Remove dead cases from the switch.
3275 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003276 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003277 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003278 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003279 if (HasWeight) {
3280 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3281 Weights.pop_back();
3282 }
3283
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003284 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003285 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003286 SI->removeCase(Case);
3287 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003288 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003289 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3290 SI->setMetadata(LLVMContext::MD_prof,
3291 MDBuilder(SI->getParent()->getContext()).
3292 createBranchWeights(MDWeights));
3293 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003294
3295 return !DeadCases.empty();
3296}
3297
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003298/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3299/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3300/// by an unconditional branch), look at the phi node for BB in the successor
3301/// block and see if the incoming value is equal to CaseValue. If so, return
3302/// the phi node, and set PhiIndex to BB's index in the phi node.
3303static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3304 BasicBlock *BB,
3305 int *PhiIndex) {
3306 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003307 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003308 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003309 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003310
3311 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3312 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003313 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003314
3315 BasicBlock *Succ = Branch->getSuccessor(0);
3316
3317 BasicBlock::iterator I = Succ->begin();
3318 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3319 int Idx = PHI->getBasicBlockIndex(BB);
3320 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3321
3322 Value *InValue = PHI->getIncomingValue(Idx);
3323 if (InValue != CaseValue) continue;
3324
3325 *PhiIndex = Idx;
3326 return PHI;
3327 }
3328
Craig Topperf40110f2014-04-25 05:29:35 +00003329 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003330}
3331
3332/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3333/// instruction to a phi node dominated by the switch, if that would mean that
3334/// some of the destination blocks of the switch can be folded away.
3335/// Returns true if a change is made.
3336static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3337 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3338 ForwardingNodesMap ForwardingNodes;
3339
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003340 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003341 ConstantInt *CaseValue = I.getCaseValue();
3342 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003343
3344 int PhiIndex;
3345 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3346 &PhiIndex);
3347 if (!PHI) continue;
3348
3349 ForwardingNodes[PHI].push_back(PhiIndex);
3350 }
3351
3352 bool Changed = false;
3353
3354 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3355 E = ForwardingNodes.end(); I != E; ++I) {
3356 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003357 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003358
3359 if (Indexes.size() < 2) continue;
3360
3361 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3362 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3363 Changed = true;
3364 }
3365
3366 return Changed;
3367}
3368
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003369/// ValidLookupTableConstant - Return true if the backend will be able to handle
3370/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003371static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003372 if (C->isThreadDependent())
3373 return false;
3374 if (C->isDLLImportDependent())
3375 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003376
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3378 return CE->isGEPWithNoNotionalOverIndexing();
3379
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003380 return isa<ConstantFP>(C) ||
3381 isa<ConstantInt>(C) ||
3382 isa<ConstantPointerNull>(C) ||
3383 isa<GlobalValue>(C) ||
3384 isa<UndefValue>(C);
3385}
3386
Hans Wennborg09acdb92012-10-31 15:14:39 +00003387/// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003388/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003389static Constant *LookupConstant(Value *V,
3390 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3391 if (Constant *C = dyn_cast<Constant>(V))
3392 return C;
3393 return ConstantPool.lookup(V);
3394}
3395
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003396/// ConstantFold - Try to fold instruction I into a constant. This works for
3397/// simple instructions such as binary operations where both operands are
3398/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003399/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003400static Constant *
3401ConstantFold(Instruction *I,
3402 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3403 const DataLayout *DL) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003404 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003405 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3406 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003407 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003408 if (A->isAllOnesValue())
3409 return LookupConstant(Select->getTrueValue(), ConstantPool);
3410 if (A->isNullValue())
3411 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003412 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003413 }
3414
Benjamin Kramer7c302602013-11-12 12:24:36 +00003415 SmallVector<Constant *, 4> COps;
3416 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3417 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3418 COps.push_back(A);
3419 else
Craig Topperf40110f2014-04-25 05:29:35 +00003420 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003421 }
3422
Benjamin Kramer7c302602013-11-12 12:24:36 +00003423 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3424 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3425 COps[1], DL);
3426
3427 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003428}
3429
3430/// GetCaseResults - Try to determine the resulting constant values in phi nodes
3431/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003432/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003433/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003434static bool
3435GetCaseResults(SwitchInst *SI,
3436 ConstantInt *CaseVal,
3437 BasicBlock *CaseDest,
3438 BasicBlock **CommonDest,
Benjamin Kramer7c302602013-11-12 12:24:36 +00003439 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3440 const DataLayout *DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003441 // The block from which we enter the common destination.
3442 BasicBlock *Pred = SI->getParent();
3443
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003444 // If CaseDest is empty except for some side-effect free instructions through
3445 // which we can constant-propagate the CaseVal, continue to its successor.
3446 SmallDenseMap<Value*, Constant*> ConstantPool;
3447 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3448 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3449 ++I) {
3450 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3451 // If the terminator is a simple branch, continue to the next block.
3452 if (T->getNumSuccessors() != 1)
3453 return false;
3454 Pred = CaseDest;
3455 CaseDest = T->getSuccessor(0);
3456 } else if (isa<DbgInfoIntrinsic>(I)) {
3457 // Skip debug intrinsic.
3458 continue;
Benjamin Kramer7c302602013-11-12 12:24:36 +00003459 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003460 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003461
3462 // If the instruction has uses outside this block or a phi node slot for
3463 // the block, it is not safe to bypass the instruction since it would then
3464 // no longer dominate all its uses.
3465 for (auto &Use : I->uses()) {
3466 User *User = Use.getUser();
3467 if (Instruction *I = dyn_cast<Instruction>(User))
3468 if (I->getParent() == CaseDest)
3469 continue;
3470 if (PHINode *Phi = dyn_cast<PHINode>(User))
3471 if (Phi->getIncomingBlock(Use) == CaseDest)
3472 continue;
3473 return false;
3474 }
3475
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003476 ConstantPool.insert(std::make_pair(I, C));
3477 } else {
3478 break;
3479 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003480 }
3481
3482 // If we did not have a CommonDest before, use the current one.
3483 if (!*CommonDest)
3484 *CommonDest = CaseDest;
3485 // If the destination isn't the common one, abort.
3486 if (CaseDest != *CommonDest)
3487 return false;
3488
3489 // Get the values for this case from phi nodes in the destination block.
3490 BasicBlock::iterator I = (*CommonDest)->begin();
3491 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3492 int Idx = PHI->getBasicBlockIndex(Pred);
3493 if (Idx == -1)
3494 continue;
3495
Hans Wennborg09acdb92012-10-31 15:14:39 +00003496 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3497 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003498 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003499 return false;
3500
3501 // Be conservative about which kinds of constants we support.
3502 if (!ValidLookupTableConstant(ConstVal))
3503 return false;
3504
3505 Res.push_back(std::make_pair(PHI, ConstVal));
3506 }
3507
Hans Wennborgac114a32014-01-12 00:44:41 +00003508 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003509}
3510
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003511// MapCaseToResult - Helper function used to
3512// add CaseVal to the list of cases that generate Result.
3513static void MapCaseToResult(ConstantInt *CaseVal,
3514 SwitchCaseResultVectorTy &UniqueResults,
3515 Constant *Result) {
3516 for (auto &I : UniqueResults) {
3517 if (I.first == Result) {
3518 I.second.push_back(CaseVal);
3519 return;
3520 }
3521 }
3522 UniqueResults.push_back(std::make_pair(Result,
3523 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3524}
3525
3526// InitializeUniqueCases - Helper function that initializes a map containing
3527// results for the PHI node of the common destination block for a switch
3528// instruction. Returns false if multiple PHI nodes have been found or if
3529// there is not a common destination block for the switch.
3530static bool InitializeUniqueCases(
3531 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3532 BasicBlock *&CommonDest,
3533 SwitchCaseResultVectorTy &UniqueResults,
3534 Constant *&DefaultResult) {
3535 for (auto &I : SI->cases()) {
3536 ConstantInt *CaseVal = I.getCaseValue();
3537
3538 // Resulting value at phi nodes for this case value.
3539 SwitchCaseResultsTy Results;
3540 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3541 DL))
3542 return false;
3543
3544 // Only one value per case is permitted
3545 if (Results.size() > 1)
3546 return false;
3547 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3548
3549 // Check the PHI consistency.
3550 if (!PHI)
3551 PHI = Results[0].first;
3552 else if (PHI != Results[0].first)
3553 return false;
3554 }
3555 // Find the default result value.
3556 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3557 BasicBlock *DefaultDest = SI->getDefaultDest();
3558 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3559 DL);
3560 // If the default value is not found abort unless the default destination
3561 // is unreachable.
3562 DefaultResult =
3563 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3564 if ((!DefaultResult &&
3565 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3566 return false;
3567
3568 return true;
3569}
3570
3571// ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3572// transform a switch with only two cases (or two cases + default)
3573// that produces a result into a value select.
3574// Example:
3575// switch (a) {
3576// case 10: %0 = icmp eq i32 %a, 10
3577// return 10; %1 = select i1 %0, i32 10, i32 4
3578// case 20: ----> %2 = icmp eq i32 %a, 20
3579// return 2; %3 = select i1 %2, i32 2, i32 %1
3580// default:
3581// return 4;
3582// }
3583static Value *
3584ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3585 Constant *DefaultResult, Value *Condition,
3586 IRBuilder<> &Builder) {
3587 assert(ResultVector.size() == 2 &&
3588 "We should have exactly two unique results at this point");
3589 // If we are selecting between only two cases transform into a simple
3590 // select or a two-way select if default is possible.
3591 if (ResultVector[0].second.size() == 1 &&
3592 ResultVector[1].second.size() == 1) {
3593 ConstantInt *const FirstCase = ResultVector[0].second[0];
3594 ConstantInt *const SecondCase = ResultVector[1].second[0];
3595
3596 bool DefaultCanTrigger = DefaultResult;
3597 Value *SelectValue = ResultVector[1].first;
3598 if (DefaultCanTrigger) {
3599 Value *const ValueCompare =
3600 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3601 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3602 DefaultResult, "switch.select");
3603 }
3604 Value *const ValueCompare =
3605 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3606 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3607 "switch.select");
3608 }
3609
3610 return nullptr;
3611}
3612
3613// RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3614// instruction that has been converted into a select, fixing up PHI nodes and
3615// basic blocks.
3616static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3617 Value *SelectValue,
3618 IRBuilder<> &Builder) {
3619 BasicBlock *SelectBB = SI->getParent();
3620 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3621 PHI->removeIncomingValue(SelectBB);
3622 PHI->addIncoming(SelectValue, SelectBB);
3623
3624 Builder.CreateBr(PHI->getParent());
3625
3626 // Remove the switch.
3627 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3628 BasicBlock *Succ = SI->getSuccessor(i);
3629
3630 if (Succ == PHI->getParent())
3631 continue;
3632 Succ->removePredecessor(SelectBB);
3633 }
3634 SI->eraseFromParent();
3635}
3636
3637/// SwitchToSelect - If the switch is only used to initialize one or more
3638/// phi nodes in a common successor block with only two different
3639/// constant values, replace the switch with select.
3640static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Chandler Carruth66b31302015-01-04 12:03:27 +00003641 const DataLayout *DL, AssumptionCache *AC) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003642 Value *const Cond = SI->getCondition();
3643 PHINode *PHI = nullptr;
3644 BasicBlock *CommonDest = nullptr;
3645 Constant *DefaultResult;
3646 SwitchCaseResultVectorTy UniqueResults;
3647 // Collect all the cases that will deliver the same value from the switch.
3648 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3649 DefaultResult))
3650 return false;
3651 // Selects choose between maximum two values.
3652 if (UniqueResults.size() != 2)
3653 return false;
3654 assert(PHI != nullptr && "PHI for value select not found");
3655
3656 Builder.SetInsertPoint(SI);
3657 Value *SelectValue = ConvertTwoCaseSwitch(
3658 UniqueResults,
3659 DefaultResult, Cond, Builder);
3660 if (SelectValue) {
3661 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3662 return true;
3663 }
3664 // The switch couldn't be converted into a select.
3665 return false;
3666}
3667
Hans Wennborg776d7122012-09-26 09:34:53 +00003668namespace {
3669 /// SwitchLookupTable - This class represents a lookup table that can be used
3670 /// to replace a switch.
3671 class SwitchLookupTable {
3672 public:
3673 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3674 /// with the contents of Values, using DefaultValue to fill any holes in the
3675 /// table.
3676 SwitchLookupTable(Module &M,
3677 uint64_t TableSize,
3678 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003679 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003680 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003681 const DataLayout *DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003682
3683 /// BuildLookup - Build instructions with Builder to retrieve the value at
3684 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003685 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003686
Hans Wennborg39583b82012-09-26 09:44:49 +00003687 /// WouldFitInRegister - Return true if a table with TableSize elements of
3688 /// type ElementType would fit in a target-legal register.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003689 static bool WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003690 uint64_t TableSize,
3691 const Type *ElementType);
3692
Hans Wennborg776d7122012-09-26 09:34:53 +00003693 private:
3694 // Depending on the contents of the table, it can be represented in
3695 // different ways.
3696 enum {
3697 // For tables where each element contains the same value, we just have to
3698 // store that single value and return it for each lookup.
3699 SingleValueKind,
3700
Erik Eckstein105374f2014-11-17 09:13:57 +00003701 // For tables where there is a linear relationship between table index
3702 // and values. We calculate the result with a simple multiplication
3703 // and addition instead of a table lookup.
3704 LinearMapKind,
3705
Hans Wennborg39583b82012-09-26 09:44:49 +00003706 // For small tables with integer elements, we can pack them into a bitmap
3707 // that fits into a target-legal register. Values are retrieved by
3708 // shift and mask operations.
3709 BitMapKind,
3710
Hans Wennborg776d7122012-09-26 09:34:53 +00003711 // The table is stored as an array of values. Values are retrieved by load
3712 // instructions from the table.
3713 ArrayKind
3714 } Kind;
3715
3716 // For SingleValueKind, this is the single value.
3717 Constant *SingleValue;
3718
Hans Wennborg39583b82012-09-26 09:44:49 +00003719 // For BitMapKind, this is the bitmap.
3720 ConstantInt *BitMap;
3721 IntegerType *BitMapElementTy;
3722
Erik Eckstein105374f2014-11-17 09:13:57 +00003723 // For LinearMapKind, these are the constants used to derive the value.
3724 ConstantInt *LinearOffset;
3725 ConstantInt *LinearMultiplier;
3726
Hans Wennborg776d7122012-09-26 09:34:53 +00003727 // For ArrayKind, this is the array.
3728 GlobalVariable *Array;
3729 };
3730}
3731
3732SwitchLookupTable::SwitchLookupTable(Module &M,
3733 uint64_t TableSize,
3734 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003735 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003736 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003737 const DataLayout *DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003738 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003739 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003740 assert(Values.size() && "Can't build lookup table without values!");
3741 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003742
3743 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003744 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003745
Hans Wennborgac114a32014-01-12 00:44:41 +00003746 Type *ValueType = Values.begin()->second->getType();
3747
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003748 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003749 SmallVector<Constant*, 64> TableContents(TableSize);
3750 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3751 ConstantInt *CaseVal = Values[I].first;
3752 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003753 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003754
Hans Wennborg776d7122012-09-26 09:34:53 +00003755 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3756 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003757 TableContents[Idx] = CaseRes;
3758
Hans Wennborg776d7122012-09-26 09:34:53 +00003759 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003760 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003761 }
3762
3763 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003764 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003765 assert(DefaultValue &&
3766 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003767 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003768 for (uint64_t I = 0; I < TableSize; ++I) {
3769 if (!TableContents[I])
3770 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003771 }
3772
Hans Wennborg776d7122012-09-26 09:34:53 +00003773 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003774 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003775 }
3776
Hans Wennborg776d7122012-09-26 09:34:53 +00003777 // If each element in the table contains the same value, we only need to store
3778 // that single value.
3779 if (SingleValue) {
3780 Kind = SingleValueKind;
3781 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003782 }
3783
Erik Eckstein105374f2014-11-17 09:13:57 +00003784 // Check if we can derive the value with a linear transformation from the
3785 // table index.
3786 if (isa<IntegerType>(ValueType)) {
3787 bool LinearMappingPossible = true;
3788 APInt PrevVal;
3789 APInt DistToPrev;
3790 assert(TableSize >= 2 && "Should be a SingleValue table.");
3791 // Check if there is the same distance between two consecutive values.
3792 for (uint64_t I = 0; I < TableSize; ++I) {
3793 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3794 if (!ConstVal) {
3795 // This is an undef. We could deal with it, but undefs in lookup tables
3796 // are very seldom. It's probably not worth the additional complexity.
3797 LinearMappingPossible = false;
3798 break;
3799 }
3800 APInt Val = ConstVal->getValue();
3801 if (I != 0) {
3802 APInt Dist = Val - PrevVal;
3803 if (I == 1) {
3804 DistToPrev = Dist;
3805 } else if (Dist != DistToPrev) {
3806 LinearMappingPossible = false;
3807 break;
3808 }
3809 }
3810 PrevVal = Val;
3811 }
3812 if (LinearMappingPossible) {
3813 LinearOffset = cast<ConstantInt>(TableContents[0]);
3814 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3815 Kind = LinearMapKind;
3816 ++NumLinearMaps;
3817 return;
3818 }
3819 }
3820
Hans Wennborg39583b82012-09-26 09:44:49 +00003821 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003822 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003823 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003824 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3825 for (uint64_t I = TableSize; I > 0; --I) {
3826 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003827 // Insert values into the bitmap. Undef values are set to zero.
3828 if (!isa<UndefValue>(TableContents[I - 1])) {
3829 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3830 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3831 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003832 }
3833 BitMap = ConstantInt::get(M.getContext(), TableInt);
3834 BitMapElementTy = IT;
3835 Kind = BitMapKind;
3836 ++NumBitMaps;
3837 return;
3838 }
3839
Hans Wennborg776d7122012-09-26 09:34:53 +00003840 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003841 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003842 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3843
Hans Wennborg776d7122012-09-26 09:34:53 +00003844 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3845 GlobalVariable::PrivateLinkage,
3846 Initializer,
3847 "switch.table");
3848 Array->setUnnamedAddr(true);
3849 Kind = ArrayKind;
3850}
3851
Manman Ren4d189fb2014-07-24 21:13:20 +00003852Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003853 switch (Kind) {
3854 case SingleValueKind:
3855 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00003856 case LinearMapKind: {
3857 // Derive the result value from the input value.
3858 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3859 false, "switch.idx.cast");
3860 if (!LinearMultiplier->isOne())
3861 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3862 if (!LinearOffset->isZero())
3863 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3864 return Result;
3865 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003866 case BitMapKind: {
3867 // Type of the bitmap (e.g. i59).
3868 IntegerType *MapTy = BitMap->getType();
3869
3870 // Cast Index to the same type as the bitmap.
3871 // Note: The Index is <= the number of elements in the table, so
3872 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003873 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003874
3875 // Multiply the shift amount by the element width.
3876 ShiftAmt = Builder.CreateMul(ShiftAmt,
3877 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3878 "switch.shiftamt");
3879
3880 // Shift down.
3881 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3882 "switch.downshift");
3883 // Mask off.
3884 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3885 "switch.masked");
3886 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003887 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003888 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003889 IntegerType *IT = cast<IntegerType>(Index->getType());
3890 uint64_t TableSize = Array->getInitializer()->getType()
3891 ->getArrayNumElements();
3892 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3893 Index = Builder.CreateZExt(Index,
3894 IntegerType::get(IT->getContext(),
3895 IT->getBitWidth() + 1),
3896 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003897
Hans Wennborg776d7122012-09-26 09:34:53 +00003898 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3899 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3900 "switch.gep");
3901 return Builder.CreateLoad(GEP, "switch.load");
3902 }
3903 }
3904 llvm_unreachable("Unknown lookup table kind!");
3905}
3906
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003907bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003908 uint64_t TableSize,
3909 const Type *ElementType) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003910 if (!DL)
Hans Wennborg39583b82012-09-26 09:44:49 +00003911 return false;
3912 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3913 if (!IT)
3914 return false;
3915 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3916 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003917
3918 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3919 if (TableSize >= UINT_MAX/IT->getBitWidth())
3920 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003921 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003922}
3923
Hans Wennborg776d7122012-09-26 09:34:53 +00003924/// ShouldBuildLookupTable - Determine whether a lookup table should be built
Hans Wennborg5cf30be2013-06-04 11:22:30 +00003925/// for this switch, based on the number of cases, size of the table and the
Hans Wennborg776d7122012-09-26 09:34:53 +00003926/// types of the results.
3927static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003928 uint64_t TableSize,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003929 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003930 const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003931 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003932 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3933 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003934
Chandler Carruth77d433d2012-11-30 09:26:25 +00003935 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003936 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00003937 for (const auto &I : ResultTypes) {
3938 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003939
3940 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003941 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003942
3943 // Saturate this flag to false.
3944 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003945 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003946
3947 // If both flags saturate, we're done. NOTE: This *only* works with
3948 // saturating flags, and all flags have to saturate first due to the
3949 // non-deterministic behavior of iterating over a dense map.
3950 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003951 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003952 }
Evan Cheng65df8082012-11-30 02:02:42 +00003953
Chandler Carruth77d433d2012-11-30 09:26:25 +00003954 // If each table would fit in a register, we should build it anyway.
3955 if (AllTablesFitInRegister)
3956 return true;
3957
3958 // Don't build a table that doesn't fit in-register if it has illegal types.
3959 if (HasIllegalType)
3960 return false;
3961
3962 // The table density should be at least 40%. This is the same criterion as for
3963 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3964 // FIXME: Find the best cut-off.
3965 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003966}
3967
Erik Eckstein0d86c762014-11-27 15:13:14 +00003968/// Try to reuse the switch table index compare. Following pattern:
3969/// \code
3970/// if (idx < tablesize)
3971/// r = table[idx]; // table does not contain default_value
3972/// else
3973/// r = default_value;
3974/// if (r != default_value)
3975/// ...
3976/// \endcode
3977/// Is optimized to:
3978/// \code
3979/// cond = idx < tablesize;
3980/// if (cond)
3981/// r = table[idx];
3982/// else
3983/// r = default_value;
3984/// if (cond)
3985/// ...
3986/// \endcode
3987/// Jump threading will then eliminate the second if(cond).
3988static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
3989 BranchInst *RangeCheckBranch, Constant *DefaultValue,
3990 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
3991
3992 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
3993 if (!CmpInst)
3994 return;
3995
3996 // We require that the compare is in the same block as the phi so that jump
3997 // threading can do its work afterwards.
3998 if (CmpInst->getParent() != PhiBlock)
3999 return;
4000
4001 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4002 if (!CmpOp1)
4003 return;
4004
4005 Value *RangeCmp = RangeCheckBranch->getCondition();
4006 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4007 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4008
4009 // Check if the compare with the default value is constant true or false.
4010 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4011 DefaultValue, CmpOp1, true);
4012 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4013 return;
4014
4015 // Check if the compare with the case values is distinct from the default
4016 // compare result.
4017 for (auto ValuePair : Values) {
4018 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4019 ValuePair.second, CmpOp1, true);
4020 if (!CaseConst || CaseConst == DefaultConst)
4021 return;
4022 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4023 "Expect true or false as compare result.");
4024 }
4025
4026 // Check if the branch instruction dominates the phi node. It's a simple
4027 // dominance check, but sufficient for our needs.
4028 // Although this check is invariant in the calling loops, it's better to do it
4029 // at this late stage. Practically we do it at most once for a switch.
4030 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4031 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4032 BasicBlock *Pred = *PI;
4033 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4034 return;
4035 }
4036
4037 if (DefaultConst == FalseConst) {
4038 // The compare yields the same result. We can replace it.
4039 CmpInst->replaceAllUsesWith(RangeCmp);
4040 ++NumTableCmpReuses;
4041 } else {
4042 // The compare yields the same result, just inverted. We can replace it.
4043 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4044 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4045 RangeCheckBranch);
4046 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4047 ++NumTableCmpReuses;
4048 }
4049}
4050
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004051/// SwitchToLookupTable - If the switch is only used to initialize one or more
4052/// phi nodes in a common successor block with different constant values,
4053/// replace the switch with lookup tables.
4054static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00004055 IRBuilder<> &Builder,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004056 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004057 const DataLayout* DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004058 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004059
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004060 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004061 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004062 return false;
4063
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004064 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4065 // split off a dense part and build a lookup table for that.
4066
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004067 // FIXME: This creates arrays of GEPs to constant strings, which means each
4068 // GEP needs a runtime relocation in PIC code. We should just build one big
4069 // string and lookup indices into that.
4070
Hans Wennborg4744ac12014-01-15 05:00:27 +00004071 // Ignore switches with less than three cases. Lookup tables will not make them
4072 // faster, so we don't analyze them.
4073 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004074 return false;
4075
4076 // Figure out the corresponding result for each case value and phi node in the
4077 // common destination, as well as the the min and max case values.
4078 assert(SI->case_begin() != SI->case_end());
4079 SwitchInst::CaseIt CI = SI->case_begin();
4080 ConstantInt *MinCaseVal = CI.getCaseValue();
4081 ConstantInt *MaxCaseVal = CI.getCaseValue();
4082
Craig Topperf40110f2014-04-25 05:29:35 +00004083 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004084 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004085 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4086 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4087 SmallDenseMap<PHINode*, Type*> ResultTypes;
4088 SmallVector<PHINode*, 4> PHIs;
4089
4090 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4091 ConstantInt *CaseVal = CI.getCaseValue();
4092 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4093 MinCaseVal = CaseVal;
4094 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4095 MaxCaseVal = CaseVal;
4096
4097 // Resulting value at phi nodes for this case value.
4098 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4099 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004100 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004101 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004102 return false;
4103
4104 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004105 for (const auto &I : Results) {
4106 PHINode *PHI = I.first;
4107 Constant *Value = I.second;
4108 if (!ResultLists.count(PHI))
4109 PHIs.push_back(PHI);
4110 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004111 }
4112 }
4113
Hans Wennborgac114a32014-01-12 00:44:41 +00004114 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004115 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004116 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4117 }
4118
4119 uint64_t NumResults = ResultLists[PHIs[0]].size();
4120 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4121 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4122 bool TableHasHoles = (NumResults < TableSize);
4123
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004124 // If the table has holes, we need a constant result for the default case
4125 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004126 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004127 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Craig Topperf40110f2014-04-25 05:29:35 +00004128 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004129
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004130 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4131 if (NeedMask) {
4132 // As an extra penalty for the validity test we require more cases.
4133 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4134 return false;
4135 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4136 return false;
4137 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004138
Hans Wennborga6a11a92014-11-18 02:37:11 +00004139 for (const auto &I : DefaultResultsList) {
4140 PHINode *PHI = I.first;
4141 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004142 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004143 }
4144
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004145 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004146 return false;
4147
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004148 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004149 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004150 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4151 "switch.lookup",
4152 CommonDest->getParent(),
4153 CommonDest);
4154
Michael Gottesmanc024f322013-10-20 07:04:37 +00004155 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004156 Builder.SetInsertPoint(SI);
4157 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4158 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004159
4160 // Compute the maximum table size representable by the integer type we are
4161 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004162 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004163 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004164 assert(MaxTableSize >= TableSize &&
4165 "It is impossible for a switch to have more entries than the max "
4166 "representable value of its input integer type's size.");
4167
Hans Wennborgb64cb272015-01-26 19:52:34 +00004168 // If the default destination is unreachable, or if the lookup table covers
4169 // all values of the conditional variable, branch directly to the lookup table
4170 // BB. Otherwise, check that the condition is within the case range.
4171 const bool DefaultIsReachable =
4172 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4173 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004174 BranchInst *RangeCheckBranch = nullptr;
4175
Hans Wennborgb64cb272015-01-26 19:52:34 +00004176 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004177 Builder.CreateBr(LookupBB);
Manman Ren062f58d2014-08-02 23:41:54 +00004178 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4179 // do not delete PHINodes here.
4180 SI->getDefaultDest()->removePredecessor(SI->getParent(),
Hans Wennborgb64cb272015-01-26 19:52:34 +00004181 /*DontDeleteUselessPHIs=*/true);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004182 } else {
4183 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004184 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004185 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004186 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004187
4188 // Populate the BB that does the lookups.
4189 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004190
4191 if (NeedMask) {
4192 // Before doing the lookup we do the hole check.
4193 // The LookupBB is therefore re-purposed to do the hole check
4194 // and we create a new LookupBB.
4195 BasicBlock *MaskBB = LookupBB;
4196 MaskBB->setName("switch.hole_check");
4197 LookupBB = BasicBlock::Create(Mod.getContext(),
4198 "switch.lookup",
4199 CommonDest->getParent(),
4200 CommonDest);
4201
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004202 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4203 // unnecessary illegal types.
4204 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4205 APInt MaskInt(TableSizePowOf2, 0);
4206 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004207 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004208 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4209 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4210 uint64_t Idx = (ResultList[I].first->getValue() -
4211 MinCaseVal->getValue()).getLimitedValue();
4212 MaskInt |= One << Idx;
4213 }
4214 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4215
4216 // Get the TableIndex'th bit of the bitmask.
4217 // If this bit is 0 (meaning hole) jump to the default destination,
4218 // else continue with table lookup.
4219 IntegerType *MapTy = TableMask->getType();
4220 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4221 "switch.maskindex");
4222 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4223 "switch.shifted");
4224 Value *LoBit = Builder.CreateTrunc(Shifted,
4225 Type::getInt1Ty(Mod.getContext()),
4226 "switch.lobit");
4227 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4228
4229 Builder.SetInsertPoint(LookupBB);
4230 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4231 }
4232
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004233 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004234 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4235 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004236 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004237
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004238 // If using a bitmask, use any value to fill the lookup table holes.
4239 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004240 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004241
Manman Ren4d189fb2014-07-24 21:13:20 +00004242 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004243
Hans Wennborgf744fa92012-09-19 14:24:21 +00004244 // If the result is used to return immediately from the function, we want to
4245 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004246 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4247 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004248 Builder.CreateRet(Result);
4249 ReturnedEarly = true;
4250 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004251 }
4252
Erik Eckstein0d86c762014-11-27 15:13:14 +00004253 // Do a small peephole optimization: re-use the switch table compare if
4254 // possible.
4255 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4256 BasicBlock *PhiBlock = PHI->getParent();
4257 // Search for compare instructions which use the phi.
4258 for (auto *User : PHI->users()) {
4259 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4260 }
4261 }
4262
Hans Wennborgf744fa92012-09-19 14:24:21 +00004263 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004264 }
4265
4266 if (!ReturnedEarly)
4267 Builder.CreateBr(CommonDest);
4268
4269 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004270 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004271 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004272
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004273 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004274 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004275 Succ->removePredecessor(SI->getParent());
4276 }
4277 SI->eraseFromParent();
4278
4279 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004280 if (NeedMask)
4281 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004282 return true;
4283}
4284
Devang Patela7ec47d2011-05-18 20:35:38 +00004285bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004286 BasicBlock *BB = SI->getParent();
4287
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004288 if (isValueEqualityComparison(SI)) {
4289 // If we only have one predecessor, and if it is a branch on this value,
4290 // see if that predecessor totally determines the outcome of this switch.
4291 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4292 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Chandler Carruth66b31302015-01-04 12:03:27 +00004293 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004294
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004295 Value *Cond = SI->getCondition();
4296 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4297 if (SimplifySwitchOnSelect(SI, Select))
Chandler Carruth66b31302015-01-04 12:03:27 +00004298 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004299
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004300 // If the block only contains the switch, see if we can fold the block
4301 // away into any preds.
4302 BasicBlock::iterator BBI = BB->begin();
4303 // Ignore dbg intrinsics.
4304 while (isa<DbgInfoIntrinsic>(BBI))
4305 ++BBI;
4306 if (SI == &*BBI)
4307 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Chandler Carruth66b31302015-01-04 12:03:27 +00004308 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004309 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004310
4311 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004312 if (TurnSwitchRangeIntoICmp(SI, Builder))
Chandler Carruth66b31302015-01-04 12:03:27 +00004313 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004314
4315 // Remove unreachable cases.
Chandler Carruth66b31302015-01-04 12:03:27 +00004316 if (EliminateDeadSwitchCases(SI, DL, AC))
4317 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004318
Chandler Carruth66b31302015-01-04 12:03:27 +00004319 if (SwitchToSelect(SI, Builder, DL, AC))
4320 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004321
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004322 if (ForwardSwitchConditionToPHI(SI))
Chandler Carruth66b31302015-01-04 12:03:27 +00004323 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004324
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004325 if (SwitchToLookupTable(SI, Builder, TTI, DL))
Chandler Carruth66b31302015-01-04 12:03:27 +00004326 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004327
Chris Lattner25c3af32010-12-13 06:25:44 +00004328 return false;
4329}
4330
4331bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4332 BasicBlock *BB = IBI->getParent();
4333 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004334
Chris Lattner25c3af32010-12-13 06:25:44 +00004335 // Eliminate redundant destinations.
4336 SmallPtrSet<Value *, 8> Succs;
4337 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4338 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004339 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004340 Dest->removePredecessor(BB);
4341 IBI->removeDestination(i);
4342 --i; --e;
4343 Changed = true;
4344 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004345 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004346
4347 if (IBI->getNumDestinations() == 0) {
4348 // If the indirectbr has no successors, change it to unreachable.
4349 new UnreachableInst(IBI->getContext(), IBI);
4350 EraseTerminatorInstAndDCECond(IBI);
4351 return true;
4352 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004353
Chris Lattner25c3af32010-12-13 06:25:44 +00004354 if (IBI->getNumDestinations() == 1) {
4355 // If the indirectbr has one successor, change it to a direct branch.
4356 BranchInst::Create(IBI->getDestination(0), IBI);
4357 EraseTerminatorInstAndDCECond(IBI);
4358 return true;
4359 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004360
Chris Lattner25c3af32010-12-13 06:25:44 +00004361 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4362 if (SimplifyIndirectBrOnSelect(IBI, SI))
Chandler Carruth66b31302015-01-04 12:03:27 +00004363 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004364 }
4365 return Changed;
4366}
4367
Devang Patel767f6932011-05-18 18:28:48 +00004368bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004369 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004370
Manman Ren93ab6492012-09-20 22:37:36 +00004371 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4372 return true;
4373
Chris Lattner25c3af32010-12-13 06:25:44 +00004374 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004375 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004376 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4377 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4378 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004379
Chris Lattner25c3af32010-12-13 06:25:44 +00004380 // If the only instruction in the block is a seteq/setne comparison
4381 // against a constant, try to simplify the block.
4382 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4383 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4384 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4385 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004386 if (I->isTerminator() &&
Jingyue Wufc029672014-09-30 22:23:38 +00004387 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004388 BonusInstThreshold, DL, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004389 return true;
4390 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004391
Manman Rend33f4ef2012-06-13 05:43:29 +00004392 // If this basic block is ONLY a compare and a branch, and if a predecessor
4393 // branches to us and our successor, fold the comparison into the
4394 // predecessor and use logical operations to update the incoming value
4395 // for PHI nodes in common successor.
Jingyue Wufc029672014-09-30 22:23:38 +00004396 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
Chandler Carruth66b31302015-01-04 12:03:27 +00004397 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004398 return false;
4399}
4400
4401
Devang Patela7ec47d2011-05-18 20:35:38 +00004402bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004403 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004404
Chris Lattner25c3af32010-12-13 06:25:44 +00004405 // Conditional branch
4406 if (isValueEqualityComparison(BI)) {
4407 // If we only have one predecessor, and if it is a branch on this value,
4408 // see if that predecessor totally determines the outcome of this
4409 // switch.
4410 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004411 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Chandler Carruth66b31302015-01-04 12:03:27 +00004412 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004413
Chris Lattner25c3af32010-12-13 06:25:44 +00004414 // This block must be empty, except for the setcond inst, if it exists.
4415 // Ignore dbg intrinsics.
4416 BasicBlock::iterator I = BB->begin();
4417 // Ignore dbg intrinsics.
4418 while (isa<DbgInfoIntrinsic>(I))
4419 ++I;
4420 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004421 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Chandler Carruth66b31302015-01-04 12:03:27 +00004422 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004423 } else if (&*I == cast<Instruction>(BI->getCondition())){
4424 ++I;
4425 // Ignore dbg intrinsics.
4426 while (isa<DbgInfoIntrinsic>(I))
4427 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004428 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Chandler Carruth66b31302015-01-04 12:03:27 +00004429 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004430 }
4431 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004432
Chris Lattner25c3af32010-12-13 06:25:44 +00004433 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004434 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004435 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004436
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004437 // If this basic block is ONLY a compare and a branch, and if a predecessor
4438 // branches to us and one of our successors, fold the comparison into the
4439 // predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00004440 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
Chandler Carruth66b31302015-01-04 12:03:27 +00004441 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004442
Chris Lattner25c3af32010-12-13 06:25:44 +00004443 // We have a conditional branch to two blocks that are only reachable
4444 // from BI. We know that the condbr dominates the two blocks, so see if
4445 // there is any identical code in the "then" and "else" blocks. If so, we
4446 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004447 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4448 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chad Rosier54390052015-02-23 19:15:16 +00004449 if (HoistThenElseCodeToIf(BI, DL, TTI))
Chandler Carruth66b31302015-01-04 12:03:27 +00004450 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004451 } else {
4452 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004453 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004454 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4455 if (Succ0TI->getNumSuccessors() == 1 &&
4456 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
James Molloy7c336572015-02-11 12:15:41 +00004457 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL, TTI))
Chandler Carruth66b31302015-01-04 12:03:27 +00004458 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004459 }
Craig Topperf40110f2014-04-25 05:29:35 +00004460 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004461 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004462 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004463 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4464 if (Succ1TI->getNumSuccessors() == 1 &&
4465 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
James Molloy7c336572015-02-11 12:15:41 +00004466 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL, TTI))
Chandler Carruth66b31302015-01-04 12:03:27 +00004467 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004468 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004469
Chris Lattner25c3af32010-12-13 06:25:44 +00004470 // If this is a branch on a phi node in the current block, thread control
4471 // through this block if any PHI node entries are constants.
4472 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4473 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004474 if (FoldCondBranchOnPHI(BI, DL))
Chandler Carruth66b31302015-01-04 12:03:27 +00004475 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004476
Chris Lattner25c3af32010-12-13 06:25:44 +00004477 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004478 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4479 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004480 if (PBI != BI && PBI->isConditional())
4481 if (SimplifyCondBranchToCondBranch(PBI, BI))
Chandler Carruth66b31302015-01-04 12:03:27 +00004482 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004483
4484 return false;
4485}
4486
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004487/// Check if passing a value to an instruction will cause undefined behavior.
4488static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4489 Constant *C = dyn_cast<Constant>(V);
4490 if (!C)
4491 return false;
4492
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004493 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004494 return false;
4495
4496 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004497 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004498 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004499
4500 // Now make sure that there are no instructions in between that can alter
4501 // control flow (eg. calls)
4502 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004503 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004504 return false;
4505
4506 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4507 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4508 if (GEP->getPointerOperand() == I)
4509 return passingValueIsAlwaysUndefined(V, GEP);
4510
4511 // Look through bitcasts.
4512 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4513 return passingValueIsAlwaysUndefined(V, BC);
4514
Benjamin Kramer0655b782011-08-26 02:25:55 +00004515 // Load from null is undefined.
4516 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004517 if (!LI->isVolatile())
4518 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004519
Benjamin Kramer0655b782011-08-26 02:25:55 +00004520 // Store to null is undefined.
4521 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004522 if (!SI->isVolatile())
4523 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004524 }
4525 return false;
4526}
4527
4528/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004529/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004530static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4531 for (BasicBlock::iterator i = BB->begin();
4532 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4533 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4534 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4535 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4536 IRBuilder<> Builder(T);
4537 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4538 BB->removePredecessor(PHI->getIncomingBlock(i));
4539 // Turn uncoditional branches into unreachables and remove the dead
4540 // destination from conditional branches.
4541 if (BI->isUnconditional())
4542 Builder.CreateUnreachable();
4543 else
4544 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4545 BI->getSuccessor(0));
4546 BI->eraseFromParent();
4547 return true;
4548 }
4549 // TODO: SwitchInst.
4550 }
4551
4552 return false;
4553}
4554
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004555bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004556 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004557
Chris Lattnerd7beca32010-12-14 06:17:25 +00004558 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004559 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004560
Dan Gohman4a63fad2010-08-14 00:29:42 +00004561 // Remove basic blocks that have no predecessors (except the entry block)...
4562 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00004563 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00004564 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004565 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004566 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004567 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004568 return true;
4569 }
4570
Chris Lattner031340a2003-08-17 19:41:53 +00004571 // Check to see if we can constant propagate this terminator instruction
4572 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004573 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004574
Dan Gohman1a951062009-10-30 22:39:04 +00004575 // Check for and eliminate duplicate PHI nodes in this block.
4576 Changed |= EliminateDuplicatePHINodes(BB);
4577
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004578 // Check for and remove branches that will always cause undefined behavior.
4579 Changed |= removeUndefIntroducingPredecessor(BB);
4580
Chris Lattner2e3832d2010-12-13 05:10:48 +00004581 // Merge basic blocks into their predecessor if there is only one distinct
4582 // pred, and if there is only one distinct successor of the predecessor, and
4583 // if there are no PHI nodes.
4584 //
4585 if (MergeBlockIntoPredecessor(BB))
4586 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004587
Devang Patel15ad6762011-05-18 18:01:27 +00004588 IRBuilder<> Builder(BB);
4589
Dan Gohman20af5a02008-03-11 21:53:06 +00004590 // If there is a trivial two-entry PHI node in this basic block, and we can
4591 // eliminate it, do so now.
4592 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4593 if (PN->getNumIncomingValues() == 2)
James Molloy7c336572015-02-11 12:15:41 +00004594 Changed |= FoldTwoEntryPHINode(PN, DL, TTI);
Dan Gohman20af5a02008-03-11 21:53:06 +00004595
Devang Patela7ec47d2011-05-18 20:35:38 +00004596 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004597 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004598 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004599 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004600 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004601 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004602 }
4603 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004604 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004605 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4606 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004607 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004608 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004609 } else if (UnreachableInst *UI =
4610 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4611 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004612 } else if (IndirectBrInst *IBI =
4613 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4614 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004615 }
4616
Chris Lattner031340a2003-08-17 19:41:53 +00004617 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004618}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004619
4620/// SimplifyCFG - This function is used to do simplification of a CFG. For
4621/// example, it adjusts branches to branches to eliminate the extra hop, it
4622/// eliminates unreachable basic blocks, and does other "peephole" optimization
4623/// of the CFG. It returns true if a modification was made.
4624///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004625bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004626 unsigned BonusInstThreshold, const DataLayout *DL,
4627 AssumptionCache *AC) {
4628 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004629}