blob: 3bb3fa5a301f2c117675495c52c894f8df37dd44 [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"
James Molloy4de84dd2015-11-04 15:28:04 +000017#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000022#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000028#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000040#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000042#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000044#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Jingyue Wufc029672014-09-30 22:23:38 +000048#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000049#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000050#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000052using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000053using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "simplifycfg"
56
James Molloy1b6207e2015-02-13 10:48:30 +000057// Chosen as 2 so as to be cheap, but still to have enough power to fold
58// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59// To catch this, we need to fold a compare and a select, hence '2' being the
60// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000061static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000062PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000064
Evan Chengd983eba2011-01-29 04:46:23 +000065static cl::opt<bool>
66DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
68
Manman Ren93ab6492012-09-20 22:37:36 +000069static cl::opt<bool>
70SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
72
Alp Tokercb402912014-01-24 17:20:08 +000073static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000076
James Molloy4de84dd2015-11-04 15:28:04 +000077static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
81 "predicated store"));
82
83static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
87
Sanjay Patel38a02262015-12-15 17:38:29 +000088static cl::opt<bool> SpeculateOneExpensiveInst(
89 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
90 cl::desc("Allow exactly one expensive instruction to be speculatively "
91 "executed"));
92
Hans Wennborg39583b82012-09-26 09:44:49 +000093STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000094STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000095STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000096STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000097STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000098STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000099STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000100
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000101namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000102 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +0000103 // case group is selected, and the second field is a vector containing the
104 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000105 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
106 SwitchCaseResultVectorTy;
107 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000108 // and the second field contains the value generated for a certain case in the
109 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000110 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
111
Eric Christopherb65acc62012-07-02 23:22:21 +0000112 /// ValueEqualityComparisonCase - Represents a case of a switch.
113 struct ValueEqualityComparisonCase {
114 ConstantInt *Value;
115 BasicBlock *Dest;
116
117 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
118 : Value(Value), Dest(Dest) {}
119
120 bool operator<(ValueEqualityComparisonCase RHS) const {
121 // Comparing pointers is ok as we only rely on the order for uniquing.
122 return Value < RHS.Value;
123 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000124
125 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000126 };
127
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000128class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000129 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000131 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000132 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133 Value *isValueEqualityComparison(TerminatorInst *TI);
134 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000135 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000136 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000137 BasicBlock *Pred,
138 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000139 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
140 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000141
Devang Pateldd14e0f2011-05-18 21:33:11 +0000142 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000143 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000144 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000145 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000146 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000147 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000148 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000149 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000150
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000151public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000152 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
153 unsigned BonusInstThreshold, AssumptionCache *AC)
154 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000155 bool run(BasicBlock *BB);
156};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000157}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000158
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000159/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000160/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000161static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
162 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000163
Chris Lattner76dc2042005-08-03 00:19:45 +0000164 // It is not safe to merge these two switch instructions if they have a common
165 // successor, and if that successor has a PHI node, and if *that* PHI node has
166 // conflicting incoming values from the two switch blocks.
167 BasicBlock *SI1BB = SI1->getParent();
168 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000169 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000170
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000171 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
172 if (SI1Succs.count(*I))
173 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000174 isa<PHINode>(BBI); ++BBI) {
175 PHINode *PN = cast<PHINode>(BBI);
176 if (PN->getIncomingValueForBlock(SI1BB) !=
177 PN->getIncomingValueForBlock(SI2BB))
178 return false;
179 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000180
Chris Lattner76dc2042005-08-03 00:19:45 +0000181 return true;
182}
183
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000184/// Return true if it is safe and profitable to merge these two terminator
185/// instructions together, where SI1 is an unconditional branch. PhiNodes will
186/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000187static bool isProfitableToFoldUnconditional(BranchInst *SI1,
188 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000189 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000190 SmallVectorImpl<PHINode*> &PhiNodes) {
191 if (SI1 == SI2) return false; // Can't merge with self!
192 assert(SI1->isUnconditional() && SI2->isConditional());
193
194 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000195 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000196 // 1> We have a constant incoming value for the conditional branch;
197 // 2> We have "Cond" as the incoming value for the unconditional branch;
198 // 3> SI2->getCondition() and Cond have same operands.
199 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
200 if (!Ci2) return false;
201 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
202 Cond->getOperand(1) == Ci2->getOperand(1)) &&
203 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
204 Cond->getOperand(1) == Ci2->getOperand(0)))
205 return false;
206
207 BasicBlock *SI1BB = SI1->getParent();
208 BasicBlock *SI2BB = SI2->getParent();
209 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000210 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
211 if (SI1Succs.count(*I))
212 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000213 isa<PHINode>(BBI); ++BBI) {
214 PHINode *PN = cast<PHINode>(BBI);
215 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000216 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000217 return false;
218 PhiNodes.push_back(PN);
219 }
220 return true;
221}
222
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000223/// Update PHI nodes in Succ to indicate that there will now be entries in it
224/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
225/// will be the same as those coming in from ExistPred, an existing predecessor
226/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000227static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
228 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000229 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000230
Chris Lattner80b03a12008-07-13 22:23:11 +0000231 PHINode *PN;
232 for (BasicBlock::iterator I = Succ->begin();
233 (PN = dyn_cast<PHINode>(I)); ++I)
234 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000235}
236
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000237/// Compute an abstract "cost" of speculating the given instruction,
238/// which is assumed to be safe to speculate. TCC_Free means cheap,
239/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000240/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000241static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000242 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000243 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000244 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000245 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000246}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000247
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000248/// If we have a merge point of an "if condition" as accepted above,
249/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000250/// don't handle the true generality of domination here, just a special case
251/// which works well enough for us.
252///
253/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000254/// see if V (which must be an instruction) and its recursive operands
255/// that do not dominate BB have a combined cost lower than CostRemaining and
256/// are non-trapping. If both are true, the instruction is inserted into the
257/// set and true is returned.
258///
259/// The cost for most non-trapping instructions is defined as 1 except for
260/// Select whose cost is 2.
261///
262/// After this function returns, CostRemaining is decreased by the cost of
263/// V plus its non-dominating operands. If that cost is greater than
264/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000265static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000266 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000267 unsigned &CostRemaining,
Sanjay Patel38a02262015-12-15 17:38:29 +0000268 const TargetTransformInfo &TTI,
269 unsigned Depth = 0) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000270 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000271 if (!I) {
272 // Non-instructions all dominate instructions, but not all constantexprs
273 // can be executed unconditionally.
274 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
275 if (C->canTrap())
276 return false;
277 return true;
278 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000279 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000280
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000281 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000282 // the bottom of this block.
283 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000284
Chris Lattner0aa56562004-04-09 22:50:22 +0000285 // If this instruction is defined in a block that contains an unconditional
286 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000287 // statement". If not, it definitely dominates the region.
288 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000289 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000290 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000291
Chris Lattner9ac168d2010-12-14 07:41:39 +0000292 // If we aren't allowing aggressive promotion anymore, then don't consider
293 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000294 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000295
Peter Collingbournee3511e12011-04-29 18:47:31 +0000296 // If we have seen this instruction before, don't count it again.
297 if (AggressiveInsts->count(I)) return true;
298
Chris Lattner9ac168d2010-12-14 07:41:39 +0000299 // Okay, it looks like the instruction IS in the "condition". Check to
300 // see if it's a cheap instruction to unconditionally compute, and if it
301 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000302 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000303 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000304
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000305 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000306
Sanjay Patel38a02262015-12-15 17:38:29 +0000307 // Allow exactly one instruction to be speculated regardless of its cost
308 // (as long as it is safe to do so).
309 // This is intended to flatten the CFG even if the instruction is a division
310 // or other expensive operation. The speculation of an expensive instruction
311 // is expected to be undone in CodeGenPrepare if the speculation has not
312 // enabled further IR optimizations.
313 if (Cost > CostRemaining &&
314 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000315 return false;
316
Sanjay Patel38a02262015-12-15 17:38:29 +0000317 // Avoid unsigned wrap.
318 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000319
320 // Okay, we can only really hoist these out if their operands do
321 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000322 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Sanjay Patel38a02262015-12-15 17:38:29 +0000323 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
324 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000325 return false;
326 // Okay, it's safe to do this! Remember this instruction.
327 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000328 return true;
329}
Chris Lattner466a0492002-05-21 20:50:24 +0000330
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000331/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000332/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000333static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000334 // Normal constant int.
335 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000336 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000337 return CI;
338
339 // This is some kind of pointer constant. Turn it into a pointer-sized
340 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000341 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000342
343 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
344 if (isa<ConstantPointerNull>(V))
345 return ConstantInt::get(PtrTy, 0);
346
347 // IntToPtr const int.
348 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
349 if (CE->getOpcode() == Instruction::IntToPtr)
350 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
351 // The constant is very likely to have the right type already.
352 if (CI->getType() == PtrTy)
353 return CI;
354 else
355 return cast<ConstantInt>
356 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
357 }
Craig Topperf40110f2014-04-25 05:29:35 +0000358 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000359}
360
Mehdi Aminiffd01002014-11-20 22:40:25 +0000361namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000362
Mehdi Aminiffd01002014-11-20 22:40:25 +0000363/// Given a chain of or (||) or and (&&) comparison of a value against a
364/// constant, this will try to recover the information required for a switch
365/// structure.
366/// It will depth-first traverse the chain of comparison, seeking for patterns
367/// like %a == 12 or %a < 4 and combine them to produce a set of integer
368/// representing the different cases for the switch.
369/// Note that if the chain is composed of '||' it will build the set of elements
370/// that matches the comparisons (i.e. any of this value validate the chain)
371/// while for a chain of '&&' it will build the set elements that make the test
372/// fail.
373struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000374 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000375 Value *CompValue; /// Value found for the switch comparison
376 Value *Extra; /// Extra clause to be checked before the switch
377 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
378 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000379
Mehdi Aminiffd01002014-11-20 22:40:25 +0000380 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000381 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
382 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
383 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000384 }
385
Mehdi Aminiffd01002014-11-20 22:40:25 +0000386 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000387 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000388 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000389 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000390
Mehdi Aminiffd01002014-11-20 22:40:25 +0000391private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000392
Mehdi Aminiffd01002014-11-20 22:40:25 +0000393 /// Try to set the current value used for the comparison, it succeeds only if
394 /// it wasn't set before or if the new value is the same as the old one
395 bool setValueOnce(Value *NewVal) {
396 if(CompValue && CompValue != NewVal) return false;
397 CompValue = NewVal;
398 return (CompValue != nullptr);
399 }
400
401 /// Try to match Instruction "I" as a comparison against a constant and
402 /// populates the array Vals with the set of values that match (or do not
403 /// match depending on isEQ).
404 /// Return false on failure. On success, the Value the comparison matched
405 /// against is placed in CompValue.
406 /// If CompValue is already set, the function is expected to fail if a match
407 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000409 // If this is an icmp against a constant, handle this as one of the cases.
410 ICmpInst *ICI;
411 ConstantInt *C;
412 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
413 (C = GetConstantInt(I->getOperand(1), DL)))) {
414 return false;
415 }
416
417 Value *RHSVal;
418 ConstantInt *RHSC;
419
420 // Pattern match a special case
421 // (x & ~2^x) == y --> x == y || x == y|2^x
422 // This undoes a transformation done by instcombine to fuse 2 compares.
423 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
424 if (match(ICI->getOperand(0),
425 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
426 APInt Not = ~RHSC->getValue();
427 if (Not.isPowerOf2()) {
428 // If we already have a value for the switch, it has to match!
429 if(!setValueOnce(RHSVal))
430 return false;
431
432 Vals.push_back(C);
433 Vals.push_back(ConstantInt::get(C->getContext(),
434 C->getValue() | Not));
435 UsedICmps++;
436 return true;
437 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000438 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000439
440 // If we already have a value for the switch, it has to match!
441 if(!setValueOnce(ICI->getOperand(0)))
442 return false;
443
444 UsedICmps++;
445 Vals.push_back(C);
446 return ICI->getOperand(0);
447 }
448
449 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
Sanjoy Das7182d362015-03-18 00:41:24 +0000450 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
451 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000452
453 // Shift the range if the compare is fed by an add. This is the range
454 // compare idiom as emitted by instcombine.
455 Value *CandidateVal = I->getOperand(0);
456 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
457 Span = Span.subtract(RHSC->getValue());
458 CandidateVal = RHSVal;
459 }
460
461 // If this is an and/!= check, then we are looking to build the set of
462 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
463 // x != 0 && x != 1.
464 if (!isEQ)
465 Span = Span.inverse();
466
467 // If there are a ton of values, we don't want to make a ginormous switch.
468 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
469 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000470 }
471
472 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000473 if(!setValueOnce(CandidateVal))
474 return false;
475
476 // Add all values from the range to the set
477 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
478 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000479
480 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000481 return true;
482
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000483 }
484
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000485 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000486 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
487 /// the value being compared, and stick the list constants into the Vals
488 /// vector.
489 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000491 Instruction *I = dyn_cast<Instruction>(V);
492 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000493
Mehdi Aminiffd01002014-11-20 22:40:25 +0000494 // Keep a stack (SmallVector for efficiency) for depth-first traversal
495 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000496
Mehdi Aminiffd01002014-11-20 22:40:25 +0000497 // Initialize
498 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000499
Mehdi Aminiffd01002014-11-20 22:40:25 +0000500 while(!DFT.empty()) {
501 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000502
Mehdi Aminiffd01002014-11-20 22:40:25 +0000503 if (Instruction *I = dyn_cast<Instruction>(V)) {
504 // If it is a || (or && depending on isEQ), process the operands.
505 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
506 DFT.push_back(I->getOperand(1));
507 DFT.push_back(I->getOperand(0));
508 continue;
509 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000510
Mehdi Aminiffd01002014-11-20 22:40:25 +0000511 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000512 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000513 // Match succeed, continue the loop
514 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000515 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000516
Mehdi Aminiffd01002014-11-20 22:40:25 +0000517 // One element of the sequence of || (or &&) could not be match as a
518 // comparison against the same value as the others.
519 // We allow only one "Extra" case to be checked before the switch
520 if (!Extra) {
521 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000522 continue;
523 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000524 // Failed to parse a proper sequence, abort now
525 CompValue = nullptr;
526 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000527 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000528 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000529};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000530
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000531}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000532
Eli Friedmancb61afb2008-12-16 20:54:32 +0000533static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000534 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000535 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
536 Cond = dyn_cast<Instruction>(SI->getCondition());
537 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
538 if (BI->isConditional())
539 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000540 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
541 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000542 }
543
544 TI->eraseFromParent();
545 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
546}
547
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000548/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000549/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000550Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000551 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000552 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
553 // Do not permit merging of large switch instructions into their
554 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000555 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
556 pred_end(SI->getParent())) <= 128)
557 CV = SI->getCondition();
558 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000559 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000560 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000561 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000562 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000563 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000564
565 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000566 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000567 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
568 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000569 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000570 CV = Ptr;
571 }
572 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000573 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000574}
575
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000576/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000577/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000578BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000579GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000580 std::vector<ValueEqualityComparisonCase>
581 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000582 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000583 Cases.reserve(SI->getNumCases());
584 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
585 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
586 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000587 return SI->getDefaultDest();
588 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000589
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000590 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000591 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000592 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
593 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000594 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000595 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000596 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000597}
598
Eric Christopherb65acc62012-07-02 23:22:21 +0000599
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000600/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000601/// in the list that match the specified block.
602static void EliminateBlockCases(BasicBlock *BB,
603 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000604 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000605}
606
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000607/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000608static bool
609ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
610 std::vector<ValueEqualityComparisonCase > &C2) {
611 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
612
613 // Make V1 be smaller than V2.
614 if (V1->size() > V2->size())
615 std::swap(V1, V2);
616
617 if (V1->size() == 0) return false;
618 if (V1->size() == 1) {
619 // Just scan V2.
620 ConstantInt *TheVal = (*V1)[0].Value;
621 for (unsigned i = 0, e = V2->size(); i != e; ++i)
622 if (TheVal == (*V2)[i].Value)
623 return true;
624 }
625
626 // Otherwise, just sort both lists and compare element by element.
627 array_pod_sort(V1->begin(), V1->end());
628 array_pod_sort(V2->begin(), V2->end());
629 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
630 while (i1 != e1 && i2 != e2) {
631 if ((*V1)[i1].Value == (*V2)[i2].Value)
632 return true;
633 if ((*V1)[i1].Value < (*V2)[i2].Value)
634 ++i1;
635 else
636 ++i2;
637 }
638 return false;
639}
640
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000641/// If TI is known to be a terminator instruction and its block is known to
642/// only have a single predecessor block, check to see if that predecessor is
643/// also a value comparison with the same value, and if that comparison
644/// determines the outcome of this comparison. If so, simplify TI. This does a
645/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000646bool SimplifyCFGOpt::
647SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000648 BasicBlock *Pred,
649 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000650 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
651 if (!PredVal) return false; // Not a value comparison in predecessor.
652
653 Value *ThisVal = isValueEqualityComparison(TI);
654 assert(ThisVal && "This isn't a value comparison!!");
655 if (ThisVal != PredVal) return false; // Different predicates.
656
Andrew Trick3051aa12012-08-29 21:46:38 +0000657 // TODO: Preserve branch weight metadata, similarly to how
658 // FoldValueComparisonIntoPredecessors preserves it.
659
Chris Lattner1cca9592005-02-24 06:17:52 +0000660 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000661 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000662 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
663 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000664 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000665
Chris Lattner1cca9592005-02-24 06:17:52 +0000666 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000667 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000668 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000669 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000670
671 // If TI's block is the default block from Pred's comparison, potentially
672 // simplify TI based on this knowledge.
673 if (PredDef == TI->getParent()) {
674 // If we are here, we know that the value is none of those cases listed in
675 // PredCases. If there are any cases in ThisCases that are in PredCases, we
676 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000677 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000678 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000679
Chris Lattner4088e2b2010-12-13 01:47:07 +0000680 if (isa<BranchInst>(TI)) {
681 // Okay, one of the successors of this condbr is dead. Convert it to a
682 // uncond br.
683 assert(ThisCases.size() == 1 && "Branch can only have one case!");
684 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000685 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000686 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000687
Chris Lattner4088e2b2010-12-13 01:47:07 +0000688 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000689 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000690
Chris Lattner4088e2b2010-12-13 01:47:07 +0000691 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
692 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000693
Chris Lattner4088e2b2010-12-13 01:47:07 +0000694 EraseTerminatorInstAndDCECond(TI);
695 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000696 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000697
Chris Lattner4088e2b2010-12-13 01:47:07 +0000698 SwitchInst *SI = cast<SwitchInst>(TI);
699 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000700 SmallPtrSet<Constant*, 16> DeadCases;
701 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
702 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000703
David Greene725c7c32010-01-05 01:26:52 +0000704 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000705 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000706
Manman Ren8691e522012-09-14 21:53:06 +0000707 // Collect branch weights into a vector.
708 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000709 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000710 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
711 if (HasWeight)
712 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
713 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000714 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000715 Weights.push_back(CI->getValue().getZExtValue());
716 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000717 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
718 --i;
719 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000720 if (HasWeight) {
721 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
722 Weights.pop_back();
723 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000724 i.getCaseSuccessor()->removePredecessor(TI->getParent());
725 SI->removeCase(i);
726 }
727 }
Manman Ren97c18762012-10-11 22:28:34 +0000728 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000729 SI->setMetadata(LLVMContext::MD_prof,
730 MDBuilder(SI->getParent()->getContext()).
731 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000732
733 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000734 return true;
735 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000736
Chris Lattner4088e2b2010-12-13 01:47:07 +0000737 // Otherwise, TI's block must correspond to some matched value. Find out
738 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000739 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000740 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000741 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
742 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000743 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000744 return false; // Cannot handle multiple values coming to this block.
745 TIV = PredCases[i].Value;
746 }
747 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000748
749 // Okay, we found the one constant that our value can be if we get into TI's
750 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000751 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000752 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
753 if (ThisCases[i].Value == TIV) {
754 TheRealDest = ThisCases[i].Dest;
755 break;
756 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000757
758 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000759 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000760
761 // Remove PHI node entries for dead edges.
762 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000763 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
764 if (*SI != CheckEdge)
765 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000766 else
Craig Topperf40110f2014-04-25 05:29:35 +0000767 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000768
769 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000770 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000771 (void) NI;
772
773 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
774 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
775
776 EraseTerminatorInstAndDCECond(TI);
777 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000778}
779
Dale Johannesen7f99d222009-03-12 21:01:11 +0000780namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000781 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000782 /// integers that does not depend on their address. This is important for
783 /// applications that sort ConstantInt's to ensure uniqueness.
784 struct ConstantIntOrdering {
785 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
786 return LHS->getValue().ult(RHS->getValue());
787 }
788 };
789}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000790
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000791static int ConstantIntSortPredicate(ConstantInt *const *P1,
792 ConstantInt *const *P2) {
793 const ConstantInt *LHS = *P1;
794 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000795 if (LHS->getValue().ult(RHS->getValue()))
796 return 1;
797 if (LHS->getValue() == RHS->getValue())
798 return 0;
799 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000800}
801
Andrew Trick3051aa12012-08-29 21:46:38 +0000802static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000803 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000804 if (ProfMD && ProfMD->getOperand(0))
805 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
806 return MDS->getString().equals("branch_weights");
807
808 return false;
809}
810
Manman Ren571d9e42012-09-11 17:43:35 +0000811/// Get Weights of a given TerminatorInst, the default weight is at the front
812/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
813/// metadata.
814static void GetBranchWeights(TerminatorInst *TI,
815 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000816 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000817 assert(MD);
818 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000819 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000820 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000821 }
822
Manman Ren571d9e42012-09-11 17:43:35 +0000823 // If TI is a conditional eq, the default case is the false case,
824 // and the corresponding branch-weight data is at index 2. We swap the
825 // default weight to be the first entry.
826 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
827 assert(Weights.size() == 2);
828 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
829 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
830 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000831 }
832}
833
Manman Renf1cb16e2014-01-27 23:39:03 +0000834/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000835static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000836 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
837 if (Max > UINT_MAX) {
838 unsigned Offset = 32 - countLeadingZeros(Max);
839 for (uint64_t &I : Weights)
840 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000841 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000842}
843
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000844/// The specified terminator is a value equality comparison instruction
845/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000846/// See if any of the predecessors of the terminator block are value comparisons
847/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000848bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
849 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000850 BasicBlock *BB = TI->getParent();
851 Value *CV = isValueEqualityComparison(TI); // CondVal
852 assert(CV && "Not a comparison?");
853 bool Changed = false;
854
Chris Lattner6b39cb92008-02-18 07:42:56 +0000855 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000856 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000857 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000858
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000859 // See if the predecessor is a comparison with the same value.
860 TerminatorInst *PTI = Pred->getTerminator();
861 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
862
863 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
864 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000865 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000866 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
867
Eric Christopherb65acc62012-07-02 23:22:21 +0000868 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000869 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
870
871 // Based on whether the default edge from PTI goes to BB or not, fill in
872 // PredCases and PredDefault with the new switch cases we would like to
873 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000874 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000875
Andrew Trick3051aa12012-08-29 21:46:38 +0000876 // Update the branch weight metadata along the way
877 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000878 bool PredHasWeights = HasBranchWeights(PTI);
879 bool SuccHasWeights = HasBranchWeights(TI);
880
Manman Ren5e5049d2012-09-14 19:05:19 +0000881 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000882 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000883 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000884 if (Weights.size() != 1 + PredCases.size())
885 PredHasWeights = SuccHasWeights = false;
886 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000887 // If there are no predecessor weights but there are successor weights,
888 // populate Weights with 1, which will later be scaled to the sum of
889 // successor's weights
890 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000891
Manman Ren571d9e42012-09-11 17:43:35 +0000892 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000893 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000894 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000895 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000896 if (SuccWeights.size() != 1 + BBCases.size())
897 PredHasWeights = SuccHasWeights = false;
898 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000899 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000900
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000901 if (PredDefault == BB) {
902 // If this is the default destination from PTI, only the edges in TI
903 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000904 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
905 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
906 if (PredCases[i].Dest != BB)
907 PTIHandled.insert(PredCases[i].Value);
908 else {
909 // The default destination is BB, we don't need explicit targets.
910 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000911
Manman Ren571d9e42012-09-11 17:43:35 +0000912 if (PredHasWeights || SuccHasWeights) {
913 // Increase weight for the default case.
914 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000915 std::swap(Weights[i+1], Weights.back());
916 Weights.pop_back();
917 }
918
Eric Christopherb65acc62012-07-02 23:22:21 +0000919 PredCases.pop_back();
920 --i; --e;
921 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000922
Eric Christopherb65acc62012-07-02 23:22:21 +0000923 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000924 if (PredDefault != BBDefault) {
925 PredDefault->removePredecessor(Pred);
926 PredDefault = BBDefault;
927 NewSuccessors.push_back(BBDefault);
928 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000929
Manman Ren571d9e42012-09-11 17:43:35 +0000930 unsigned CasesFromPred = Weights.size();
931 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000932 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
933 if (!PTIHandled.count(BBCases[i].Value) &&
934 BBCases[i].Dest != BBDefault) {
935 PredCases.push_back(BBCases[i]);
936 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000937 if (SuccHasWeights || PredHasWeights) {
938 // The default weight is at index 0, so weight for the ith case
939 // should be at index i+1. Scale the cases from successor by
940 // PredDefaultWeight (Weights[0]).
941 Weights.push_back(Weights[0] * SuccWeights[i+1]);
942 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000943 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000944 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000945
Manman Ren571d9e42012-09-11 17:43:35 +0000946 if (SuccHasWeights || PredHasWeights) {
947 ValidTotalSuccWeight += SuccWeights[0];
948 // Scale the cases from predecessor by ValidTotalSuccWeight.
949 for (unsigned i = 1; i < CasesFromPred; ++i)
950 Weights[i] *= ValidTotalSuccWeight;
951 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
952 Weights[0] *= SuccWeights[0];
953 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000954 } else {
955 // If this is not the default destination from PSI, only the edges
956 // in SI that occur in PSI with a destination of BB will be
957 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000958 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000959 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000960 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
961 if (PredCases[i].Dest == BB) {
962 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000963
964 if (PredHasWeights || SuccHasWeights) {
965 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
966 std::swap(Weights[i+1], Weights.back());
967 Weights.pop_back();
968 }
969
Eric Christopherb65acc62012-07-02 23:22:21 +0000970 std::swap(PredCases[i], PredCases.back());
971 PredCases.pop_back();
972 --i; --e;
973 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000974
975 // Okay, now we know which constants were sent to BB from the
976 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000977 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
978 if (PTIHandled.count(BBCases[i].Value)) {
979 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000980 if (PredHasWeights || SuccHasWeights)
981 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000982 PredCases.push_back(BBCases[i]);
983 NewSuccessors.push_back(BBCases[i].Dest);
984 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
985 }
986
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000987 // If there are any constants vectored to BB that TI doesn't handle,
988 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000989 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000990 PTIHandled.begin(),
991 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000992 if (PredHasWeights || SuccHasWeights)
993 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000994 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000995 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000996 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000997 }
998
999 // Okay, at this point, we know which new successor Pred will get. Make
1000 // sure we update the number of entries in the PHI nodes for these
1001 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001002 for (BasicBlock *NewSuccessor : NewSuccessors)
1003 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001004
Devang Patel58380552011-05-18 20:53:17 +00001005 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001006 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001007 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001008 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001009 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001010 }
1011
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001012 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +00001013 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1014 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001015 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001016 for (ValueEqualityComparisonCase &V : PredCases)
1017 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001018
Andrew Trick3051aa12012-08-29 21:46:38 +00001019 if (PredHasWeights || SuccHasWeights) {
1020 // Halve the weights if any of them cannot fit in an uint32_t
1021 FitWeights(Weights);
1022
1023 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1024
1025 NewSI->setMetadata(LLVMContext::MD_prof,
1026 MDBuilder(BB->getContext()).
1027 createBranchWeights(MDWeights));
1028 }
1029
Eli Friedmancb61afb2008-12-16 20:54:32 +00001030 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001031
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001032 // Okay, last check. If BB is still a successor of PSI, then we must
1033 // have an infinite loop case. If so, add an infinitely looping block
1034 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001035 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001036 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1037 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001038 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001039 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001040 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001041 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1042 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001043 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001044 }
1045 NewSI->setSuccessor(i, InfLoopBlock);
1046 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001047
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001048 Changed = true;
1049 }
1050 }
1051 return Changed;
1052}
1053
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001054// If we would need to insert a select that uses the value of this invoke
1055// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1056// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001057static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1058 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001059 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001060 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001061 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001062 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1063 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1064 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1065 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1066 return false;
1067 }
1068 }
1069 }
1070 return true;
1071}
1072
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001073static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1074
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001075/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1076/// in the two blocks up into the branch block. The caller of this function
1077/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001078static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001079 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001080 // This does very trivial matching, with limited scanning, to find identical
1081 // instructions in the two blocks. In particular, we don't want to get into
1082 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1083 // such, we currently just scan for obviously identical instructions in an
1084 // identical order.
1085 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1086 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1087
Devang Patelf10e2872009-02-04 00:03:08 +00001088 BasicBlock::iterator BB1_Itr = BB1->begin();
1089 BasicBlock::iterator BB2_Itr = BB2->begin();
1090
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001091 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001092 // Skip debug info if it is not identical.
1093 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1094 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1095 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1096 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001097 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001098 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001099 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001100 }
Devang Patele48ddf82011-04-07 00:30:15 +00001101 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001102 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001103 return false;
1104
Chris Lattner389cfac2004-11-30 00:29:14 +00001105 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001106
David Majnemerc82f27a2013-06-03 20:43:12 +00001107 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001108 do {
1109 // If we are hoisting the terminator instruction, don't move one (making a
1110 // broken BB), instead clone it, and remove BI.
1111 if (isa<TerminatorInst>(I1))
1112 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001113
Chad Rosier54390052015-02-23 19:15:16 +00001114 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1115 return Changed;
1116
Chris Lattner389cfac2004-11-30 00:29:14 +00001117 // For a normal instruction, we just move one to right before the branch,
1118 // then replace all uses of the other with the first. Finally, we remove
1119 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001120 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001121 if (!I2->use_empty())
1122 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001123 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001124 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001125 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1126 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001127 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1128 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1129 LLVMContext::MD_dereferenceable_or_null};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001130 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001131 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001132 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001133
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001134 I1 = &*BB1_Itr++;
1135 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001136 // Skip debug info if it is not identical.
1137 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1138 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1139 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1140 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001141 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001142 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001143 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001144 }
Devang Patele48ddf82011-04-07 00:30:15 +00001145 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001146
1147 return true;
1148
1149HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001150 // It may not be possible to hoist an invoke.
1151 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001152 return Changed;
1153
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001154 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001155 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001156 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001157 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1158 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1159 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1160 if (BB1V == BB2V)
1161 continue;
1162
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001163 // Check for passingValueIsAlwaysUndefined here because we would rather
1164 // eliminate undefined control flow then converting it to a select.
1165 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1166 passingValueIsAlwaysUndefined(BB2V, PN))
1167 return Changed;
1168
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001170 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001171 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001172 return Changed;
1173 }
1174 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001175
Chris Lattner389cfac2004-11-30 00:29:14 +00001176 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001177 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001178 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001179 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001180 I1->replaceAllUsesWith(NT);
1181 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001182 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001183 }
1184
Devang Patel1407fb42011-05-19 20:52:46 +00001185 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001186 // Hoisting one of the terminators from our successor is a great thing.
1187 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1188 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1189 // nodes, so we insert select instruction to compute the final result.
1190 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001191 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001192 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001193 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001194 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001195 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1196 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001197 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001198
Chris Lattner4088e2b2010-12-13 01:47:07 +00001199 // These values do not agree. Insert a select instruction before NT
1200 // that determines the right value.
1201 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001202 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001203 SI = cast<SelectInst>
1204 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1205 BB1V->getName()+"."+BB2V->getName()));
1206
Chris Lattner4088e2b2010-12-13 01:47:07 +00001207 // Make the PHI node use the select for all incoming values for BB1/BB2
1208 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1209 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1210 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001211 }
1212 }
1213
1214 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001215 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1216 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001217
Eli Friedmancb61afb2008-12-16 20:54:32 +00001218 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001219 return true;
1220}
1221
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001222/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001223/// check whether BBEnd has only two predecessors and the other predecessor
1224/// ends with an unconditional branch. If it is true, sink any common code
1225/// in the two predecessors to BBEnd.
1226static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1227 assert(BI1->isUnconditional());
1228 BasicBlock *BB1 = BI1->getParent();
1229 BasicBlock *BBEnd = BI1->getSuccessor(0);
1230
1231 // Check that BBEnd has two predecessors and the other predecessor ends with
1232 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001233 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1234 BasicBlock *Pred0 = *PI++;
1235 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001236 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001237 BasicBlock *Pred1 = *PI++;
1238 if (PI != PE) // More than two predecessors.
1239 return false;
1240 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001241 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1242 if (!BI2 || !BI2->isUnconditional())
1243 return false;
1244
1245 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001246 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001247 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001248 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001249 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1250 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001251 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001252 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001253 } else {
1254 FirstNonPhiInBBEnd = &*I;
1255 break;
1256 }
1257 }
1258 if (!FirstNonPhiInBBEnd)
1259 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001260
Manman Ren93ab6492012-09-20 22:37:36 +00001261 // This does very trivial matching, with limited scanning, to find identical
1262 // instructions in the two blocks. We scan backward for obviously identical
1263 // instructions in an identical order.
1264 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001265 RE1 = BB1->getInstList().rend(),
1266 RI2 = BB2->getInstList().rbegin(),
1267 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001268 // Skip debug info.
1269 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1270 if (RI1 == RE1)
1271 return false;
1272 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1273 if (RI2 == RE2)
1274 return false;
1275 // Skip the unconditional branches.
1276 ++RI1;
1277 ++RI2;
1278
1279 bool Changed = false;
1280 while (RI1 != RE1 && RI2 != RE2) {
1281 // Skip debug info.
1282 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1283 if (RI1 == RE1)
1284 return Changed;
1285 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1286 if (RI2 == RE2)
1287 return Changed;
1288
1289 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001290 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001291 // I1 and I2 should have a single use in the same PHI node, and they
1292 // perform the same operation.
1293 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1294 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1295 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001296 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001297 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1298 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1299 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1300 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001301 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001302 return Changed;
1303
1304 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001305 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001306 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1307 bool SwapOpnds = false;
1308 if (ICmp1 && ICmp2 &&
1309 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1310 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1311 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1312 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1313 ICmp2->swapOperands();
1314 SwapOpnds = true;
1315 }
1316 if (!I1->isSameOperationAs(I2)) {
1317 if (SwapOpnds)
1318 ICmp2->swapOperands();
1319 return Changed;
1320 }
1321
1322 // The operands should be either the same or they need to be generated
1323 // with a PHI node after sinking. We only handle the case where there is
1324 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001325 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001326 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001327 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1328 if (I1->getOperand(I) == I2->getOperand(I))
1329 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001330 // Early exit if we have more-than one pair of different operands or if
1331 // we need a PHI node to replace a constant.
1332 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001333 isa<Constant>(I1->getOperand(I)) ||
1334 isa<Constant>(I2->getOperand(I))) {
1335 // If we can't sink the instructions, undo the swapping.
1336 if (SwapOpnds)
1337 ICmp2->swapOperands();
1338 return Changed;
1339 }
1340 DifferentOp1 = I1->getOperand(I);
1341 Op1Idx = I;
1342 DifferentOp2 = I2->getOperand(I);
1343 }
1344
Michael Liao5313da32014-12-23 08:26:55 +00001345 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1346 DEBUG(dbgs() << " " << *I2 << "\n");
1347
1348 // We insert the pair of different operands to JointValueMap and
1349 // remove (I1, I2) from JointValueMap.
1350 if (Op1Idx != ~0U) {
1351 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1352 if (!NewPN) {
1353 NewPN =
1354 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001355 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001356 NewPN->addIncoming(DifferentOp1, BB1);
1357 NewPN->addIncoming(DifferentOp2, BB2);
1358 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1359 }
Manman Ren93ab6492012-09-20 22:37:36 +00001360 // I1 should use NewPN instead of DifferentOp1.
1361 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001362 }
Michael Liao5313da32014-12-23 08:26:55 +00001363 PHINode *OldPN = JointValueMap[InstPair];
1364 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001365
Manman Ren93ab6492012-09-20 22:37:36 +00001366 // We need to update RE1 and RE2 if we are going to sink the first
1367 // instruction in the basic block down.
1368 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1369 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001370 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1371 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001372 if (!OldPN->use_empty())
1373 OldPN->replaceAllUsesWith(I1);
1374 OldPN->eraseFromParent();
1375
1376 if (!I2->use_empty())
1377 I2->replaceAllUsesWith(I1);
1378 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001379 // TODO: Use combineMetadata here to preserve what metadata we can
1380 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001381 I2->eraseFromParent();
1382
1383 if (UpdateRE1)
1384 RE1 = BB1->getInstList().rend();
1385 if (UpdateRE2)
1386 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001387 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001388 NumSinkCommons++;
1389 Changed = true;
1390 }
1391 return Changed;
1392}
1393
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001394/// \brief Determine if we can hoist sink a sole store instruction out of a
1395/// conditional block.
1396///
1397/// We are looking for code like the following:
1398/// BrBB:
1399/// store i32 %add, i32* %arrayidx2
1400/// ... // No other stores or function calls (we could be calling a memory
1401/// ... // function).
1402/// %cmp = icmp ult %x, %y
1403/// br i1 %cmp, label %EndBB, label %ThenBB
1404/// ThenBB:
1405/// store i32 %add5, i32* %arrayidx2
1406/// br label EndBB
1407/// EndBB:
1408/// ...
1409/// We are going to transform this into:
1410/// BrBB:
1411/// store i32 %add, i32* %arrayidx2
1412/// ... //
1413/// %cmp = icmp ult %x, %y
1414/// %add.add5 = select i1 %cmp, i32 %add, %add5
1415/// store i32 %add.add5, i32* %arrayidx2
1416/// ...
1417///
1418/// \return The pointer to the value of the previous store if the store can be
1419/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001420static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1421 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001422 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1423 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001424 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001425
1426 // Volatile or atomic.
1427 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001428 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001429
1430 Value *StorePtr = StoreToHoist->getPointerOperand();
1431
1432 // Look for a store to the same pointer in BrBB.
1433 unsigned MaxNumInstToLookAt = 10;
1434 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1435 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1436 Instruction *CurI = &*RI;
1437
1438 // Could be calling an instruction that effects memory like free().
1439 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001440 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001441
1442 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1443 // Found the previous store make sure it stores to the same location.
1444 if (SI && SI->getPointerOperand() == StorePtr)
1445 // Found the previous store, return its value operand.
1446 return SI->getValueOperand();
1447 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001448 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001449 }
1450
Craig Topperf40110f2014-04-25 05:29:35 +00001451 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001452}
1453
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001454/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001455///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001456/// Note that this is a very risky transform currently. Speculating
1457/// instructions like this is most often not desirable. Instead, there is an MI
1458/// pass which can do it with full awareness of the resource constraints.
1459/// However, some cases are "obvious" and we should do directly. An example of
1460/// this is speculating a single, reasonably cheap instruction.
1461///
1462/// There is only one distinct advantage to flattening the CFG at the IR level:
1463/// it makes very common but simplistic optimizations such as are common in
1464/// instcombine and the DAG combiner more powerful by removing CFG edges and
1465/// modeling their effects with easier to reason about SSA value graphs.
1466///
1467///
1468/// An illustration of this transform is turning this IR:
1469/// \code
1470/// BB:
1471/// %cmp = icmp ult %x, %y
1472/// br i1 %cmp, label %EndBB, label %ThenBB
1473/// ThenBB:
1474/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001475/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001476/// EndBB:
1477/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1478/// ...
1479/// \endcode
1480///
1481/// Into this IR:
1482/// \code
1483/// BB:
1484/// %cmp = icmp ult %x, %y
1485/// %sub = sub %x, %y
1486/// %cond = select i1 %cmp, 0, %sub
1487/// ...
1488/// \endcode
1489///
1490/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001491static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001492 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001493 // Be conservative for now. FP select instruction can often be expensive.
1494 Value *BrCond = BI->getCondition();
1495 if (isa<FCmpInst>(BrCond))
1496 return false;
1497
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001498 BasicBlock *BB = BI->getParent();
1499 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1500
1501 // If ThenBB is actually on the false edge of the conditional branch, remember
1502 // to swap the select operands later.
1503 bool Invert = false;
1504 if (ThenBB != BI->getSuccessor(0)) {
1505 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1506 Invert = true;
1507 }
1508 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1509
Chandler Carruthceff2222013-01-25 05:40:09 +00001510 // Keep a count of how many times instructions are used within CondBB when
1511 // they are candidates for sinking into CondBB. Specifically:
1512 // - They are defined in BB, and
1513 // - They have no side effects, and
1514 // - All of their uses are in CondBB.
1515 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1516
Chandler Carruth7481ca82013-01-24 11:52:58 +00001517 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001518 Value *SpeculatedStoreValue = nullptr;
1519 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001520 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001521 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001522 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001523 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001524 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001525 if (isa<DbgInfoIntrinsic>(I))
1526 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001527
Mark Lacey274f48b2015-04-12 18:18:51 +00001528 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001529 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001530 ++SpeculationCost;
1531 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001532 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001533
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001534 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001535 if (!isSafeToSpeculativelyExecute(I) &&
1536 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1537 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001538 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001539 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001540 ComputeSpeculationCost(I, TTI) >
1541 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001542 return false;
1543
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001544 // Store the store speculation candidate.
1545 if (SpeculatedStoreValue)
1546 SpeculatedStore = cast<StoreInst>(I);
1547
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001548 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001549 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001550 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001551 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001552 i != e; ++i) {
1553 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001554 if (!OpI || OpI->getParent() != BB ||
1555 OpI->mayHaveSideEffects())
1556 continue; // Not a candidate for sinking.
1557
1558 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001559 }
1560 }
Evan Cheng89200c92008-06-07 08:52:29 +00001561
Chandler Carruthceff2222013-01-25 05:40:09 +00001562 // Consider any sink candidates which are only used in CondBB as costs for
1563 // speculation. Note, while we iterate over a DenseMap here, we are summing
1564 // and so iteration order isn't significant.
1565 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1566 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1567 I != E; ++I)
1568 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001569 ++SpeculationCost;
1570 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001571 return false;
1572 }
1573
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001574 // Check that the PHI nodes can be converted to selects.
1575 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001576 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001577 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001578 Value *OrigV = PN->getIncomingValueForBlock(BB);
1579 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001580
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001581 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001582 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001583 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001584 continue;
1585
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001586 // Don't convert to selects if we could remove undefined behavior instead.
1587 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1588 passingValueIsAlwaysUndefined(ThenV, PN))
1589 return false;
1590
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001591 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001592 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1593 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1594 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001595 continue; // Known safe and cheap.
1596
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001597 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1598 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001599 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001600 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1601 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001602 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1603 TargetTransformInfo::TCC_Basic;
1604 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001605 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001606
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001607 // Account for the cost of an unfolded ConstantExpr which could end up
1608 // getting expanded into Instructions.
1609 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001610 // constant expression.
1611 ++SpeculationCost;
1612 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001613 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001614 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001615
1616 // If there are no PHIs to process, bail early. This helps ensure idempotence
1617 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001618 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001619 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001620
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001621 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001622 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001623
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001624 // Insert a select of the value of the speculated store.
1625 if (SpeculatedStoreValue) {
1626 IRBuilder<true, NoFolder> Builder(BI);
1627 Value *TrueV = SpeculatedStore->getValueOperand();
1628 Value *FalseV = SpeculatedStoreValue;
1629 if (Invert)
1630 std::swap(TrueV, FalseV);
1631 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1632 "." + FalseV->getName());
1633 SpeculatedStore->setOperand(0, S);
1634 }
1635
Igor Laevsky7310c682015-11-18 14:50:18 +00001636 // Metadata can be dependent on the condition we are hoisting above.
1637 // Conservatively strip all metadata on the instruction.
1638 for (auto &I: *ThenBB)
1639 I.dropUnknownNonDebugMetadata();
1640
Chandler Carruth7481ca82013-01-24 11:52:58 +00001641 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001642 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1643 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001644
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001645 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001646 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001647 for (BasicBlock::iterator I = EndBB->begin();
1648 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1649 unsigned OrigI = PN->getBasicBlockIndex(BB);
1650 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1651 Value *OrigV = PN->getIncomingValue(OrigI);
1652 Value *ThenV = PN->getIncomingValue(ThenI);
1653
1654 // Skip PHIs which are trivial.
1655 if (OrigV == ThenV)
1656 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001657
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001658 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001659 // false value is the preexisting value. Swap them if the branch
1660 // destinations were inverted.
1661 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001662 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001663 std::swap(TrueV, FalseV);
1664 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1665 TrueV->getName() + "." + FalseV->getName());
1666 PN->setIncomingValue(OrigI, V);
1667 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001668 }
1669
Evan Cheng89553cc2008-06-12 21:15:59 +00001670 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001671 return true;
1672}
1673
Tom Stellarde1631dd2013-10-21 20:07:30 +00001674/// \returns True if this block contains a CallInst with the NoDuplicate
1675/// attribute.
1676static bool HasNoDuplicateCall(const BasicBlock *BB) {
1677 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1678 const CallInst *CI = dyn_cast<CallInst>(I);
1679 if (!CI)
1680 continue;
1681 if (CI->cannotDuplicate())
1682 return true;
1683 }
1684 return false;
1685}
1686
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001687/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001688static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1689 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001690 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001691
Devang Patel84fceff2009-03-10 18:00:05 +00001692 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001693 if (isa<DbgInfoIntrinsic>(BBI))
1694 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001695 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001696 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001697
Dale Johannesened6f5a82009-03-12 23:18:09 +00001698 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001699 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001700 for (User *U : BBI->users()) {
1701 Instruction *UI = cast<Instruction>(U);
1702 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001703 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001704
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001705 // Looks ok, continue checking.
1706 }
Chris Lattner6c701062005-09-20 01:48:40 +00001707
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001708 return true;
1709}
1710
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001711/// If we have a conditional branch on a PHI node value that is defined in the
1712/// same block as the branch and if any PHI entries are constants, thread edges
1713/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001714static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001715 BasicBlock *BB = BI->getParent();
1716 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001717 // NOTE: we currently cannot transform this case if the PHI node is used
1718 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001719 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1720 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001721
Chris Lattner748f9032005-09-19 23:49:37 +00001722 // Degenerate case of a single entry PHI.
1723 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001724 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001725 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001726 }
1727
1728 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001729 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001730
Tom Stellarde1631dd2013-10-21 20:07:30 +00001731 if (HasNoDuplicateCall(BB)) return false;
1732
Chris Lattner748f9032005-09-19 23:49:37 +00001733 // Okay, this is a simple enough basic block. See if any phi values are
1734 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001735 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001736 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001737 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001738
Chris Lattner4088e2b2010-12-13 01:47:07 +00001739 // Okay, we now know that all edges from PredBB should be revectored to
1740 // branch to RealDest.
1741 BasicBlock *PredBB = PN->getIncomingBlock(i);
1742 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001743
Chris Lattner4088e2b2010-12-13 01:47:07 +00001744 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001745 // Skip if the predecessor's terminator is an indirect branch.
1746 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001747
Chris Lattner4088e2b2010-12-13 01:47:07 +00001748 // The dest block might have PHI nodes, other predecessors and other
1749 // difficult cases. Instead of being smart about this, just insert a new
1750 // block that jumps to the destination block, effectively splitting
1751 // the edge we are about to create.
1752 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1753 RealDest->getName()+".critedge",
1754 RealDest->getParent(), RealDest);
1755 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001756
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001757 // Update PHI nodes.
1758 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001759
1760 // BB may have instructions that are being threaded over. Clone these
1761 // instructions into EdgeBB. We know that there will be no uses of the
1762 // cloned instructions outside of EdgeBB.
1763 BasicBlock::iterator InsertPt = EdgeBB->begin();
1764 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1765 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1766 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1767 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1768 continue;
1769 }
1770 // Clone the instruction.
1771 Instruction *N = BBI->clone();
1772 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001773
Chris Lattner4088e2b2010-12-13 01:47:07 +00001774 // Update operands due to translation.
1775 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1776 i != e; ++i) {
1777 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1778 if (PI != TranslateMap.end())
1779 *i = PI->second;
1780 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001781
Chris Lattner4088e2b2010-12-13 01:47:07 +00001782 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001783 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001784 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001785 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001786 } else {
1787 // Insert the new instruction into its new home.
1788 EdgeBB->getInstList().insert(InsertPt, N);
1789 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001790 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001791 }
1792 }
1793
1794 // Loop over all of the edges from PredBB to BB, changing them to branch
1795 // to EdgeBB instead.
1796 TerminatorInst *PredBBTI = PredBB->getTerminator();
1797 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1798 if (PredBBTI->getSuccessor(i) == BB) {
1799 BB->removePredecessor(PredBB);
1800 PredBBTI->setSuccessor(i, EdgeBB);
1801 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001802
Chris Lattner4088e2b2010-12-13 01:47:07 +00001803 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001804 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001805 }
Chris Lattner748f9032005-09-19 23:49:37 +00001806
1807 return false;
1808}
1809
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001810/// Given a BB that starts with the specified two-entry PHI node,
1811/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001812static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1813 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001814 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1815 // statement", which has a very simple dominance structure. Basically, we
1816 // are trying to find the condition that is being branched on, which
1817 // subsequently causes this merge to happen. We really want control
1818 // dependence information for this check, but simplifycfg can't keep it up
1819 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001820 BasicBlock *BB = PN->getParent();
1821 BasicBlock *IfTrue, *IfFalse;
1822 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001823 if (!IfCond ||
1824 // Don't bother if the branch will be constant folded trivially.
1825 isa<ConstantInt>(IfCond))
1826 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001827
Chris Lattner95adf8f12006-11-18 19:19:36 +00001828 // Okay, we found that we can merge this two-entry phi node into a select.
1829 // Doing so would require us to fold *all* two entry phi nodes in this block.
1830 // At some point this becomes non-profitable (particularly if the target
1831 // doesn't support cmov's). Only do this transformation if there are two or
1832 // fewer PHI nodes in this block.
1833 unsigned NumPhis = 0;
1834 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1835 if (NumPhis > 2)
1836 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001837
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001838 // Loop over the PHI's seeing if we can promote them all to select
1839 // instructions. While we are at it, keep track of the instructions
1840 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001841 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001842 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1843 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001844 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1845 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001846
Chris Lattner7499b452010-12-14 08:46:09 +00001847 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1848 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001849 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001850 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001851 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001852 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001853 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001854
Peter Collingbournee3511e12011-04-29 18:47:31 +00001855 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001856 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001857 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001858 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001859 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001860 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001861
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001862 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001863 // we ran out of PHIs then we simplified them all.
1864 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001865 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001866
Chris Lattner7499b452010-12-14 08:46:09 +00001867 // Don't fold i1 branches on PHIs which contain binary operators. These can
1868 // often be turned into switches and other things.
1869 if (PN->getType()->isIntegerTy(1) &&
1870 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1871 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1872 isa<BinaryOperator>(IfCond)))
1873 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001874
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001875 // If we all PHI nodes are promotable, check to make sure that all
1876 // instructions in the predecessor blocks can be promoted as well. If
1877 // not, we won't be able to get rid of the control flow, so it's not
1878 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001879 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001880 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1881 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1882 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001883 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001884 } else {
1885 DomBlock = *pred_begin(IfBlock1);
1886 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001887 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001888 // This is not an aggressive instruction that we can promote.
1889 // Because of this, we won't be able to get rid of the control
1890 // flow, so the xform is not worth it.
1891 return false;
1892 }
1893 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001894
Chris Lattner9ac168d2010-12-14 07:41:39 +00001895 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001896 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001897 } else {
1898 DomBlock = *pred_begin(IfBlock2);
1899 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001900 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001901 // This is not an aggressive instruction that we can promote.
1902 // Because of this, we won't be able to get rid of the control
1903 // flow, so the xform is not worth it.
1904 return false;
1905 }
1906 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001907
Chris Lattner9fd838d2010-12-14 07:23:10 +00001908 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001909 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001910
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001911 // If we can still promote the PHI nodes after this gauntlet of tests,
1912 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001913 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001914 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001915
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001916 // Move all 'aggressive' instructions, which are defined in the
1917 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001918 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001919 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001920 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001921 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001922 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001923 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001924 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001925 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001926
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001927 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1928 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001929 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1930 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001931
1932 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001933 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001934 PN->replaceAllUsesWith(NV);
1935 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001936 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001937 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001938
Chris Lattner335f0e42010-12-14 08:01:53 +00001939 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1940 // has been flattened. Change DomBlock to jump directly to our new block to
1941 // avoid other simplifycfg's kicking in on the diamond.
1942 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001943 Builder.SetInsertPoint(OldTI);
1944 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001945 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001946 return true;
1947}
Chris Lattner748f9032005-09-19 23:49:37 +00001948
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001949/// If we found a conditional branch that goes to two returning blocks,
1950/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001951/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001952static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001953 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001954 assert(BI->isConditional() && "Must be a conditional branch");
1955 BasicBlock *TrueSucc = BI->getSuccessor(0);
1956 BasicBlock *FalseSucc = BI->getSuccessor(1);
1957 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1958 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001959
Chris Lattner86bbf332008-04-24 00:01:19 +00001960 // Check to ensure both blocks are empty (just a return) or optionally empty
1961 // with PHI nodes. If there are other instructions, merging would cause extra
1962 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001963 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001964 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001965 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001966 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001967
Devang Pateldd14e0f2011-05-18 21:33:11 +00001968 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001969 // Okay, we found a branch that is going to two return nodes. If
1970 // there is no return value for this function, just change the
1971 // branch into a return.
1972 if (FalseRet->getNumOperands() == 0) {
1973 TrueSucc->removePredecessor(BI->getParent());
1974 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001975 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001976 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001977 return true;
1978 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001979
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001980 // Otherwise, figure out what the true and false return values are
1981 // so we can insert a new select instruction.
1982 Value *TrueValue = TrueRet->getReturnValue();
1983 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001984
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001985 // Unwrap any PHI nodes in the return blocks.
1986 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1987 if (TVPN->getParent() == TrueSucc)
1988 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1989 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1990 if (FVPN->getParent() == FalseSucc)
1991 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001992
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001993 // In order for this transformation to be safe, we must be able to
1994 // unconditionally execute both operands to the return. This is
1995 // normally the case, but we could have a potentially-trapping
1996 // constant expression that prevents this transformation from being
1997 // safe.
1998 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1999 if (TCV->canTrap())
2000 return false;
2001 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2002 if (FCV->canTrap())
2003 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002004
Chris Lattner86bbf332008-04-24 00:01:19 +00002005 // Okay, we collected all the mapped values and checked them for sanity, and
2006 // defined to really do this transformation. First, update the CFG.
2007 TrueSucc->removePredecessor(BI->getParent());
2008 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002009
Chris Lattner86bbf332008-04-24 00:01:19 +00002010 // Insert select instructions where needed.
2011 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002012 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002013 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002014 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2015 } else if (isa<UndefValue>(TrueValue)) {
2016 TrueValue = FalseValue;
2017 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00002018 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2019 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002020 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002021 }
2022
Andrew Trickf3cf1932012-08-29 21:46:36 +00002023 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002024 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2025
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002026 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002027
David Greene725c7c32010-01-05 01:26:52 +00002028 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002029 << "\n " << *BI << "NewRet = " << *RI
2030 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002031
Eli Friedmancb61afb2008-12-16 20:54:32 +00002032 EraseTerminatorInstAndDCECond(BI);
2033
Chris Lattner86bbf332008-04-24 00:01:19 +00002034 return true;
2035}
2036
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002037/// Given a conditional BranchInstruction, retrieve the probabilities of the
2038/// branch taking each edge. Fills in the two APInt parameters and returns true,
2039/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002040static bool ExtractBranchMetadata(BranchInst *BI,
2041 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2042 assert(BI->isConditional() &&
2043 "Looking for probabilities on unconditional branch?");
2044 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2045 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002046 ConstantInt *CITrue =
2047 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2048 ConstantInt *CIFalse =
2049 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002050 if (!CITrue || !CIFalse) return false;
2051 ProbTrue = CITrue->getValue().getZExtValue();
2052 ProbFalse = CIFalse->getValue().getZExtValue();
2053 return true;
2054}
2055
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002056/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002057/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002058static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002059 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2060 return false;
2061 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2062 Instruction *PBI = &*I;
2063 // Check whether Inst and PBI generate the same value.
2064 if (Inst->isIdenticalTo(PBI)) {
2065 Inst->replaceAllUsesWith(PBI);
2066 Inst->eraseFromParent();
2067 return true;
2068 }
2069 }
2070 return false;
2071}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002072
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002073/// If this basic block is simple enough, and if a predecessor branches to us
2074/// and one of our successors, fold the block into the predecessor and use
2075/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002076bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002077 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002078
Craig Topperf40110f2014-04-25 05:29:35 +00002079 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002080 if (BI->isConditional())
2081 Cond = dyn_cast<Instruction>(BI->getCondition());
2082 else {
2083 // For unconditional branch, check for a simple CFG pattern, where
2084 // BB has a single predecessor and BB's successor is also its predecessor's
2085 // successor. If such pattern exisits, check for CSE between BB and its
2086 // predecessor.
2087 if (BasicBlock *PB = BB->getSinglePredecessor())
2088 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2089 if (PBI->isConditional() &&
2090 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2091 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2092 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2093 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002094 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002095 if (isa<CmpInst>(Curr)) {
2096 Cond = Curr;
2097 break;
2098 }
2099 // Quit if we can't remove this instruction.
2100 if (!checkCSEInPredecessor(Curr, PB))
2101 return false;
2102 }
2103 }
2104
Craig Topperf40110f2014-04-25 05:29:35 +00002105 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002106 return false;
2107 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002108
Craig Topperf40110f2014-04-25 05:29:35 +00002109 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2110 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002111 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002112
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002113 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002114 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002115
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002116 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002117 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002118
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002119 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002120 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002121
Jingyue Wufc029672014-09-30 22:23:38 +00002122 // Only allow this transformation if computing the condition doesn't involve
2123 // too many instructions and these involved instructions can be executed
2124 // unconditionally. We denote all involved instructions except the condition
2125 // as "bonus instructions", and only allow this transformation when the
2126 // number of the bonus instructions does not exceed a certain threshold.
2127 unsigned NumBonusInsts = 0;
2128 for (auto I = BB->begin(); Cond != I; ++I) {
2129 // Ignore dbg intrinsics.
2130 if (isa<DbgInfoIntrinsic>(I))
2131 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002132 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002133 return false;
2134 // I has only one use and can be executed unconditionally.
2135 Instruction *User = dyn_cast<Instruction>(I->user_back());
2136 if (User == nullptr || User->getParent() != BB)
2137 return false;
2138 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2139 // to use any other instruction, User must be an instruction between next(I)
2140 // and Cond.
2141 ++NumBonusInsts;
2142 // Early exits once we reach the limit.
2143 if (NumBonusInsts > BonusInstThreshold)
2144 return false;
2145 }
2146
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002147 // Cond is known to be a compare or binary operator. Check to make sure that
2148 // neither operand is a potentially-trapping constant expression.
2149 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2150 if (CE->canTrap())
2151 return false;
2152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2153 if (CE->canTrap())
2154 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002155
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002156 // Finally, don't infinitely unroll conditional loops.
2157 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002158 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002159 if (TrueDest == BB || FalseDest == BB)
2160 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002161
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002162 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2163 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002164 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002165
Chris Lattner80b03a12008-07-13 22:23:11 +00002166 // Check that we have two conditional branches. If there is a PHI node in
2167 // the common successor, verify that the same value flows in from both
2168 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002169 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002170 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002171 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002172 !SafeToMergeTerminators(BI, PBI)) ||
2173 (!BI->isConditional() &&
2174 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002175 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002176
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002177 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002178 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002179 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002180
Manman Rend33f4ef2012-06-13 05:43:29 +00002181 if (BI->isConditional()) {
2182 if (PBI->getSuccessor(0) == TrueDest)
2183 Opc = Instruction::Or;
2184 else if (PBI->getSuccessor(1) == FalseDest)
2185 Opc = Instruction::And;
2186 else if (PBI->getSuccessor(0) == FalseDest)
2187 Opc = Instruction::And, InvertPredCond = true;
2188 else if (PBI->getSuccessor(1) == TrueDest)
2189 Opc = Instruction::Or, InvertPredCond = true;
2190 else
2191 continue;
2192 } else {
2193 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2194 continue;
2195 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002196
David Greene725c7c32010-01-05 01:26:52 +00002197 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002198 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002199
Chris Lattner55eaae12008-07-13 21:20:19 +00002200 // If we need to invert the condition in the pred block to match, do so now.
2201 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002202 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002203
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002204 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2205 CmpInst *CI = cast<CmpInst>(NewCond);
2206 CI->setPredicate(CI->getInversePredicate());
2207 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002208 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002209 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002210 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002211
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002212 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002213 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002214 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002215
Jingyue Wufc029672014-09-30 22:23:38 +00002216 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002217 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002218 // bonus instructions to a predecessor block.
2219 ValueToValueMapTy VMap; // maps original values to cloned values
2220 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002221 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002222 // instructions.
2223 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2224 if (isa<DbgInfoIntrinsic>(BonusInst))
2225 continue;
2226 Instruction *NewBonusInst = BonusInst->clone();
2227 RemapInstruction(NewBonusInst, VMap,
2228 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002229 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002230
2231 // If we moved a load, we cannot any longer claim any knowledge about
2232 // its potential value. The previous information might have been valid
2233 // only given the branch precondition.
2234 // For an analogous reason, we must also drop all the metadata whose
2235 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002236 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002237
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002238 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2239 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002240 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002241 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002242
Chris Lattner55eaae12008-07-13 21:20:19 +00002243 // Clone Cond into the predecessor basic block, and or/and the
2244 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002245 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002246 RemapInstruction(New, VMap,
2247 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002248 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002249 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002250 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002251
Manman Rend33f4ef2012-06-13 05:43:29 +00002252 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002253 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002254 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002255 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002256 PBI->setCondition(NewCond);
2257
Manman Renbfb9d432012-09-15 00:39:57 +00002258 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002259 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2260 PredFalseWeight);
2261 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2262 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002263 SmallVector<uint64_t, 8> NewWeights;
2264
Manman Rend33f4ef2012-06-13 05:43:29 +00002265 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002266 if (PredHasWeights && SuccHasWeights) {
2267 // PBI: br i1 %x, BB, FalseDest
2268 // BI: br i1 %y, TrueDest, FalseDest
2269 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2270 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2271 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2272 // TrueWeight for PBI * FalseWeight for BI.
2273 // We assume that total weights of a BranchInst can fit into 32 bits.
2274 // Therefore, we will not have overflow using 64-bit arithmetic.
2275 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2276 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2277 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002278 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2279 PBI->setSuccessor(0, TrueDest);
2280 }
2281 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002282 if (PredHasWeights && SuccHasWeights) {
2283 // PBI: br i1 %x, TrueDest, BB
2284 // BI: br i1 %y, TrueDest, FalseDest
2285 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2286 // FalseWeight for PBI * TrueWeight for BI.
2287 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2288 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2289 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2290 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2291 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002292 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2293 PBI->setSuccessor(1, FalseDest);
2294 }
Manman Renbfb9d432012-09-15 00:39:57 +00002295 if (NewWeights.size() == 2) {
2296 // Halve the weights if any of them cannot fit in an uint32_t
2297 FitWeights(NewWeights);
2298
2299 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2300 PBI->setMetadata(LLVMContext::MD_prof,
2301 MDBuilder(BI->getContext()).
2302 createBranchWeights(MDWeights));
2303 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002304 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002305 } else {
2306 // Update PHI nodes in the common successors.
2307 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002308 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002309 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2310 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002311 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002312 if (PBI->getSuccessor(0) == TrueDest) {
2313 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2314 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2315 // is false: !PBI_Cond and BI_Value
2316 Instruction *NotCond =
2317 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2318 "not.cond"));
2319 MergedCond =
2320 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2321 NotCond, New,
2322 "and.cond"));
2323 if (PBI_C->isOne())
2324 MergedCond =
2325 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2326 PBI->getCondition(), MergedCond,
2327 "or.cond"));
2328 } else {
2329 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2330 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2331 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002332 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002333 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2334 PBI->getCondition(), New,
2335 "and.cond"));
2336 if (PBI_C->isOne()) {
2337 Instruction *NotCond =
2338 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2339 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002340 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002341 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2342 NotCond, MergedCond,
2343 "or.cond"));
2344 }
2345 }
2346 // Update PHI Node.
2347 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2348 MergedCond);
2349 }
2350 // Change PBI from Conditional to Unconditional.
2351 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2352 EraseTerminatorInstAndDCECond(PBI);
2353 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002354 }
Devang Pateld715ec82011-04-06 22:37:20 +00002355
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002356 // TODO: If BB is reachable from all paths through PredBlock, then we
2357 // could replace PBI's branch probabilities with BI's.
2358
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002359 // Copy any debug value intrinsics into the end of PredBlock.
2360 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2361 if (isa<DbgInfoIntrinsic>(*I))
2362 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002363
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002364 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002365 }
2366 return false;
2367}
2368
James Molloy4de84dd2015-11-04 15:28:04 +00002369// If there is only one store in BB1 and BB2, return it, otherwise return
2370// nullptr.
2371static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2372 StoreInst *S = nullptr;
2373 for (auto *BB : {BB1, BB2}) {
2374 if (!BB)
2375 continue;
2376 for (auto &I : *BB)
2377 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2378 if (S)
2379 // Multiple stores seen.
2380 return nullptr;
2381 else
2382 S = SI;
2383 }
2384 }
2385 return S;
2386}
2387
2388static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2389 Value *AlternativeV = nullptr) {
2390 // PHI is going to be a PHI node that allows the value V that is defined in
2391 // BB to be referenced in BB's only successor.
2392 //
2393 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2394 // doesn't matter to us what the other operand is (it'll never get used). We
2395 // could just create a new PHI with an undef incoming value, but that could
2396 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2397 // other PHI. So here we directly look for some PHI in BB's successor with V
2398 // as an incoming operand. If we find one, we use it, else we create a new
2399 // one.
2400 //
2401 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2402 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2403 // where OtherBB is the single other predecessor of BB's only successor.
2404 PHINode *PHI = nullptr;
2405 BasicBlock *Succ = BB->getSingleSuccessor();
2406
2407 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2408 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2409 PHI = cast<PHINode>(I);
2410 if (!AlternativeV)
2411 break;
2412
2413 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2414 auto PredI = pred_begin(Succ);
2415 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2416 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2417 break;
2418 PHI = nullptr;
2419 }
2420 if (PHI)
2421 return PHI;
2422
James Molloy3d21dcf2015-12-16 14:12:44 +00002423 // If V is not an instruction defined in BB, just return it.
2424 if (!AlternativeV &&
2425 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2426 return V;
2427
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002428 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002429 PHI->addIncoming(V, BB);
2430 for (BasicBlock *PredBB : predecessors(Succ))
2431 if (PredBB != BB)
2432 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2433 PredBB);
2434 return PHI;
2435}
2436
2437static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2438 BasicBlock *QTB, BasicBlock *QFB,
2439 BasicBlock *PostBB, Value *Address,
2440 bool InvertPCond, bool InvertQCond) {
2441 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2442 return Operator::getOpcode(&I) == Instruction::BitCast &&
2443 I.getType()->isPointerTy();
2444 };
2445
2446 // If we're not in aggressive mode, we only optimize if we have some
2447 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2448 auto IsWorthwhile = [&](BasicBlock *BB) {
2449 if (!BB)
2450 return true;
2451 // Heuristic: if the block can be if-converted/phi-folded and the
2452 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2453 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002454 unsigned N = 0;
2455 for (auto &I : *BB) {
2456 // Cheap instructions viable for folding.
2457 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2458 isa<StoreInst>(I))
2459 ++N;
2460 // Free instructions.
2461 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2462 IsaBitcastOfPointerType(I))
2463 continue;
2464 else
James Molloy4de84dd2015-11-04 15:28:04 +00002465 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002466 }
2467 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002468 };
2469
2470 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2471 !IsWorthwhile(PFB) ||
2472 !IsWorthwhile(QTB) ||
2473 !IsWorthwhile(QFB)))
2474 return false;
2475
2476 // For every pointer, there must be exactly two stores, one coming from
2477 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2478 // store (to any address) in PTB,PFB or QTB,QFB.
2479 // FIXME: We could relax this restriction with a bit more work and performance
2480 // testing.
2481 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2482 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2483 if (!PStore || !QStore)
2484 return false;
2485
2486 // Now check the stores are compatible.
2487 if (!QStore->isUnordered() || !PStore->isUnordered())
2488 return false;
2489
2490 // Check that sinking the store won't cause program behavior changes. Sinking
2491 // the store out of the Q blocks won't change any behavior as we're sinking
2492 // from a block to its unconditional successor. But we're moving a store from
2493 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2494 // So we need to check that there are no aliasing loads or stores in
2495 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2496 // operations between PStore and the end of its parent block.
2497 //
2498 // The ideal way to do this is to query AliasAnalysis, but we don't
2499 // preserve AA currently so that is dangerous. Be super safe and just
2500 // check there are no other memory operations at all.
2501 for (auto &I : *QFB->getSinglePredecessor())
2502 if (I.mayReadOrWriteMemory())
2503 return false;
2504 for (auto &I : *QFB)
2505 if (&I != QStore && I.mayReadOrWriteMemory())
2506 return false;
2507 if (QTB)
2508 for (auto &I : *QTB)
2509 if (&I != QStore && I.mayReadOrWriteMemory())
2510 return false;
2511 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2512 I != E; ++I)
2513 if (&*I != PStore && I->mayReadOrWriteMemory())
2514 return false;
2515
2516 // OK, we're going to sink the stores to PostBB. The store has to be
2517 // conditional though, so first create the predicate.
2518 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2519 ->getCondition();
2520 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2521 ->getCondition();
2522
2523 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2524 PStore->getParent());
2525 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2526 QStore->getParent(), PPHI);
2527
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002528 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2529
James Molloy4de84dd2015-11-04 15:28:04 +00002530 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2531 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2532
2533 if (InvertPCond)
2534 PPred = QB.CreateNot(PPred);
2535 if (InvertQCond)
2536 QPred = QB.CreateNot(QPred);
2537 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2538
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002539 auto *T =
2540 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002541 QB.SetInsertPoint(T);
2542 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2543 AAMDNodes AAMD;
2544 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2545 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2546 SI->setAAMetadata(AAMD);
2547
2548 QStore->eraseFromParent();
2549 PStore->eraseFromParent();
2550
2551 return true;
2552}
2553
2554static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2555 // The intention here is to find diamonds or triangles (see below) where each
2556 // conditional block contains a store to the same address. Both of these
2557 // stores are conditional, so they can't be unconditionally sunk. But it may
2558 // be profitable to speculatively sink the stores into one merged store at the
2559 // end, and predicate the merged store on the union of the two conditions of
2560 // PBI and QBI.
2561 //
2562 // This can reduce the number of stores executed if both of the conditions are
2563 // true, and can allow the blocks to become small enough to be if-converted.
2564 // This optimization will also chain, so that ladders of test-and-set
2565 // sequences can be if-converted away.
2566 //
2567 // We only deal with simple diamonds or triangles:
2568 //
2569 // PBI or PBI or a combination of the two
2570 // / \ | \
2571 // PTB PFB | PFB
2572 // \ / | /
2573 // QBI QBI
2574 // / \ | \
2575 // QTB QFB | QFB
2576 // \ / | /
2577 // PostBB PostBB
2578 //
2579 // We model triangles as a type of diamond with a nullptr "true" block.
2580 // Triangles are canonicalized so that the fallthrough edge is represented by
2581 // a true condition, as in the diagram above.
2582 //
2583 BasicBlock *PTB = PBI->getSuccessor(0);
2584 BasicBlock *PFB = PBI->getSuccessor(1);
2585 BasicBlock *QTB = QBI->getSuccessor(0);
2586 BasicBlock *QFB = QBI->getSuccessor(1);
2587 BasicBlock *PostBB = QFB->getSingleSuccessor();
2588
2589 bool InvertPCond = false, InvertQCond = false;
2590 // Canonicalize fallthroughs to the true branches.
2591 if (PFB == QBI->getParent()) {
2592 std::swap(PFB, PTB);
2593 InvertPCond = true;
2594 }
2595 if (QFB == PostBB) {
2596 std::swap(QFB, QTB);
2597 InvertQCond = true;
2598 }
2599
2600 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2601 // and QFB may not. Model fallthroughs as a nullptr block.
2602 if (PTB == QBI->getParent())
2603 PTB = nullptr;
2604 if (QTB == PostBB)
2605 QTB = nullptr;
2606
2607 // Legality bailouts. We must have at least the non-fallthrough blocks and
2608 // the post-dominating block, and the non-fallthroughs must only have one
2609 // predecessor.
2610 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2611 return BB->getSinglePredecessor() == P &&
2612 BB->getSingleSuccessor() == S;
2613 };
2614 if (!PostBB ||
2615 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2616 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2617 return false;
2618 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2619 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2620 return false;
2621 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2622 return false;
2623
2624 // OK, this is a sequence of two diamonds or triangles.
2625 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2626 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2627 for (auto *BB : {PTB, PFB}) {
2628 if (!BB)
2629 continue;
2630 for (auto &I : *BB)
2631 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2632 PStoreAddresses.insert(SI->getPointerOperand());
2633 }
2634 for (auto *BB : {QTB, QFB}) {
2635 if (!BB)
2636 continue;
2637 for (auto &I : *BB)
2638 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2639 QStoreAddresses.insert(SI->getPointerOperand());
2640 }
2641
2642 set_intersect(PStoreAddresses, QStoreAddresses);
2643 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2644 // clear what it contains.
2645 auto &CommonAddresses = PStoreAddresses;
2646
2647 bool Changed = false;
2648 for (auto *Address : CommonAddresses)
2649 Changed |= mergeConditionalStoreToAddress(
2650 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2651 return Changed;
2652}
2653
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002654/// If we have a conditional branch as a predecessor of another block,
2655/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002656/// that PBI and BI are both conditional branches, and BI is in one of the
2657/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002658static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2659 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002660 assert(PBI->isConditional() && BI->isConditional());
2661 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002662
Chris Lattner9aada1d2008-07-13 21:53:26 +00002663 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002664 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002665 // this conditional branch redundant.
2666 if (PBI->getCondition() == BI->getCondition() &&
2667 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2668 // Okay, the outcome of this conditional branch is statically
2669 // knowable. If this block had a single pred, handle specially.
2670 if (BB->getSinglePredecessor()) {
2671 // Turn this into a branch on constant.
2672 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002673 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002674 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002675 return true; // Nuke the branch on constant.
2676 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002677
Chris Lattner9aada1d2008-07-13 21:53:26 +00002678 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2679 // in the constant and simplify the block result. Subsequent passes of
2680 // simplifycfg will thread the block.
2681 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002682 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002683 PHINode *NewPN = PHINode::Create(
2684 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2685 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002686 // Okay, we're going to insert the PHI node. Since PBI is not the only
2687 // predecessor, compute the PHI'd conditional value for all of the preds.
2688 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002689 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002690 BasicBlock *P = *PI;
2691 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002692 PBI != BI && PBI->isConditional() &&
2693 PBI->getCondition() == BI->getCondition() &&
2694 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2695 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002696 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002697 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002698 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002699 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002700 }
Gabor Greif8629f122010-07-12 10:59:23 +00002701 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002702
Chris Lattner9aada1d2008-07-13 21:53:26 +00002703 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002704 return true;
2705 }
2706 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002707
Philip Reamesb42db212015-10-14 22:46:19 +00002708 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2709 if (CE->canTrap())
2710 return false;
2711
Philip Reames846e3e42015-10-29 03:11:49 +00002712 // If BI is reached from the true path of PBI and PBI's condition implies
2713 // BI's condition, we know the direction of the BI branch.
2714 if (PBI->getSuccessor(0) == BI->getParent() &&
Sanjoy Das55ea67c2015-11-06 19:01:08 +00002715 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
Philip Reames846e3e42015-10-29 03:11:49 +00002716 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2717 BB->getSinglePredecessor()) {
2718 // Turn this into a branch on constant.
2719 auto *OldCond = BI->getCondition();
2720 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2721 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2722 return true; // Nuke the branch on constant.
2723 }
2724
James Molloy4de84dd2015-11-04 15:28:04 +00002725 // If both branches are conditional and both contain stores to the same
2726 // address, remove the stores from the conditionals and create a conditional
2727 // merged store at the end.
2728 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2729 return true;
2730
Chris Lattner9aada1d2008-07-13 21:53:26 +00002731 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002732 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002733 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002734 BasicBlock::iterator BBI = BB->begin();
2735 // Ignore dbg intrinsics.
2736 while (isa<DbgInfoIntrinsic>(BBI))
2737 ++BBI;
2738 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002739 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002740
Chris Lattner834ab4e2008-07-13 22:04:41 +00002741 int PBIOp, BIOp;
2742 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2743 PBIOp = BIOp = 0;
2744 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2745 PBIOp = 0, BIOp = 1;
2746 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2747 PBIOp = 1, BIOp = 0;
2748 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2749 PBIOp = BIOp = 1;
2750 else
2751 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002752
Chris Lattner834ab4e2008-07-13 22:04:41 +00002753 // Check to make sure that the other destination of this branch
2754 // isn't BB itself. If so, this is an infinite loop that will
2755 // keep getting unwound.
2756 if (PBI->getSuccessor(PBIOp) == BB)
2757 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002758
2759 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002760 // insertion of a large number of select instructions. For targets
2761 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002762
Sanjay Patela932da82014-07-07 21:19:00 +00002763 // Also do not perform this transformation if any phi node in the common
2764 // destination block can trap when reached by BB or PBB (PR17073). In that
2765 // case, it would be unsafe to hoist the operation into a select instruction.
2766
2767 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002768 unsigned NumPhis = 0;
2769 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002770 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002771 if (NumPhis > 2) // Disable this xform.
2772 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002773
Sanjay Patela932da82014-07-07 21:19:00 +00002774 PHINode *PN = cast<PHINode>(II);
2775 Value *BIV = PN->getIncomingValueForBlock(BB);
2776 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2777 if (CE->canTrap())
2778 return false;
2779
2780 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2781 Value *PBIV = PN->getIncomingValue(PBBIdx);
2782 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2783 if (CE->canTrap())
2784 return false;
2785 }
2786
Chris Lattner834ab4e2008-07-13 22:04:41 +00002787 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002788 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002789
David Greene725c7c32010-01-05 01:26:52 +00002790 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002791 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002792
2793
Chris Lattner80b03a12008-07-13 22:23:11 +00002794 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2795 // branch in it, where one edge (OtherDest) goes back to itself but the other
2796 // exits. We don't *know* that the program avoids the infinite loop
2797 // (even though that seems likely). If we do this xform naively, we'll end up
2798 // recursively unpeeling the loop. Since we know that (after the xform is
2799 // done) that the block *is* infinite if reached, we just make it an obviously
2800 // infinite loop with no cond branch.
2801 if (OtherDest == BB) {
2802 // Insert it at the end of the function, because it's either code,
2803 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002804 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2805 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002806 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2807 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002808 }
2809
David Greene725c7c32010-01-05 01:26:52 +00002810 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002811
Chris Lattner834ab4e2008-07-13 22:04:41 +00002812 // BI may have other predecessors. Because of this, we leave
2813 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002814
Chris Lattner834ab4e2008-07-13 22:04:41 +00002815 // Make sure we get to CommonDest on True&True directions.
2816 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002817 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002818 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002819 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2820
Chris Lattner834ab4e2008-07-13 22:04:41 +00002821 Value *BICond = BI->getCondition();
2822 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002823 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2824
Chris Lattner834ab4e2008-07-13 22:04:41 +00002825 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002826 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002827
Chris Lattner834ab4e2008-07-13 22:04:41 +00002828 // Modify PBI to branch on the new condition to the new dests.
2829 PBI->setCondition(Cond);
2830 PBI->setSuccessor(0, CommonDest);
2831 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002832
Manman Ren2d4c10f2012-09-17 21:30:40 +00002833 // Update branch weight for PBI.
2834 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002835 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2836 PredFalseWeight);
2837 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2838 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002839 if (PredHasWeights && SuccHasWeights) {
2840 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2841 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2842 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2843 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2844 // The weight to CommonDest should be PredCommon * SuccTotal +
2845 // PredOther * SuccCommon.
2846 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002847 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2848 PredOther * SuccCommon,
2849 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002850 // Halve the weights if any of them cannot fit in an uint32_t
2851 FitWeights(NewWeights);
2852
Manman Ren2d4c10f2012-09-17 21:30:40 +00002853 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002854 MDBuilder(BI->getContext())
2855 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002856 }
2857
Chris Lattner834ab4e2008-07-13 22:04:41 +00002858 // OtherDest may have phi nodes. If so, add an entry from PBI's
2859 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002860 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002861
Chris Lattner834ab4e2008-07-13 22:04:41 +00002862 // We know that the CommonDest already had an edge from PBI to
2863 // it. If it has PHIs though, the PHIs may have different
2864 // entries for BB and PBI's BB. If so, insert a select to make
2865 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002866 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002867 for (BasicBlock::iterator II = CommonDest->begin();
2868 (PN = dyn_cast<PHINode>(II)); ++II) {
2869 Value *BIV = PN->getIncomingValueForBlock(BB);
2870 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2871 Value *PBIV = PN->getIncomingValue(PBBIdx);
2872 if (BIV != PBIV) {
2873 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002874 Value *NV = cast<SelectInst>
2875 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002876 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002877 }
2878 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002879
David Greene725c7c32010-01-05 01:26:52 +00002880 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2881 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002882
Chris Lattner834ab4e2008-07-13 22:04:41 +00002883 // This basic block is probably dead. We know it has at least
2884 // one fewer predecessor.
2885 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002886}
2887
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002888// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2889// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002890// Takes care of updating the successors and removing the old terminator.
2891// Also makes sure not to introduce new successors by assuming that edges to
2892// non-successor TrueBBs and FalseBBs aren't reachable.
2893static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002894 BasicBlock *TrueBB, BasicBlock *FalseBB,
2895 uint32_t TrueWeight,
2896 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002897 // Remove any superfluous successor edges from the CFG.
2898 // First, figure out which successors to preserve.
2899 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2900 // successor.
2901 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002902 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002903
2904 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002905 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002906 // Make sure only to keep exactly one copy of each edge.
2907 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002908 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002909 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002910 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002911 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002912 Succ->removePredecessor(OldTerm->getParent(),
2913 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002914 }
2915
Devang Patel2c2ea222011-05-18 18:43:31 +00002916 IRBuilder<> Builder(OldTerm);
2917 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2918
Frits van Bommel8e158492011-01-11 12:52:11 +00002919 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002920 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002921 if (TrueBB == FalseBB)
2922 // We were only looking for one successor, and it was present.
2923 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002924 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002925 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002926 // We found both of the successors we were looking for.
2927 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002928 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2929 if (TrueWeight != FalseWeight)
2930 NewBI->setMetadata(LLVMContext::MD_prof,
2931 MDBuilder(OldTerm->getContext()).
2932 createBranchWeights(TrueWeight, FalseWeight));
2933 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002934 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2935 // Neither of the selected blocks were successors, so this
2936 // terminator must be unreachable.
2937 new UnreachableInst(OldTerm->getContext(), OldTerm);
2938 } else {
2939 // One of the selected values was a successor, but the other wasn't.
2940 // Insert an unconditional branch to the one that was found;
2941 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002942 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002943 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002944 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002945 else
2946 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002947 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002948 }
2949
2950 EraseTerminatorInstAndDCECond(OldTerm);
2951 return true;
2952}
2953
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002954// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002955// (switch (select cond, X, Y)) on constant X, Y
2956// with a branch - conditional if X and Y lead to distinct BBs,
2957// unconditional otherwise.
2958static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2959 // Check for constant integer values in the select.
2960 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2961 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2962 if (!TrueVal || !FalseVal)
2963 return false;
2964
2965 // Find the relevant condition and destinations.
2966 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002967 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2968 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002969
Manman Ren774246a2012-09-17 22:28:55 +00002970 // Get weight for TrueBB and FalseBB.
2971 uint32_t TrueWeight = 0, FalseWeight = 0;
2972 SmallVector<uint64_t, 8> Weights;
2973 bool HasWeights = HasBranchWeights(SI);
2974 if (HasWeights) {
2975 GetBranchWeights(SI, Weights);
2976 if (Weights.size() == 1 + SI->getNumCases()) {
2977 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2978 getSuccessorIndex()];
2979 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2980 getSuccessorIndex()];
2981 }
2982 }
2983
Frits van Bommel8ae07992011-02-28 09:44:07 +00002984 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002985 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2986 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002987}
2988
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002989// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002990// (indirectbr (select cond, blockaddress(@fn, BlockA),
2991// blockaddress(@fn, BlockB)))
2992// with
2993// (br cond, BlockA, BlockB).
2994static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2995 // Check that both operands of the select are block addresses.
2996 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2997 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2998 if (!TBA || !FBA)
2999 return false;
3000
3001 // Extract the actual blocks.
3002 BasicBlock *TrueBB = TBA->getBasicBlock();
3003 BasicBlock *FalseBB = FBA->getBasicBlock();
3004
Frits van Bommel8e158492011-01-11 12:52:11 +00003005 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003006 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3007 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003008}
3009
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003010/// This is called when we find an icmp instruction
3011/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003012/// block that ends with an uncond branch. We are looking for a very specific
3013/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3014/// this case, we merge the first two "or's of icmp" into a switch, but then the
3015/// default value goes to an uncond block with a seteq in it, we get something
3016/// like:
3017///
3018/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3019/// DEFAULT:
3020/// %tmp = icmp eq i8 %A, 92
3021/// br label %end
3022/// end:
3023/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003024///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003025/// We prefer to split the edge to 'end' so that there is a true/false entry to
3026/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003027static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003028 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3029 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3030 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003031 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003032
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003033 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3034 // complex.
3035 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3036
3037 Value *V = ICI->getOperand(0);
3038 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003039
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003040 // The pattern we're looking for is where our only predecessor is a switch on
3041 // 'V' and this block is the default case for the switch. In this case we can
3042 // fold the compared value into the switch to simplify things.
3043 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00003044 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003045
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003046 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3047 if (SI->getCondition() != V)
3048 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003049
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003050 // If BB is reachable on a non-default case, then we simply know the value of
3051 // V in this block. Substitute it and constant fold the icmp instruction
3052 // away.
3053 if (SI->getDefaultDest() != BB) {
3054 ConstantInt *VVal = SI->findCaseDest(BB);
3055 assert(VVal && "Should have a unique destination value");
3056 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003057
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003058 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003059 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003060 ICI->eraseFromParent();
3061 }
3062 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003063 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003064 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003065
Chris Lattner62cc76e2010-12-13 03:43:57 +00003066 // Ok, the block is reachable from the default dest. If the constant we're
3067 // comparing exists in one of the other edges, then we can constant fold ICI
3068 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003069 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003070 Value *V;
3071 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3072 V = ConstantInt::getFalse(BB->getContext());
3073 else
3074 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003075
Chris Lattner62cc76e2010-12-13 03:43:57 +00003076 ICI->replaceAllUsesWith(V);
3077 ICI->eraseFromParent();
3078 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003079 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003080 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003081
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003082 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3083 // the block.
3084 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003085 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003086 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003087 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3088 return false;
3089
3090 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3091 // true in the PHI.
3092 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3093 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3094
3095 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3096 std::swap(DefaultCst, NewCst);
3097
3098 // Replace ICI (which is used by the PHI for the default value) with true or
3099 // false depending on if it is EQ or NE.
3100 ICI->replaceAllUsesWith(DefaultCst);
3101 ICI->eraseFromParent();
3102
3103 // Okay, the switch goes to this block on a default value. Add an edge from
3104 // the switch to the merge point on the compared value.
3105 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3106 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003107 SmallVector<uint64_t, 8> Weights;
3108 bool HasWeights = HasBranchWeights(SI);
3109 if (HasWeights) {
3110 GetBranchWeights(SI, Weights);
3111 if (Weights.size() == 1 + SI->getNumCases()) {
3112 // Split weight for default case to case for "Cst".
3113 Weights[0] = (Weights[0]+1) >> 1;
3114 Weights.push_back(Weights[0]);
3115
3116 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3117 SI->setMetadata(LLVMContext::MD_prof,
3118 MDBuilder(SI->getContext()).
3119 createBranchWeights(MDWeights));
3120 }
3121 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003122 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003123
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003124 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003125 Builder.SetInsertPoint(NewBB);
3126 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3127 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003128 PHIUse->addIncoming(NewCst, NewBB);
3129 return true;
3130}
3131
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003132/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003133/// Check to see if it is branching on an or/and chain of icmp instructions, and
3134/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003135static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3136 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003137 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00003138 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003139
Chris Lattnera69c4432010-12-13 05:03:41 +00003140 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3141 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3142 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003143
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003144 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003145 ConstantComparesGatherer ConstantCompare(Cond, DL);
3146 // Unpack the result
3147 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3148 Value *CompVal = ConstantCompare.CompValue;
3149 unsigned UsedICmps = ConstantCompare.UsedICmps;
3150 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003151
Chris Lattnera69c4432010-12-13 05:03:41 +00003152 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00003153 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003154
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003155 // Avoid turning single icmps into a switch.
3156 if (UsedICmps <= 1)
3157 return false;
3158
Mehdi Aminiffd01002014-11-20 22:40:25 +00003159 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3160
Chris Lattnera69c4432010-12-13 05:03:41 +00003161 // There might be duplicate constants in the list, which the switch
3162 // instruction can't handle, remove them now.
3163 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3164 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003165
Chris Lattnera69c4432010-12-13 05:03:41 +00003166 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003167 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003168 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003169
Andrew Trick3051aa12012-08-29 21:46:38 +00003170 // TODO: Preserve branch weight metadata, similarly to how
3171 // FoldValueComparisonIntoPredecessors preserves it.
3172
Chris Lattnera69c4432010-12-13 05:03:41 +00003173 // Figure out which block is which destination.
3174 BasicBlock *DefaultBB = BI->getSuccessor(1);
3175 BasicBlock *EdgeBB = BI->getSuccessor(0);
3176 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003177
Chris Lattnera69c4432010-12-13 05:03:41 +00003178 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003179
Chris Lattnerd7beca32010-12-14 06:17:25 +00003180 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003181 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003182
Chris Lattnera69c4432010-12-13 05:03:41 +00003183 // If there are any extra values that couldn't be folded into the switch
3184 // then we evaluate them with an explicit branch first. Split the block
3185 // right before the condbr to handle it.
3186 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003187 BasicBlock *NewBB =
3188 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003189 // Remove the uncond branch added to the old block.
3190 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003191 Builder.SetInsertPoint(OldTI);
3192
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003193 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003194 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003195 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003196 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003197
Chris Lattnera69c4432010-12-13 05:03:41 +00003198 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003199
Chris Lattnercb570f82010-12-13 05:34:18 +00003200 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3201 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003202 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003203
Chris Lattnerd7beca32010-12-14 06:17:25 +00003204 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3205 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003206 BB = NewBB;
3207 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003208
3209 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003210 // Convert pointer to int before we switch.
3211 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003212 CompVal = Builder.CreatePtrToInt(
3213 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003214 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003215
Chris Lattnera69c4432010-12-13 05:03:41 +00003216 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003217 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003218
Chris Lattnera69c4432010-12-13 05:03:41 +00003219 // Add all of the 'cases' to the switch instruction.
3220 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3221 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003222
Chris Lattnera69c4432010-12-13 05:03:41 +00003223 // We added edges from PI to the EdgeBB. As such, if there were any
3224 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3225 // the number of edges added.
3226 for (BasicBlock::iterator BBI = EdgeBB->begin();
3227 isa<PHINode>(BBI); ++BBI) {
3228 PHINode *PN = cast<PHINode>(BBI);
3229 Value *InVal = PN->getIncomingValueForBlock(BB);
3230 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3231 PN->addIncoming(InVal, BB);
3232 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003233
Chris Lattnera69c4432010-12-13 05:03:41 +00003234 // Erase the old branch instruction.
3235 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003236
Chris Lattnerd7beca32010-12-14 06:17:25 +00003237 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003238 return true;
3239}
3240
Duncan Sands29192d02011-09-05 12:57:57 +00003241bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3242 // If this is a trivial landing pad that just continues unwinding the caught
3243 // exception then zap the landing pad, turning its invokes into calls.
3244 BasicBlock *BB = RI->getParent();
3245 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Li7009cd32015-10-23 21:13:01 +00003246 if (RI->getValue() != LPInst)
3247 // Not a landing pad, or the resume is not unwinding the exception that
3248 // caused control to branch here.
Duncan Sands29192d02011-09-05 12:57:57 +00003249 return false;
3250
Chen Li7009cd32015-10-23 21:13:01 +00003251 // Check that there are no other instructions except for debug intrinsics.
3252 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003253 while (++I != E)
3254 if (!isa<DbgInfoIntrinsic>(I))
3255 return false;
3256
Chen Lic6e28782015-10-22 20:48:38 +00003257 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003258 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3259 BasicBlock *Pred = *PI++;
3260 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003261 }
3262
Chen Li7009cd32015-10-23 21:13:01 +00003263 // The landingpad is now unreachable. Zap it.
3264 BB->eraseFromParent();
3265 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003266}
3267
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003268bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3269 // If this is a trivial cleanup pad that executes no instructions, it can be
3270 // eliminated. If the cleanup pad continues to the caller, any predecessor
3271 // that is an EH pad will be updated to continue to the caller and any
3272 // predecessor that terminates with an invoke instruction will have its invoke
3273 // instruction converted to a call instruction. If the cleanup pad being
3274 // simplified does not continue to the caller, each predecessor will be
3275 // updated to continue to the unwind destination of the cleanup pad being
3276 // simplified.
3277 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003278 CleanupPadInst *CPInst = RI->getCleanupPad();
3279 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003280 // This isn't an empty cleanup.
3281 return false;
3282
3283 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003284 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003285 while (++I != E)
3286 if (!isa<DbgInfoIntrinsic>(I))
3287 return false;
3288
David Majnemer8a1c45d2015-12-12 05:38:55 +00003289 // If the cleanup return we are simplifying unwinds to the caller, this will
3290 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003291 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003292 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003293
3294 // We're about to remove BB from the control flow. Before we do, sink any
3295 // PHINodes into the unwind destination. Doing this before changing the
3296 // control flow avoids some potentially slow checks, since we can currently
3297 // be certain that UnwindDest and BB have no common predecessors (since they
3298 // are both EH pads).
3299 if (UnwindDest) {
3300 // First, go through the PHI nodes in UnwindDest and update any nodes that
3301 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003302 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003303 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003304 I != IE; ++I) {
3305 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003306
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003307 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003308 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003309 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003310 // This PHI node has an incoming value that corresponds to a control
3311 // path through the cleanup pad we are removing. If the incoming
3312 // value is in the cleanup pad, it must be a PHINode (because we
3313 // verified above that the block is otherwise empty). Otherwise, the
3314 // value is either a constant or a value that dominates the cleanup
3315 // pad being removed.
3316 //
3317 // Because BB and UnwindDest are both EH pads, all of their
3318 // predecessors must unwind to these blocks, and since no instruction
3319 // can have multiple unwind destinations, there will be no overlap in
3320 // incoming blocks between SrcPN and DestPN.
3321 Value *SrcVal = DestPN->getIncomingValue(Idx);
3322 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3323
3324 // Remove the entry for the block we are deleting.
3325 DestPN->removeIncomingValue(Idx, false);
3326
3327 if (SrcPN && SrcPN->getParent() == BB) {
3328 // If the incoming value was a PHI node in the cleanup pad we are
3329 // removing, we need to merge that PHI node's incoming values into
3330 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003331 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003332 SrcIdx != SrcE; ++SrcIdx) {
3333 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3334 SrcPN->getIncomingBlock(SrcIdx));
3335 }
3336 } else {
3337 // Otherwise, the incoming value came from above BB and
3338 // so we can just reuse it. We must associate all of BB's
3339 // predecessors with this value.
3340 for (auto *pred : predecessors(BB)) {
3341 DestPN->addIncoming(SrcVal, pred);
3342 }
3343 }
3344 }
3345
3346 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003347 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003348 for (BasicBlock::iterator I = BB->begin(),
3349 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003350 I != IE;) {
3351 // The iterator must be incremented here because the instructions are
3352 // being moved to another block.
3353 PHINode *PN = cast<PHINode>(I++);
3354 if (PN->use_empty())
3355 // If the PHI node has no uses, just leave it. It will be erased
3356 // when we erase BB below.
3357 continue;
3358
3359 // Otherwise, sink this PHI node into UnwindDest.
3360 // Any predecessors to UnwindDest which are not already represented
3361 // must be back edges which inherit the value from the path through
3362 // BB. In this case, the PHI value must reference itself.
3363 for (auto *pred : predecessors(UnwindDest))
3364 if (pred != BB)
3365 PN->addIncoming(PN, pred);
3366 PN->moveBefore(InsertPt);
3367 }
3368 }
3369
3370 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3371 // The iterator must be updated here because we are removing this pred.
3372 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003373 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003374 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003375 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003376 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003377 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003378 }
3379 }
3380
3381 // The cleanup pad is now unreachable. Zap it.
3382 BB->eraseFromParent();
3383 return true;
3384}
3385
Devang Pateldd14e0f2011-05-18 21:33:11 +00003386bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003387 BasicBlock *BB = RI->getParent();
3388 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003389
Chris Lattner25c3af32010-12-13 06:25:44 +00003390 // Find predecessors that end with branches.
3391 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3392 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003393 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3394 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003395 TerminatorInst *PTI = P->getTerminator();
3396 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3397 if (BI->isUnconditional())
3398 UncondBranchPreds.push_back(P);
3399 else
3400 CondBranchPreds.push_back(BI);
3401 }
3402 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003403
Chris Lattner25c3af32010-12-13 06:25:44 +00003404 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003405 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003406 while (!UncondBranchPreds.empty()) {
3407 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3408 DEBUG(dbgs() << "FOLDING: " << *BB
3409 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003410 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003411 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003412
Chris Lattner25c3af32010-12-13 06:25:44 +00003413 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003414 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003415 // We know there are no successors, so just nuke the block.
3416 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003417
Chris Lattner25c3af32010-12-13 06:25:44 +00003418 return true;
3419 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003420
Chris Lattner25c3af32010-12-13 06:25:44 +00003421 // Check out all of the conditional branches going to this return
3422 // instruction. If any of them just select between returns, change the
3423 // branch itself into a select/return pair.
3424 while (!CondBranchPreds.empty()) {
3425 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003426
Chris Lattner25c3af32010-12-13 06:25:44 +00003427 // Check to see if the non-BB successor is also a return block.
3428 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3429 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003430 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003431 return true;
3432 }
3433 return false;
3434}
3435
Chris Lattner25c3af32010-12-13 06:25:44 +00003436bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3437 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003438
Chris Lattner25c3af32010-12-13 06:25:44 +00003439 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003440
Chris Lattner25c3af32010-12-13 06:25:44 +00003441 // If there are any instructions immediately before the unreachable that can
3442 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003443 while (UI->getIterator() != BB->begin()) {
3444 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003445 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003446 // Do not delete instructions that can have side effects which might cause
3447 // the unreachable to not be reachable; specifically, calls and volatile
3448 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003449 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003450
3451 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003452 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003453 if (SI->isVolatile())
3454 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003455 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003456 if (LI->isVolatile())
3457 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003458 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003459 if (RMWI->isVolatile())
3460 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003461 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003462 if (CXI->isVolatile())
3463 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003464 } else if (isa<CatchPadInst>(BBI)) {
3465 // A catchpad may invoke exception object constructors and such, which
3466 // in some languages can be arbitrary code, so be conservative by
3467 // default.
3468 // For CoreCLR, it just involves a type test, so can be removed.
3469 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3470 EHPersonality::CoreCLR)
3471 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003472 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3473 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003474 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003475 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003476 // Note that deleting LandingPad's here is in fact okay, although it
3477 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3478 // all the predecessors of this block will be the unwind edges of Invokes,
3479 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003480 }
3481
Eli Friedmanaac35b32011-03-09 00:48:33 +00003482 // Delete this instruction (any uses are guaranteed to be dead)
3483 if (!BBI->use_empty())
3484 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003485 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003486 Changed = true;
3487 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003488
Chris Lattner25c3af32010-12-13 06:25:44 +00003489 // If the unreachable instruction is the first in the block, take a gander
3490 // at all of the predecessors of this instruction, and simplify them.
3491 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003492
Chris Lattner25c3af32010-12-13 06:25:44 +00003493 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3494 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3495 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003496 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003497 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003498 if (BI->isUnconditional()) {
3499 if (BI->getSuccessor(0) == BB) {
3500 new UnreachableInst(TI->getContext(), TI);
3501 TI->eraseFromParent();
3502 Changed = true;
3503 }
3504 } else {
3505 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003506 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003507 EraseTerminatorInstAndDCECond(BI);
3508 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003509 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003510 EraseTerminatorInstAndDCECond(BI);
3511 Changed = true;
3512 }
3513 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003514 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003515 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003516 i != e; ++i)
3517 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003518 BB->removePredecessor(SI->getParent());
3519 SI->removeCase(i);
3520 --i; --e;
3521 Changed = true;
3522 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003523 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3524 if (II->getUnwindDest() == BB) {
3525 removeUnwindEdge(TI->getParent());
3526 Changed = true;
3527 }
3528 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3529 if (CSI->getUnwindDest() == BB) {
3530 removeUnwindEdge(TI->getParent());
3531 Changed = true;
3532 continue;
3533 }
3534
3535 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3536 E = CSI->handler_end();
3537 I != E; ++I) {
3538 if (*I == BB) {
3539 CSI->removeHandler(I);
3540 --I;
3541 --E;
3542 Changed = true;
3543 }
3544 }
3545 if (CSI->getNumHandlers() == 0) {
3546 BasicBlock *CatchSwitchBB = CSI->getParent();
3547 if (CSI->hasUnwindDest()) {
3548 // Redirect preds to the unwind dest
3549 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3550 } else {
3551 // Rewrite all preds to unwind to caller (or from invoke to call).
3552 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3553 for (BasicBlock *EHPred : EHPreds)
3554 removeUnwindEdge(EHPred);
3555 }
3556 // The catchswitch is no longer reachable.
3557 new UnreachableInst(CSI->getContext(), CSI);
3558 CSI->eraseFromParent();
3559 Changed = true;
3560 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003561 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003562 new UnreachableInst(TI->getContext(), TI);
3563 TI->eraseFromParent();
3564 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003565 }
3566 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003567
Chris Lattner25c3af32010-12-13 06:25:44 +00003568 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003569 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003570 BB != &BB->getParent()->getEntryBlock()) {
3571 // We know there are no successors, so just nuke the block.
3572 BB->eraseFromParent();
3573 return true;
3574 }
3575
3576 return Changed;
3577}
3578
Hans Wennborg68000082015-01-26 19:52:32 +00003579static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3580 assert(Cases.size() >= 1);
3581
3582 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3583 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3584 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3585 return false;
3586 }
3587 return true;
3588}
3589
3590/// Turn a switch with two reachable destinations into an integer range
3591/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003592static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003593 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003594
Hans Wennborg68000082015-01-26 19:52:32 +00003595 bool HasDefault =
3596 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003597
Hans Wennborg68000082015-01-26 19:52:32 +00003598 // Partition the cases into two sets with different destinations.
3599 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3600 BasicBlock *DestB = nullptr;
3601 SmallVector <ConstantInt *, 16> CasesA;
3602 SmallVector <ConstantInt *, 16> CasesB;
3603
3604 for (SwitchInst::CaseIt I : SI->cases()) {
3605 BasicBlock *Dest = I.getCaseSuccessor();
3606 if (!DestA) DestA = Dest;
3607 if (Dest == DestA) {
3608 CasesA.push_back(I.getCaseValue());
3609 continue;
3610 }
3611 if (!DestB) DestB = Dest;
3612 if (Dest == DestB) {
3613 CasesB.push_back(I.getCaseValue());
3614 continue;
3615 }
3616 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003617 }
3618
Hans Wennborg68000082015-01-26 19:52:32 +00003619 assert(DestA && DestB && "Single-destination switch should have been folded.");
3620 assert(DestA != DestB);
3621 assert(DestB != SI->getDefaultDest());
3622 assert(!CasesB.empty() && "There must be non-default cases.");
3623 assert(!CasesA.empty() || HasDefault);
3624
3625 // Figure out if one of the sets of cases form a contiguous range.
3626 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3627 BasicBlock *ContiguousDest = nullptr;
3628 BasicBlock *OtherDest = nullptr;
3629 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3630 ContiguousCases = &CasesA;
3631 ContiguousDest = DestA;
3632 OtherDest = DestB;
3633 } else if (CasesAreContiguous(CasesB)) {
3634 ContiguousCases = &CasesB;
3635 ContiguousDest = DestB;
3636 OtherDest = DestA;
3637 } else
3638 return false;
3639
3640 // Start building the compare and branch.
3641
3642 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3643 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003644
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003645 Value *Sub = SI->getCondition();
3646 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003647 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3648
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003649 Value *Cmp;
3650 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003651 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003652 Cmp = ConstantInt::getTrue(SI->getContext());
3653 else
3654 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003655 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003656
Manman Ren56575552012-09-18 00:47:33 +00003657 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003658 if (HasBranchWeights(SI)) {
3659 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003660 GetBranchWeights(SI, Weights);
3661 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003662 uint64_t TrueWeight = 0;
3663 uint64_t FalseWeight = 0;
3664 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3665 if (SI->getSuccessor(I) == ContiguousDest)
3666 TrueWeight += Weights[I];
3667 else
3668 FalseWeight += Weights[I];
3669 }
3670 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3671 TrueWeight /= 2;
3672 FalseWeight /= 2;
3673 }
Manman Ren56575552012-09-18 00:47:33 +00003674 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003675 MDBuilder(SI->getContext()).createBranchWeights(
3676 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003677 }
3678 }
3679
Hans Wennborg68000082015-01-26 19:52:32 +00003680 // Prune obsolete incoming values off the successors' PHI nodes.
3681 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3682 unsigned PreviousEdges = ContiguousCases->size();
3683 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3684 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003685 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3686 }
Hans Wennborg68000082015-01-26 19:52:32 +00003687 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3688 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3689 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3690 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3691 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3692 }
3693
3694 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003695 SI->eraseFromParent();
3696
3697 return true;
3698}
Chris Lattner25c3af32010-12-13 06:25:44 +00003699
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003700/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003701/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003702static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3703 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003704 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003705 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003706 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003707 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003708
3709 // Gather dead cases.
3710 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003711 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003712 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3713 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3714 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003715 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003716 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003717 }
3718 }
3719
Philip Reames98a2dab2015-08-26 23:56:46 +00003720 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003721 // default destination becomes dead and we can remove it. If we know some
3722 // of the bits in the value, we can use that to more precisely compute the
3723 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003724 bool HasDefault =
3725 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003726 const unsigned NumUnknownBits = Bits -
3727 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003728 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003729 if (HasDefault && DeadCases.empty() &&
3730 NumUnknownBits < 64 /* avoid overflow */ &&
3731 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003732 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3733 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3734 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003735 SI->setDefaultDest(&*NewDefault);
3736 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003737 auto *OldTI = NewDefault->getTerminator();
3738 new UnreachableInst(SI->getContext(), OldTI);
3739 EraseTerminatorInstAndDCECond(OldTI);
3740 return true;
3741 }
3742
Manman Ren56575552012-09-18 00:47:33 +00003743 SmallVector<uint64_t, 8> Weights;
3744 bool HasWeight = HasBranchWeights(SI);
3745 if (HasWeight) {
3746 GetBranchWeights(SI, Weights);
3747 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3748 }
3749
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003750 // Remove dead cases from the switch.
3751 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003752 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003753 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003754 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003755 if (HasWeight) {
3756 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3757 Weights.pop_back();
3758 }
3759
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003760 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003761 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003762 SI->removeCase(Case);
3763 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003764 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003765 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3766 SI->setMetadata(LLVMContext::MD_prof,
3767 MDBuilder(SI->getParent()->getContext()).
3768 createBranchWeights(MDWeights));
3769 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003770
3771 return !DeadCases.empty();
3772}
3773
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003774/// If BB would be eligible for simplification by
3775/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003776/// by an unconditional branch), look at the phi node for BB in the successor
3777/// block and see if the incoming value is equal to CaseValue. If so, return
3778/// the phi node, and set PhiIndex to BB's index in the phi node.
3779static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3780 BasicBlock *BB,
3781 int *PhiIndex) {
3782 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003783 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003784 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003785 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003786
3787 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3788 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003789 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003790
3791 BasicBlock *Succ = Branch->getSuccessor(0);
3792
3793 BasicBlock::iterator I = Succ->begin();
3794 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3795 int Idx = PHI->getBasicBlockIndex(BB);
3796 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3797
3798 Value *InValue = PHI->getIncomingValue(Idx);
3799 if (InValue != CaseValue) continue;
3800
3801 *PhiIndex = Idx;
3802 return PHI;
3803 }
3804
Craig Topperf40110f2014-04-25 05:29:35 +00003805 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003806}
3807
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003808/// Try to forward the condition of a switch instruction to a phi node
3809/// dominated by the switch, if that would mean that some of the destination
3810/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003811/// Returns true if a change is made.
3812static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3813 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3814 ForwardingNodesMap ForwardingNodes;
3815
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003816 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003817 ConstantInt *CaseValue = I.getCaseValue();
3818 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003819
3820 int PhiIndex;
3821 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3822 &PhiIndex);
3823 if (!PHI) continue;
3824
3825 ForwardingNodes[PHI].push_back(PhiIndex);
3826 }
3827
3828 bool Changed = false;
3829
3830 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3831 E = ForwardingNodes.end(); I != E; ++I) {
3832 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003833 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003834
3835 if (Indexes.size() < 2) continue;
3836
3837 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3838 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3839 Changed = true;
3840 }
3841
3842 return Changed;
3843}
3844
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003845/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003846/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003847static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003848 if (C->isThreadDependent())
3849 return false;
3850 if (C->isDLLImportDependent())
3851 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003852
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003853 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3854 return CE->isGEPWithNoNotionalOverIndexing();
3855
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003856 return isa<ConstantFP>(C) ||
3857 isa<ConstantInt>(C) ||
3858 isa<ConstantPointerNull>(C) ||
3859 isa<GlobalValue>(C) ||
3860 isa<UndefValue>(C);
3861}
3862
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003863/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003864/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003865static Constant *LookupConstant(Value *V,
3866 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3867 if (Constant *C = dyn_cast<Constant>(V))
3868 return C;
3869 return ConstantPool.lookup(V);
3870}
3871
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003872/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003873/// simple instructions such as binary operations where both operands are
3874/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003875/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003876static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003877ConstantFold(Instruction *I, const DataLayout &DL,
3878 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003879 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003880 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3881 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003882 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003883 if (A->isAllOnesValue())
3884 return LookupConstant(Select->getTrueValue(), ConstantPool);
3885 if (A->isNullValue())
3886 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003887 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003888 }
3889
Benjamin Kramer7c302602013-11-12 12:24:36 +00003890 SmallVector<Constant *, 4> COps;
3891 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3892 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3893 COps.push_back(A);
3894 else
Craig Topperf40110f2014-04-25 05:29:35 +00003895 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003896 }
3897
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003898 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003899 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3900 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003901 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003902
3903 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003904}
3905
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003906/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003907/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003908/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003909/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003910static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003911GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00003912 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003913 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3914 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003915 // The block from which we enter the common destination.
3916 BasicBlock *Pred = SI->getParent();
3917
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003918 // If CaseDest is empty except for some side-effect free instructions through
3919 // which we can constant-propagate the CaseVal, continue to its successor.
3920 SmallDenseMap<Value*, Constant*> ConstantPool;
3921 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3922 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3923 ++I) {
3924 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3925 // If the terminator is a simple branch, continue to the next block.
3926 if (T->getNumSuccessors() != 1)
3927 return false;
3928 Pred = CaseDest;
3929 CaseDest = T->getSuccessor(0);
3930 } else if (isa<DbgInfoIntrinsic>(I)) {
3931 // Skip debug intrinsic.
3932 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003933 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003934 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003935
3936 // If the instruction has uses outside this block or a phi node slot for
3937 // the block, it is not safe to bypass the instruction since it would then
3938 // no longer dominate all its uses.
3939 for (auto &Use : I->uses()) {
3940 User *User = Use.getUser();
3941 if (Instruction *I = dyn_cast<Instruction>(User))
3942 if (I->getParent() == CaseDest)
3943 continue;
3944 if (PHINode *Phi = dyn_cast<PHINode>(User))
3945 if (Phi->getIncomingBlock(Use) == CaseDest)
3946 continue;
3947 return false;
3948 }
3949
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003950 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003951 } else {
3952 break;
3953 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003954 }
3955
3956 // If we did not have a CommonDest before, use the current one.
3957 if (!*CommonDest)
3958 *CommonDest = CaseDest;
3959 // If the destination isn't the common one, abort.
3960 if (CaseDest != *CommonDest)
3961 return false;
3962
3963 // Get the values for this case from phi nodes in the destination block.
3964 BasicBlock::iterator I = (*CommonDest)->begin();
3965 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3966 int Idx = PHI->getBasicBlockIndex(Pred);
3967 if (Idx == -1)
3968 continue;
3969
Hans Wennborg09acdb92012-10-31 15:14:39 +00003970 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3971 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003972 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003973 return false;
3974
3975 // Be conservative about which kinds of constants we support.
3976 if (!ValidLookupTableConstant(ConstVal))
3977 return false;
3978
3979 Res.push_back(std::make_pair(PHI, ConstVal));
3980 }
3981
Hans Wennborgac114a32014-01-12 00:44:41 +00003982 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003983}
3984
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003985// Helper function used to add CaseVal to the list of cases that generate
3986// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003987static void MapCaseToResult(ConstantInt *CaseVal,
3988 SwitchCaseResultVectorTy &UniqueResults,
3989 Constant *Result) {
3990 for (auto &I : UniqueResults) {
3991 if (I.first == Result) {
3992 I.second.push_back(CaseVal);
3993 return;
3994 }
3995 }
3996 UniqueResults.push_back(std::make_pair(Result,
3997 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3998}
3999
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004000// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004001// results for the PHI node of the common destination block for a switch
4002// instruction. Returns false if multiple PHI nodes have been found or if
4003// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004004static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4005 BasicBlock *&CommonDest,
4006 SwitchCaseResultVectorTy &UniqueResults,
4007 Constant *&DefaultResult,
4008 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004009 for (auto &I : SI->cases()) {
4010 ConstantInt *CaseVal = I.getCaseValue();
4011
4012 // Resulting value at phi nodes for this case value.
4013 SwitchCaseResultsTy Results;
4014 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4015 DL))
4016 return false;
4017
4018 // Only one value per case is permitted
4019 if (Results.size() > 1)
4020 return false;
4021 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4022
4023 // Check the PHI consistency.
4024 if (!PHI)
4025 PHI = Results[0].first;
4026 else if (PHI != Results[0].first)
4027 return false;
4028 }
4029 // Find the default result value.
4030 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4031 BasicBlock *DefaultDest = SI->getDefaultDest();
4032 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4033 DL);
4034 // If the default value is not found abort unless the default destination
4035 // is unreachable.
4036 DefaultResult =
4037 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4038 if ((!DefaultResult &&
4039 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4040 return false;
4041
4042 return true;
4043}
4044
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004045// Helper function that checks if it is possible to transform a switch with only
4046// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004047// Example:
4048// switch (a) {
4049// case 10: %0 = icmp eq i32 %a, 10
4050// return 10; %1 = select i1 %0, i32 10, i32 4
4051// case 20: ----> %2 = icmp eq i32 %a, 20
4052// return 2; %3 = select i1 %2, i32 2, i32 %1
4053// default:
4054// return 4;
4055// }
4056static Value *
4057ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4058 Constant *DefaultResult, Value *Condition,
4059 IRBuilder<> &Builder) {
4060 assert(ResultVector.size() == 2 &&
4061 "We should have exactly two unique results at this point");
4062 // If we are selecting between only two cases transform into a simple
4063 // select or a two-way select if default is possible.
4064 if (ResultVector[0].second.size() == 1 &&
4065 ResultVector[1].second.size() == 1) {
4066 ConstantInt *const FirstCase = ResultVector[0].second[0];
4067 ConstantInt *const SecondCase = ResultVector[1].second[0];
4068
4069 bool DefaultCanTrigger = DefaultResult;
4070 Value *SelectValue = ResultVector[1].first;
4071 if (DefaultCanTrigger) {
4072 Value *const ValueCompare =
4073 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4074 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4075 DefaultResult, "switch.select");
4076 }
4077 Value *const ValueCompare =
4078 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4079 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4080 "switch.select");
4081 }
4082
4083 return nullptr;
4084}
4085
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004086// Helper function to cleanup a switch instruction that has been converted into
4087// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004088static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4089 Value *SelectValue,
4090 IRBuilder<> &Builder) {
4091 BasicBlock *SelectBB = SI->getParent();
4092 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4093 PHI->removeIncomingValue(SelectBB);
4094 PHI->addIncoming(SelectValue, SelectBB);
4095
4096 Builder.CreateBr(PHI->getParent());
4097
4098 // Remove the switch.
4099 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4100 BasicBlock *Succ = SI->getSuccessor(i);
4101
4102 if (Succ == PHI->getParent())
4103 continue;
4104 Succ->removePredecessor(SelectBB);
4105 }
4106 SI->eraseFromParent();
4107}
4108
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004109/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004110/// phi nodes in a common successor block with only two different
4111/// constant values, replace the switch with select.
4112static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004113 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004114 Value *const Cond = SI->getCondition();
4115 PHINode *PHI = nullptr;
4116 BasicBlock *CommonDest = nullptr;
4117 Constant *DefaultResult;
4118 SwitchCaseResultVectorTy UniqueResults;
4119 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004120 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4121 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004122 return false;
4123 // Selects choose between maximum two values.
4124 if (UniqueResults.size() != 2)
4125 return false;
4126 assert(PHI != nullptr && "PHI for value select not found");
4127
4128 Builder.SetInsertPoint(SI);
4129 Value *SelectValue = ConvertTwoCaseSwitch(
4130 UniqueResults,
4131 DefaultResult, Cond, Builder);
4132 if (SelectValue) {
4133 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4134 return true;
4135 }
4136 // The switch couldn't be converted into a select.
4137 return false;
4138}
4139
Hans Wennborg776d7122012-09-26 09:34:53 +00004140namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004141 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00004142 class SwitchLookupTable {
4143 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004144 /// Create a lookup table to use as a switch replacement with the contents
4145 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004146 SwitchLookupTable(
4147 Module &M, uint64_t TableSize, ConstantInt *Offset,
4148 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4149 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004150
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004151 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00004152 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00004153 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004154
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004155 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00004156 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004157 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004158 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004159
Hans Wennborg776d7122012-09-26 09:34:53 +00004160 private:
4161 // Depending on the contents of the table, it can be represented in
4162 // different ways.
4163 enum {
4164 // For tables where each element contains the same value, we just have to
4165 // store that single value and return it for each lookup.
4166 SingleValueKind,
4167
Erik Eckstein105374f2014-11-17 09:13:57 +00004168 // For tables where there is a linear relationship between table index
4169 // and values. We calculate the result with a simple multiplication
4170 // and addition instead of a table lookup.
4171 LinearMapKind,
4172
Hans Wennborg39583b82012-09-26 09:44:49 +00004173 // For small tables with integer elements, we can pack them into a bitmap
4174 // that fits into a target-legal register. Values are retrieved by
4175 // shift and mask operations.
4176 BitMapKind,
4177
Hans Wennborg776d7122012-09-26 09:34:53 +00004178 // The table is stored as an array of values. Values are retrieved by load
4179 // instructions from the table.
4180 ArrayKind
4181 } Kind;
4182
4183 // For SingleValueKind, this is the single value.
4184 Constant *SingleValue;
4185
Hans Wennborg39583b82012-09-26 09:44:49 +00004186 // For BitMapKind, this is the bitmap.
4187 ConstantInt *BitMap;
4188 IntegerType *BitMapElementTy;
4189
Erik Eckstein105374f2014-11-17 09:13:57 +00004190 // For LinearMapKind, these are the constants used to derive the value.
4191 ConstantInt *LinearOffset;
4192 ConstantInt *LinearMultiplier;
4193
Hans Wennborg776d7122012-09-26 09:34:53 +00004194 // For ArrayKind, this is the array.
4195 GlobalVariable *Array;
4196 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004197}
Hans Wennborg776d7122012-09-26 09:34:53 +00004198
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004199SwitchLookupTable::SwitchLookupTable(
4200 Module &M, uint64_t TableSize, ConstantInt *Offset,
4201 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4202 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004203 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004204 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004205 assert(Values.size() && "Can't build lookup table without values!");
4206 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004207
4208 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004209 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004210
Hans Wennborgac114a32014-01-12 00:44:41 +00004211 Type *ValueType = Values.begin()->second->getType();
4212
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004213 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00004214 SmallVector<Constant*, 64> TableContents(TableSize);
4215 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4216 ConstantInt *CaseVal = Values[I].first;
4217 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004218 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004219
Hans Wennborg776d7122012-09-26 09:34:53 +00004220 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4221 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004222 TableContents[Idx] = CaseRes;
4223
Hans Wennborg776d7122012-09-26 09:34:53 +00004224 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004225 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004226 }
4227
4228 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004229 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004230 assert(DefaultValue &&
4231 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004232 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004233 for (uint64_t I = 0; I < TableSize; ++I) {
4234 if (!TableContents[I])
4235 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004236 }
4237
Hans Wennborg776d7122012-09-26 09:34:53 +00004238 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004239 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004240 }
4241
Hans Wennborg776d7122012-09-26 09:34:53 +00004242 // If each element in the table contains the same value, we only need to store
4243 // that single value.
4244 if (SingleValue) {
4245 Kind = SingleValueKind;
4246 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004247 }
4248
Erik Eckstein105374f2014-11-17 09:13:57 +00004249 // Check if we can derive the value with a linear transformation from the
4250 // table index.
4251 if (isa<IntegerType>(ValueType)) {
4252 bool LinearMappingPossible = true;
4253 APInt PrevVal;
4254 APInt DistToPrev;
4255 assert(TableSize >= 2 && "Should be a SingleValue table.");
4256 // Check if there is the same distance between two consecutive values.
4257 for (uint64_t I = 0; I < TableSize; ++I) {
4258 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4259 if (!ConstVal) {
4260 // This is an undef. We could deal with it, but undefs in lookup tables
4261 // are very seldom. It's probably not worth the additional complexity.
4262 LinearMappingPossible = false;
4263 break;
4264 }
4265 APInt Val = ConstVal->getValue();
4266 if (I != 0) {
4267 APInt Dist = Val - PrevVal;
4268 if (I == 1) {
4269 DistToPrev = Dist;
4270 } else if (Dist != DistToPrev) {
4271 LinearMappingPossible = false;
4272 break;
4273 }
4274 }
4275 PrevVal = Val;
4276 }
4277 if (LinearMappingPossible) {
4278 LinearOffset = cast<ConstantInt>(TableContents[0]);
4279 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4280 Kind = LinearMapKind;
4281 ++NumLinearMaps;
4282 return;
4283 }
4284 }
4285
Hans Wennborg39583b82012-09-26 09:44:49 +00004286 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004287 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004288 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004289 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4290 for (uint64_t I = TableSize; I > 0; --I) {
4291 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004292 // Insert values into the bitmap. Undef values are set to zero.
4293 if (!isa<UndefValue>(TableContents[I - 1])) {
4294 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4295 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4296 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004297 }
4298 BitMap = ConstantInt::get(M.getContext(), TableInt);
4299 BitMapElementTy = IT;
4300 Kind = BitMapKind;
4301 ++NumBitMaps;
4302 return;
4303 }
4304
Hans Wennborg776d7122012-09-26 09:34:53 +00004305 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004306 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004307 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4308
Hans Wennborg776d7122012-09-26 09:34:53 +00004309 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4310 GlobalVariable::PrivateLinkage,
4311 Initializer,
4312 "switch.table");
4313 Array->setUnnamedAddr(true);
4314 Kind = ArrayKind;
4315}
4316
Manman Ren4d189fb2014-07-24 21:13:20 +00004317Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004318 switch (Kind) {
4319 case SingleValueKind:
4320 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004321 case LinearMapKind: {
4322 // Derive the result value from the input value.
4323 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4324 false, "switch.idx.cast");
4325 if (!LinearMultiplier->isOne())
4326 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4327 if (!LinearOffset->isZero())
4328 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4329 return Result;
4330 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004331 case BitMapKind: {
4332 // Type of the bitmap (e.g. i59).
4333 IntegerType *MapTy = BitMap->getType();
4334
4335 // Cast Index to the same type as the bitmap.
4336 // Note: The Index is <= the number of elements in the table, so
4337 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004338 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004339
4340 // Multiply the shift amount by the element width.
4341 ShiftAmt = Builder.CreateMul(ShiftAmt,
4342 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4343 "switch.shiftamt");
4344
4345 // Shift down.
4346 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4347 "switch.downshift");
4348 // Mask off.
4349 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4350 "switch.masked");
4351 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004352 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004353 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004354 IntegerType *IT = cast<IntegerType>(Index->getType());
4355 uint64_t TableSize = Array->getInitializer()->getType()
4356 ->getArrayNumElements();
4357 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4358 Index = Builder.CreateZExt(Index,
4359 IntegerType::get(IT->getContext(),
4360 IT->getBitWidth() + 1),
4361 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004362
Hans Wennborg776d7122012-09-26 09:34:53 +00004363 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004364 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4365 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004366 return Builder.CreateLoad(GEP, "switch.load");
4367 }
4368 }
4369 llvm_unreachable("Unknown lookup table kind!");
4370}
4371
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004372bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004373 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004374 Type *ElementType) {
4375 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004376 if (!IT)
4377 return false;
4378 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4379 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004380
4381 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4382 if (TableSize >= UINT_MAX/IT->getBitWidth())
4383 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004384 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004385}
4386
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004387/// Determine whether a lookup table should be built for this switch, based on
4388/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004389static bool
4390ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4391 const TargetTransformInfo &TTI, const DataLayout &DL,
4392 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004393 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4394 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004395
Chandler Carruth77d433d2012-11-30 09:26:25 +00004396 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004397 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004398 for (const auto &I : ResultTypes) {
4399 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004400
4401 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004402 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004403
4404 // Saturate this flag to false.
4405 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004406 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004407
4408 // If both flags saturate, we're done. NOTE: This *only* works with
4409 // saturating flags, and all flags have to saturate first due to the
4410 // non-deterministic behavior of iterating over a dense map.
4411 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004412 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004413 }
Evan Cheng65df8082012-11-30 02:02:42 +00004414
Chandler Carruth77d433d2012-11-30 09:26:25 +00004415 // If each table would fit in a register, we should build it anyway.
4416 if (AllTablesFitInRegister)
4417 return true;
4418
4419 // Don't build a table that doesn't fit in-register if it has illegal types.
4420 if (HasIllegalType)
4421 return false;
4422
4423 // The table density should be at least 40%. This is the same criterion as for
4424 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4425 // FIXME: Find the best cut-off.
4426 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004427}
4428
Erik Eckstein0d86c762014-11-27 15:13:14 +00004429/// Try to reuse the switch table index compare. Following pattern:
4430/// \code
4431/// if (idx < tablesize)
4432/// r = table[idx]; // table does not contain default_value
4433/// else
4434/// r = default_value;
4435/// if (r != default_value)
4436/// ...
4437/// \endcode
4438/// Is optimized to:
4439/// \code
4440/// cond = idx < tablesize;
4441/// if (cond)
4442/// r = table[idx];
4443/// else
4444/// r = default_value;
4445/// if (cond)
4446/// ...
4447/// \endcode
4448/// Jump threading will then eliminate the second if(cond).
4449static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4450 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4451 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4452
4453 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4454 if (!CmpInst)
4455 return;
4456
4457 // We require that the compare is in the same block as the phi so that jump
4458 // threading can do its work afterwards.
4459 if (CmpInst->getParent() != PhiBlock)
4460 return;
4461
4462 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4463 if (!CmpOp1)
4464 return;
4465
4466 Value *RangeCmp = RangeCheckBranch->getCondition();
4467 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4468 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4469
4470 // Check if the compare with the default value is constant true or false.
4471 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4472 DefaultValue, CmpOp1, true);
4473 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4474 return;
4475
4476 // Check if the compare with the case values is distinct from the default
4477 // compare result.
4478 for (auto ValuePair : Values) {
4479 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4480 ValuePair.second, CmpOp1, true);
4481 if (!CaseConst || CaseConst == DefaultConst)
4482 return;
4483 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4484 "Expect true or false as compare result.");
4485 }
James Molloy4de84dd2015-11-04 15:28:04 +00004486
Erik Eckstein0d86c762014-11-27 15:13:14 +00004487 // Check if the branch instruction dominates the phi node. It's a simple
4488 // dominance check, but sufficient for our needs.
4489 // Although this check is invariant in the calling loops, it's better to do it
4490 // at this late stage. Practically we do it at most once for a switch.
4491 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4492 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4493 BasicBlock *Pred = *PI;
4494 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4495 return;
4496 }
4497
4498 if (DefaultConst == FalseConst) {
4499 // The compare yields the same result. We can replace it.
4500 CmpInst->replaceAllUsesWith(RangeCmp);
4501 ++NumTableCmpReuses;
4502 } else {
4503 // The compare yields the same result, just inverted. We can replace it.
4504 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4505 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4506 RangeCheckBranch);
4507 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4508 ++NumTableCmpReuses;
4509 }
4510}
4511
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004512/// If the switch is only used to initialize one or more phi nodes in a common
4513/// successor block with different constant values, replace the switch with
4514/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004515static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4516 const DataLayout &DL,
4517 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004518 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004519
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004520 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004521 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004522 return false;
4523
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004524 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4525 // split off a dense part and build a lookup table for that.
4526
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004527 // FIXME: This creates arrays of GEPs to constant strings, which means each
4528 // GEP needs a runtime relocation in PIC code. We should just build one big
4529 // string and lookup indices into that.
4530
Hans Wennborg4744ac12014-01-15 05:00:27 +00004531 // Ignore switches with less than three cases. Lookup tables will not make them
4532 // faster, so we don't analyze them.
4533 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004534 return false;
4535
4536 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004537 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004538 assert(SI->case_begin() != SI->case_end());
4539 SwitchInst::CaseIt CI = SI->case_begin();
4540 ConstantInt *MinCaseVal = CI.getCaseValue();
4541 ConstantInt *MaxCaseVal = CI.getCaseValue();
4542
Craig Topperf40110f2014-04-25 05:29:35 +00004543 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004544 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004545 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4546 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4547 SmallDenseMap<PHINode*, Type*> ResultTypes;
4548 SmallVector<PHINode*, 4> PHIs;
4549
4550 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4551 ConstantInt *CaseVal = CI.getCaseValue();
4552 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4553 MinCaseVal = CaseVal;
4554 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4555 MaxCaseVal = CaseVal;
4556
4557 // Resulting value at phi nodes for this case value.
4558 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4559 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004560 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004561 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004562 return false;
4563
4564 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004565 for (const auto &I : Results) {
4566 PHINode *PHI = I.first;
4567 Constant *Value = I.second;
4568 if (!ResultLists.count(PHI))
4569 PHIs.push_back(PHI);
4570 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004571 }
4572 }
4573
Hans Wennborgac114a32014-01-12 00:44:41 +00004574 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004575 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004576 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4577 }
4578
4579 uint64_t NumResults = ResultLists[PHIs[0]].size();
4580 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4581 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4582 bool TableHasHoles = (NumResults < TableSize);
4583
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004584 // If the table has holes, we need a constant result for the default case
4585 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004586 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004587 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004588 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004589
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004590 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4591 if (NeedMask) {
4592 // As an extra penalty for the validity test we require more cases.
4593 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4594 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004595 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004596 return false;
4597 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004598
Hans Wennborga6a11a92014-11-18 02:37:11 +00004599 for (const auto &I : DefaultResultsList) {
4600 PHINode *PHI = I.first;
4601 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004602 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004603 }
4604
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004605 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004606 return false;
4607
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004608 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004609 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004610 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4611 "switch.lookup",
4612 CommonDest->getParent(),
4613 CommonDest);
4614
Michael Gottesmanc024f322013-10-20 07:04:37 +00004615 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004616 Builder.SetInsertPoint(SI);
4617 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4618 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004619
4620 // Compute the maximum table size representable by the integer type we are
4621 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004622 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004623 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004624 assert(MaxTableSize >= TableSize &&
4625 "It is impossible for a switch to have more entries than the max "
4626 "representable value of its input integer type's size.");
4627
Hans Wennborgb64cb272015-01-26 19:52:34 +00004628 // If the default destination is unreachable, or if the lookup table covers
4629 // all values of the conditional variable, branch directly to the lookup table
4630 // BB. Otherwise, check that the condition is within the case range.
4631 const bool DefaultIsReachable =
4632 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4633 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004634 BranchInst *RangeCheckBranch = nullptr;
4635
Hans Wennborgb64cb272015-01-26 19:52:34 +00004636 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004637 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004638 // Note: We call removeProdecessor later since we need to be able to get the
4639 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004640 } else {
4641 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004642 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004643 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004644 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004645
4646 // Populate the BB that does the lookups.
4647 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004648
4649 if (NeedMask) {
4650 // Before doing the lookup we do the hole check.
4651 // The LookupBB is therefore re-purposed to do the hole check
4652 // and we create a new LookupBB.
4653 BasicBlock *MaskBB = LookupBB;
4654 MaskBB->setName("switch.hole_check");
4655 LookupBB = BasicBlock::Create(Mod.getContext(),
4656 "switch.lookup",
4657 CommonDest->getParent(),
4658 CommonDest);
4659
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004660 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4661 // unnecessary illegal types.
4662 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4663 APInt MaskInt(TableSizePowOf2, 0);
4664 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004665 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004666 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4667 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4668 uint64_t Idx = (ResultList[I].first->getValue() -
4669 MinCaseVal->getValue()).getLimitedValue();
4670 MaskInt |= One << Idx;
4671 }
4672 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4673
4674 // Get the TableIndex'th bit of the bitmask.
4675 // If this bit is 0 (meaning hole) jump to the default destination,
4676 // else continue with table lookup.
4677 IntegerType *MapTy = TableMask->getType();
4678 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4679 "switch.maskindex");
4680 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4681 "switch.shifted");
4682 Value *LoBit = Builder.CreateTrunc(Shifted,
4683 Type::getInt1Ty(Mod.getContext()),
4684 "switch.lobit");
4685 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4686
4687 Builder.SetInsertPoint(LookupBB);
4688 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4689 }
4690
Hans Wennborg86ac6302015-04-24 20:57:56 +00004691 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4692 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4693 // do not delete PHINodes here.
4694 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4695 /*DontDeleteUselessPHIs=*/true);
4696 }
4697
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004698 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004699 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4700 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004701 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004702
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004703 // If using a bitmask, use any value to fill the lookup table holes.
4704 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004705 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004706
Manman Ren4d189fb2014-07-24 21:13:20 +00004707 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004708
Hans Wennborgf744fa92012-09-19 14:24:21 +00004709 // If the result is used to return immediately from the function, we want to
4710 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004711 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4712 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004713 Builder.CreateRet(Result);
4714 ReturnedEarly = true;
4715 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004716 }
4717
Erik Eckstein0d86c762014-11-27 15:13:14 +00004718 // Do a small peephole optimization: re-use the switch table compare if
4719 // possible.
4720 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4721 BasicBlock *PhiBlock = PHI->getParent();
4722 // Search for compare instructions which use the phi.
4723 for (auto *User : PHI->users()) {
4724 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4725 }
4726 }
4727
Hans Wennborgf744fa92012-09-19 14:24:21 +00004728 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004729 }
4730
4731 if (!ReturnedEarly)
4732 Builder.CreateBr(CommonDest);
4733
4734 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004735 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004736 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004737
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004738 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004739 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004740 Succ->removePredecessor(SI->getParent());
4741 }
4742 SI->eraseFromParent();
4743
4744 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004745 if (NeedMask)
4746 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004747 return true;
4748}
4749
Devang Patela7ec47d2011-05-18 20:35:38 +00004750bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004751 BasicBlock *BB = SI->getParent();
4752
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004753 if (isValueEqualityComparison(SI)) {
4754 // If we only have one predecessor, and if it is a branch on this value,
4755 // see if that predecessor totally determines the outcome of this switch.
4756 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4757 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004758 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004759
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004760 Value *Cond = SI->getCondition();
4761 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4762 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004763 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004764
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004765 // If the block only contains the switch, see if we can fold the block
4766 // away into any preds.
4767 BasicBlock::iterator BBI = BB->begin();
4768 // Ignore dbg intrinsics.
4769 while (isa<DbgInfoIntrinsic>(BBI))
4770 ++BBI;
4771 if (SI == &*BBI)
4772 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004773 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004774 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004775
4776 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004777 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004778 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004779
4780 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004781 if (EliminateDeadSwitchCases(SI, AC, DL))
4782 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004783
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004784 if (SwitchToSelect(SI, Builder, AC, DL))
4785 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004786
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004787 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004788 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004789
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004790 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4791 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004792
Chris Lattner25c3af32010-12-13 06:25:44 +00004793 return false;
4794}
4795
4796bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4797 BasicBlock *BB = IBI->getParent();
4798 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004799
Chris Lattner25c3af32010-12-13 06:25:44 +00004800 // Eliminate redundant destinations.
4801 SmallPtrSet<Value *, 8> Succs;
4802 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4803 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004804 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004805 Dest->removePredecessor(BB);
4806 IBI->removeDestination(i);
4807 --i; --e;
4808 Changed = true;
4809 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004810 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004811
4812 if (IBI->getNumDestinations() == 0) {
4813 // If the indirectbr has no successors, change it to unreachable.
4814 new UnreachableInst(IBI->getContext(), IBI);
4815 EraseTerminatorInstAndDCECond(IBI);
4816 return true;
4817 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004818
Chris Lattner25c3af32010-12-13 06:25:44 +00004819 if (IBI->getNumDestinations() == 1) {
4820 // If the indirectbr has one successor, change it to a direct branch.
4821 BranchInst::Create(IBI->getDestination(0), IBI);
4822 EraseTerminatorInstAndDCECond(IBI);
4823 return true;
4824 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004825
Chris Lattner25c3af32010-12-13 06:25:44 +00004826 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4827 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004828 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004829 }
4830 return Changed;
4831}
4832
Philip Reames2b969d72015-03-24 22:28:45 +00004833/// Given an block with only a single landing pad and a unconditional branch
4834/// try to find another basic block which this one can be merged with. This
4835/// handles cases where we have multiple invokes with unique landing pads, but
4836/// a shared handler.
4837///
4838/// We specifically choose to not worry about merging non-empty blocks
4839/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4840/// practice, the optimizer produces empty landing pad blocks quite frequently
4841/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4842/// sinking in this file)
4843///
4844/// This is primarily a code size optimization. We need to avoid performing
4845/// any transform which might inhibit optimization (such as our ability to
4846/// specialize a particular handler via tail commoning). We do this by not
4847/// merging any blocks which require us to introduce a phi. Since the same
4848/// values are flowing through both blocks, we don't loose any ability to
4849/// specialize. If anything, we make such specialization more likely.
4850///
4851/// TODO - This transformation could remove entries from a phi in the target
4852/// block when the inputs in the phi are the same for the two blocks being
4853/// merged. In some cases, this could result in removal of the PHI entirely.
4854static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4855 BasicBlock *BB) {
4856 auto Succ = BB->getUniqueSuccessor();
4857 assert(Succ);
4858 // If there's a phi in the successor block, we'd likely have to introduce
4859 // a phi into the merged landing pad block.
4860 if (isa<PHINode>(*Succ->begin()))
4861 return false;
4862
4863 for (BasicBlock *OtherPred : predecessors(Succ)) {
4864 if (BB == OtherPred)
4865 continue;
4866 BasicBlock::iterator I = OtherPred->begin();
4867 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4868 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4869 continue;
4870 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4871 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4872 if (!BI2 || !BI2->isIdenticalTo(BI))
4873 continue;
4874
4875 // We've found an identical block. Update our predeccessors to take that
4876 // path instead and make ourselves dead.
4877 SmallSet<BasicBlock *, 16> Preds;
4878 Preds.insert(pred_begin(BB), pred_end(BB));
4879 for (BasicBlock *Pred : Preds) {
4880 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4881 assert(II->getNormalDest() != BB &&
4882 II->getUnwindDest() == BB && "unexpected successor");
4883 II->setUnwindDest(OtherPred);
4884 }
4885
4886 // The debug info in OtherPred doesn't cover the merged control flow that
4887 // used to go through BB. We need to delete it or update it.
4888 for (auto I = OtherPred->begin(), E = OtherPred->end();
4889 I != E;) {
4890 Instruction &Inst = *I; I++;
4891 if (isa<DbgInfoIntrinsic>(Inst))
4892 Inst.eraseFromParent();
4893 }
4894
4895 SmallSet<BasicBlock *, 16> Succs;
4896 Succs.insert(succ_begin(BB), succ_end(BB));
4897 for (BasicBlock *Succ : Succs) {
4898 Succ->removePredecessor(BB);
4899 }
4900
4901 IRBuilder<> Builder(BI);
4902 Builder.CreateUnreachable();
4903 BI->eraseFromParent();
4904 return true;
4905 }
4906 return false;
4907}
4908
Devang Patel767f6932011-05-18 18:28:48 +00004909bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004910 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004911
Manman Ren93ab6492012-09-20 22:37:36 +00004912 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4913 return true;
4914
Chris Lattner25c3af32010-12-13 06:25:44 +00004915 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004916 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004917 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4918 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4919 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004920
Chris Lattner25c3af32010-12-13 06:25:44 +00004921 // If the only instruction in the block is a seteq/setne comparison
4922 // against a constant, try to simplify the block.
4923 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4924 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4925 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4926 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004927 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004928 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4929 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004930 return true;
4931 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004932
Philip Reames2b969d72015-03-24 22:28:45 +00004933 // See if we can merge an empty landing pad block with another which is
4934 // equivalent.
4935 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4936 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4937 if (I->isTerminator() &&
4938 TryToMergeLandingPad(LPad, BI, BB))
4939 return true;
4940 }
4941
Manman Rend33f4ef2012-06-13 05:43:29 +00004942 // If this basic block is ONLY a compare and a branch, and if a predecessor
4943 // branches to us and our successor, fold the comparison into the
4944 // predecessor and use logical operations to update the incoming value
4945 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004946 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4947 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004948 return false;
4949}
4950
James Molloy4de84dd2015-11-04 15:28:04 +00004951static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
4952 BasicBlock *PredPred = nullptr;
4953 for (auto *P : predecessors(BB)) {
4954 BasicBlock *PPred = P->getSinglePredecessor();
4955 if (!PPred || (PredPred && PredPred != PPred))
4956 return nullptr;
4957 PredPred = PPred;
4958 }
4959 return PredPred;
4960}
Chris Lattner25c3af32010-12-13 06:25:44 +00004961
Devang Patela7ec47d2011-05-18 20:35:38 +00004962bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004963 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004964
Chris Lattner25c3af32010-12-13 06:25:44 +00004965 // Conditional branch
4966 if (isValueEqualityComparison(BI)) {
4967 // If we only have one predecessor, and if it is a branch on this value,
4968 // see if that predecessor totally determines the outcome of this
4969 // switch.
4970 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004971 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004972 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004973
Chris Lattner25c3af32010-12-13 06:25:44 +00004974 // This block must be empty, except for the setcond inst, if it exists.
4975 // Ignore dbg intrinsics.
4976 BasicBlock::iterator I = BB->begin();
4977 // Ignore dbg intrinsics.
4978 while (isa<DbgInfoIntrinsic>(I))
4979 ++I;
4980 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004981 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004982 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004983 } else if (&*I == cast<Instruction>(BI->getCondition())){
4984 ++I;
4985 // Ignore dbg intrinsics.
4986 while (isa<DbgInfoIntrinsic>(I))
4987 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004988 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004989 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004990 }
4991 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004992
Chris Lattner25c3af32010-12-13 06:25:44 +00004993 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004994 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004995 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004996
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004997 // If this basic block is ONLY a compare and a branch, and if a predecessor
4998 // branches to us and one of our successors, fold the comparison into the
4999 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005000 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5001 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005002
Chris Lattner25c3af32010-12-13 06:25:44 +00005003 // We have a conditional branch to two blocks that are only reachable
5004 // from BI. We know that the condbr dominates the two blocks, so see if
5005 // there is any identical code in the "then" and "else" blocks. If so, we
5006 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005007 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5008 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005009 if (HoistThenElseCodeToIf(BI, TTI))
5010 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005011 } else {
5012 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005013 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005014 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5015 if (Succ0TI->getNumSuccessors() == 1 &&
5016 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005017 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5018 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005019 }
Craig Topperf40110f2014-04-25 05:29:35 +00005020 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005021 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005022 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005023 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5024 if (Succ1TI->getNumSuccessors() == 1 &&
5025 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005026 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5027 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005028 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005029
Chris Lattner25c3af32010-12-13 06:25:44 +00005030 // If this is a branch on a phi node in the current block, thread control
5031 // through this block if any PHI node entries are constants.
5032 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5033 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005034 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005035 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005036
Chris Lattner25c3af32010-12-13 06:25:44 +00005037 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005038 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5039 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005040 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005041 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005042 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005043
James Molloy4de84dd2015-11-04 15:28:04 +00005044 // Look for diamond patterns.
5045 if (MergeCondStores)
5046 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5047 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5048 if (PBI != BI && PBI->isConditional())
5049 if (mergeConditionalStores(PBI, BI))
5050 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5051
Chris Lattner25c3af32010-12-13 06:25:44 +00005052 return false;
5053}
5054
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005055/// Check if passing a value to an instruction will cause undefined behavior.
5056static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5057 Constant *C = dyn_cast<Constant>(V);
5058 if (!C)
5059 return false;
5060
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005061 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005062 return false;
5063
5064 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005065 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005066 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005067
5068 // Now make sure that there are no instructions in between that can alter
5069 // control flow (eg. calls)
5070 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005071 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005072 return false;
5073
5074 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5075 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5076 if (GEP->getPointerOperand() == I)
5077 return passingValueIsAlwaysUndefined(V, GEP);
5078
5079 // Look through bitcasts.
5080 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5081 return passingValueIsAlwaysUndefined(V, BC);
5082
Benjamin Kramer0655b782011-08-26 02:25:55 +00005083 // Load from null is undefined.
5084 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005085 if (!LI->isVolatile())
5086 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005087
Benjamin Kramer0655b782011-08-26 02:25:55 +00005088 // Store to null is undefined.
5089 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005090 if (!SI->isVolatile())
5091 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005092 }
5093 return false;
5094}
5095
5096/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005097/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005098static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5099 for (BasicBlock::iterator i = BB->begin();
5100 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5101 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5102 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5103 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5104 IRBuilder<> Builder(T);
5105 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5106 BB->removePredecessor(PHI->getIncomingBlock(i));
5107 // Turn uncoditional branches into unreachables and remove the dead
5108 // destination from conditional branches.
5109 if (BI->isUnconditional())
5110 Builder.CreateUnreachable();
5111 else
5112 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5113 BI->getSuccessor(0));
5114 BI->eraseFromParent();
5115 return true;
5116 }
5117 // TODO: SwitchInst.
5118 }
5119
5120 return false;
5121}
5122
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005123bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005124 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005125
Chris Lattnerd7beca32010-12-14 06:17:25 +00005126 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005127 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005128
Dan Gohman4a63fad2010-08-14 00:29:42 +00005129 // Remove basic blocks that have no predecessors (except the entry block)...
5130 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00005131 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00005132 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005133 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00005134 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00005135 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00005136 return true;
5137 }
5138
Chris Lattner031340a2003-08-17 19:41:53 +00005139 // Check to see if we can constant propagate this terminator instruction
5140 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005141 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005142
Dan Gohman1a951062009-10-30 22:39:04 +00005143 // Check for and eliminate duplicate PHI nodes in this block.
5144 Changed |= EliminateDuplicatePHINodes(BB);
5145
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005146 // Check for and remove branches that will always cause undefined behavior.
5147 Changed |= removeUndefIntroducingPredecessor(BB);
5148
Chris Lattner2e3832d2010-12-13 05:10:48 +00005149 // Merge basic blocks into their predecessor if there is only one distinct
5150 // pred, and if there is only one distinct successor of the predecessor, and
5151 // if there are no PHI nodes.
5152 //
5153 if (MergeBlockIntoPredecessor(BB))
5154 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005155
Devang Patel15ad6762011-05-18 18:01:27 +00005156 IRBuilder<> Builder(BB);
5157
Dan Gohman20af5a02008-03-11 21:53:06 +00005158 // If there is a trivial two-entry PHI node in this basic block, and we can
5159 // eliminate it, do so now.
5160 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5161 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005162 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005163
Devang Patela7ec47d2011-05-18 20:35:38 +00005164 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005165 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005166 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00005167 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005168 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00005169 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005170 }
5171 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00005172 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005173 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5174 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005175 } else if (CleanupReturnInst *RI =
5176 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5177 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005178 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00005179 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005180 } else if (UnreachableInst *UI =
5181 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5182 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005183 } else if (IndirectBrInst *IBI =
5184 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5185 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005186 }
5187
Chris Lattner031340a2003-08-17 19:41:53 +00005188 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005189}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005190
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005191/// This function is used to do simplification of a CFG.
5192/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005193/// eliminates unreachable basic blocks, and does other "peephole" optimization
5194/// of the CFG. It returns true if a modification was made.
5195///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005196bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005197 unsigned BonusInstThreshold, AssumptionCache *AC) {
5198 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5199 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005200}