blob: 0277ed34f844817754a0a20b21c96520b498eb7b [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000021#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000038#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000042#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000046#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000047#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000048#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000049#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000051using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000052using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "simplifycfg"
55
James Molloy1b6207e2015-02-13 10:48:30 +000056// Chosen as 2 so as to be cheap, but still to have enough power to fold
57// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
58// To catch this, we need to fold a compare and a select, hence '2' being the
59// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000060static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000061PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
62 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000063
Evan Chengd983eba2011-01-29 04:46:23 +000064static cl::opt<bool>
65DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
66 cl::desc("Duplicate return instructions into unconditional branches"));
67
Manman Ren93ab6492012-09-20 22:37:36 +000068static cl::opt<bool>
69SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
70 cl::desc("Sink common instructions down to the end block"));
71
Alp Tokercb402912014-01-24 17:20:08 +000072static cl::opt<bool> HoistCondStores(
73 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
74 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000075
Hans Wennborg39583b82012-09-26 09:44:49 +000076STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000077STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000078STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000079STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000080STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000081STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000082STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000083
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000084namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000085 // The first field contains the value that the switch produces when a certain
86 // case group is selected, and the second field is a vector containing the cases
87 // composing the case group.
88 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
89 SwitchCaseResultVectorTy;
90 // The first field contains the phi node that generates a result of the switch
91 // and the second field contains the value generated for a certain case in the switch
92 // for that PHI.
93 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
94
Eric Christopherb65acc62012-07-02 23:22:21 +000095 /// ValueEqualityComparisonCase - Represents a case of a switch.
96 struct ValueEqualityComparisonCase {
97 ConstantInt *Value;
98 BasicBlock *Dest;
99
100 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
101 : Value(Value), Dest(Dest) {}
102
103 bool operator<(ValueEqualityComparisonCase RHS) const {
104 // Comparing pointers is ok as we only rely on the order for uniquing.
105 return Value < RHS.Value;
106 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000107
108 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000109 };
110
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000111class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000112 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000113 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000114 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000115 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000116 Value *isValueEqualityComparison(TerminatorInst *TI);
117 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000118 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000119 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000120 BasicBlock *Pred,
121 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000122 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
123 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000124
Devang Pateldd14e0f2011-05-18 21:33:11 +0000125 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000126 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000127 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000128 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000129 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000130 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000131 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000132 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000133
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000134public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
136 unsigned BonusInstThreshold, AssumptionCache *AC)
137 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000138 bool run(BasicBlock *BB);
139};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000140}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000141
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000142/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000143/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000144static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
145 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000146
Chris Lattner76dc2042005-08-03 00:19:45 +0000147 // It is not safe to merge these two switch instructions if they have a common
148 // successor, and if that successor has a PHI node, and if *that* PHI node has
149 // conflicting incoming values from the two switch blocks.
150 BasicBlock *SI1BB = SI1->getParent();
151 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000152 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000153
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000154 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
155 if (SI1Succs.count(*I))
156 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000157 isa<PHINode>(BBI); ++BBI) {
158 PHINode *PN = cast<PHINode>(BBI);
159 if (PN->getIncomingValueForBlock(SI1BB) !=
160 PN->getIncomingValueForBlock(SI2BB))
161 return false;
162 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000163
Chris Lattner76dc2042005-08-03 00:19:45 +0000164 return true;
165}
166
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000167/// Return true if it is safe and profitable to merge these two terminator
168/// instructions together, where SI1 is an unconditional branch. PhiNodes will
169/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000170static bool isProfitableToFoldUnconditional(BranchInst *SI1,
171 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000172 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000173 SmallVectorImpl<PHINode*> &PhiNodes) {
174 if (SI1 == SI2) return false; // Can't merge with self!
175 assert(SI1->isUnconditional() && SI2->isConditional());
176
177 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000178 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000179 // 1> We have a constant incoming value for the conditional branch;
180 // 2> We have "Cond" as the incoming value for the unconditional branch;
181 // 3> SI2->getCondition() and Cond have same operands.
182 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
183 if (!Ci2) return false;
184 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
185 Cond->getOperand(1) == Ci2->getOperand(1)) &&
186 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
187 Cond->getOperand(1) == Ci2->getOperand(0)))
188 return false;
189
190 BasicBlock *SI1BB = SI1->getParent();
191 BasicBlock *SI2BB = SI2->getParent();
192 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000193 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
194 if (SI1Succs.count(*I))
195 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000196 isa<PHINode>(BBI); ++BBI) {
197 PHINode *PN = cast<PHINode>(BBI);
198 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000199 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000200 return false;
201 PhiNodes.push_back(PN);
202 }
203 return true;
204}
205
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000206/// Update PHI nodes in Succ to indicate that there will now be entries in it
207/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
208/// will be the same as those coming in from ExistPred, an existing predecessor
209/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000210static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
211 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000212 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000213
Chris Lattner80b03a12008-07-13 22:23:11 +0000214 PHINode *PN;
215 for (BasicBlock::iterator I = Succ->begin();
216 (PN = dyn_cast<PHINode>(I)); ++I)
217 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000218}
219
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000220/// Compute an abstract "cost" of speculating the given instruction,
221/// which is assumed to be safe to speculate. TCC_Free means cheap,
222/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000223/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000225 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000226 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000227 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000228 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000229}
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000230/// If we have a merge point of an "if condition" as accepted above,
231/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000232/// don't handle the true generality of domination here, just a special case
233/// which works well enough for us.
234///
235/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000236/// see if V (which must be an instruction) and its recursive operands
237/// that do not dominate BB have a combined cost lower than CostRemaining and
238/// are non-trapping. If both are true, the instruction is inserted into the
239/// set and true is returned.
240///
241/// The cost for most non-trapping instructions is defined as 1 except for
242/// Select whose cost is 2.
243///
244/// After this function returns, CostRemaining is decreased by the cost of
245/// V plus its non-dominating operands. If that cost is greater than
246/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000247static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000248 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000249 unsigned &CostRemaining,
James Molloy7c336572015-02-11 12:15:41 +0000250 const TargetTransformInfo &TTI) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000251 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000252 if (!I) {
253 // Non-instructions all dominate instructions, but not all constantexprs
254 // can be executed unconditionally.
255 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
256 if (C->canTrap())
257 return false;
258 return true;
259 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000260 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000261
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000262 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000263 // the bottom of this block.
264 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000265
Chris Lattner0aa56562004-04-09 22:50:22 +0000266 // If this instruction is defined in a block that contains an unconditional
267 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000268 // statement". If not, it definitely dominates the region.
269 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000270 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000271 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000272
Chris Lattner9ac168d2010-12-14 07:41:39 +0000273 // If we aren't allowing aggressive promotion anymore, then don't consider
274 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000275 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000276
Peter Collingbournee3511e12011-04-29 18:47:31 +0000277 // If we have seen this instruction before, don't count it again.
278 if (AggressiveInsts->count(I)) return true;
279
Chris Lattner9ac168d2010-12-14 07:41:39 +0000280 // Okay, it looks like the instruction IS in the "condition". Check to
281 // see if it's a cheap instruction to unconditionally compute, and if it
282 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000283 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000284 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000285
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000286 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000287
Peter Collingbournee3511e12011-04-29 18:47:31 +0000288 if (Cost > CostRemaining)
289 return false;
290
291 CostRemaining -= Cost;
292
293 // Okay, we can only really hoist these out if their operands do
294 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000295 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000297 return false;
298 // Okay, it's safe to do this! Remember this instruction.
299 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000300 return true;
301}
Chris Lattner466a0492002-05-21 20:50:24 +0000302
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000303/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000304/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000305static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000306 // Normal constant int.
307 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000308 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000309 return CI;
310
311 // This is some kind of pointer constant. Turn it into a pointer-sized
312 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000313 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000314
315 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
316 if (isa<ConstantPointerNull>(V))
317 return ConstantInt::get(PtrTy, 0);
318
319 // IntToPtr const int.
320 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
321 if (CE->getOpcode() == Instruction::IntToPtr)
322 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
323 // The constant is very likely to have the right type already.
324 if (CI->getType() == PtrTy)
325 return CI;
326 else
327 return cast<ConstantInt>
328 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
329 }
Craig Topperf40110f2014-04-25 05:29:35 +0000330 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000331}
332
Mehdi Aminiffd01002014-11-20 22:40:25 +0000333namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000334
Mehdi Aminiffd01002014-11-20 22:40:25 +0000335/// Given a chain of or (||) or and (&&) comparison of a value against a
336/// constant, this will try to recover the information required for a switch
337/// structure.
338/// It will depth-first traverse the chain of comparison, seeking for patterns
339/// like %a == 12 or %a < 4 and combine them to produce a set of integer
340/// representing the different cases for the switch.
341/// Note that if the chain is composed of '||' it will build the set of elements
342/// that matches the comparisons (i.e. any of this value validate the chain)
343/// while for a chain of '&&' it will build the set elements that make the test
344/// fail.
345struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000346 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000347 Value *CompValue; /// Value found for the switch comparison
348 Value *Extra; /// Extra clause to be checked before the switch
349 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
350 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000351
Mehdi Aminiffd01002014-11-20 22:40:25 +0000352 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
354 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
355 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000356 }
357
Mehdi Aminiffd01002014-11-20 22:40:25 +0000358 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000359 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000360 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000361 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000362
Mehdi Aminiffd01002014-11-20 22:40:25 +0000363private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000364
Mehdi Aminiffd01002014-11-20 22:40:25 +0000365 /// Try to set the current value used for the comparison, it succeeds only if
366 /// it wasn't set before or if the new value is the same as the old one
367 bool setValueOnce(Value *NewVal) {
368 if(CompValue && CompValue != NewVal) return false;
369 CompValue = NewVal;
370 return (CompValue != nullptr);
371 }
372
373 /// Try to match Instruction "I" as a comparison against a constant and
374 /// populates the array Vals with the set of values that match (or do not
375 /// match depending on isEQ).
376 /// Return false on failure. On success, the Value the comparison matched
377 /// against is placed in CompValue.
378 /// If CompValue is already set, the function is expected to fail if a match
379 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000381 // If this is an icmp against a constant, handle this as one of the cases.
382 ICmpInst *ICI;
383 ConstantInt *C;
384 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
385 (C = GetConstantInt(I->getOperand(1), DL)))) {
386 return false;
387 }
388
389 Value *RHSVal;
390 ConstantInt *RHSC;
391
392 // Pattern match a special case
393 // (x & ~2^x) == y --> x == y || x == y|2^x
394 // This undoes a transformation done by instcombine to fuse 2 compares.
395 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
396 if (match(ICI->getOperand(0),
397 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
398 APInt Not = ~RHSC->getValue();
399 if (Not.isPowerOf2()) {
400 // If we already have a value for the switch, it has to match!
401 if(!setValueOnce(RHSVal))
402 return false;
403
404 Vals.push_back(C);
405 Vals.push_back(ConstantInt::get(C->getContext(),
406 C->getValue() | Not));
407 UsedICmps++;
408 return true;
409 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000410 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000411
412 // If we already have a value for the switch, it has to match!
413 if(!setValueOnce(ICI->getOperand(0)))
414 return false;
415
416 UsedICmps++;
417 Vals.push_back(C);
418 return ICI->getOperand(0);
419 }
420
421 // 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 +0000422 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
423 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000424
425 // Shift the range if the compare is fed by an add. This is the range
426 // compare idiom as emitted by instcombine.
427 Value *CandidateVal = I->getOperand(0);
428 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
429 Span = Span.subtract(RHSC->getValue());
430 CandidateVal = RHSVal;
431 }
432
433 // If this is an and/!= check, then we are looking to build the set of
434 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
435 // x != 0 && x != 1.
436 if (!isEQ)
437 Span = Span.inverse();
438
439 // If there are a ton of values, we don't want to make a ginormous switch.
440 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
441 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000442 }
443
444 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000445 if(!setValueOnce(CandidateVal))
446 return false;
447
448 // Add all values from the range to the set
449 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
450 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000451
452 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000453 return true;
454
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000455 }
456
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000457 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000458 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
459 /// the value being compared, and stick the list constants into the Vals
460 /// vector.
461 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000462 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000463 Instruction *I = dyn_cast<Instruction>(V);
464 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000465
Mehdi Aminiffd01002014-11-20 22:40:25 +0000466 // Keep a stack (SmallVector for efficiency) for depth-first traversal
467 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000468
Mehdi Aminiffd01002014-11-20 22:40:25 +0000469 // Initialize
470 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000471
Mehdi Aminiffd01002014-11-20 22:40:25 +0000472 while(!DFT.empty()) {
473 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000474
Mehdi Aminiffd01002014-11-20 22:40:25 +0000475 if (Instruction *I = dyn_cast<Instruction>(V)) {
476 // If it is a || (or && depending on isEQ), process the operands.
477 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
478 DFT.push_back(I->getOperand(1));
479 DFT.push_back(I->getOperand(0));
480 continue;
481 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000482
Mehdi Aminiffd01002014-11-20 22:40:25 +0000483 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000484 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000485 // Match succeed, continue the loop
486 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000487 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000488
Mehdi Aminiffd01002014-11-20 22:40:25 +0000489 // One element of the sequence of || (or &&) could not be match as a
490 // comparison against the same value as the others.
491 // We allow only one "Extra" case to be checked before the switch
492 if (!Extra) {
493 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000494 continue;
495 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000496 // Failed to parse a proper sequence, abort now
497 CompValue = nullptr;
498 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000499 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000500 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000501};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000502
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000503}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000504
Eli Friedmancb61afb2008-12-16 20:54:32 +0000505static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000506 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000507 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
508 Cond = dyn_cast<Instruction>(SI->getCondition());
509 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
510 if (BI->isConditional())
511 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000512 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
513 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000514 }
515
516 TI->eraseFromParent();
517 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
518}
519
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000520/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000521/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000522Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000523 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000524 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
525 // Do not permit merging of large switch instructions into their
526 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000527 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
528 pred_end(SI->getParent())) <= 128)
529 CV = SI->getCondition();
530 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000531 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000532 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000533 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000534 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000535 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000536
537 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000538 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000539 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
540 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000541 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000542 CV = Ptr;
543 }
544 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000545 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000546}
547
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000548/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000549/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000550BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000551GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000552 std::vector<ValueEqualityComparisonCase>
553 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000555 Cases.reserve(SI->getNumCases());
556 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
557 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
558 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000559 return SI->getDefaultDest();
560 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000561
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000562 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000563 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000564 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
565 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000566 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000567 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000568 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000569}
570
Eric Christopherb65acc62012-07-02 23:22:21 +0000571
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000572/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000573/// in the list that match the specified block.
574static void EliminateBlockCases(BasicBlock *BB,
575 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000576 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000577}
578
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000579/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000580static bool
581ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
582 std::vector<ValueEqualityComparisonCase > &C2) {
583 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
584
585 // Make V1 be smaller than V2.
586 if (V1->size() > V2->size())
587 std::swap(V1, V2);
588
589 if (V1->size() == 0) return false;
590 if (V1->size() == 1) {
591 // Just scan V2.
592 ConstantInt *TheVal = (*V1)[0].Value;
593 for (unsigned i = 0, e = V2->size(); i != e; ++i)
594 if (TheVal == (*V2)[i].Value)
595 return true;
596 }
597
598 // Otherwise, just sort both lists and compare element by element.
599 array_pod_sort(V1->begin(), V1->end());
600 array_pod_sort(V2->begin(), V2->end());
601 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
602 while (i1 != e1 && i2 != e2) {
603 if ((*V1)[i1].Value == (*V2)[i2].Value)
604 return true;
605 if ((*V1)[i1].Value < (*V2)[i2].Value)
606 ++i1;
607 else
608 ++i2;
609 }
610 return false;
611}
612
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000613/// If TI is known to be a terminator instruction and its block is known to
614/// only have a single predecessor block, check to see if that predecessor is
615/// also a value comparison with the same value, and if that comparison
616/// determines the outcome of this comparison. If so, simplify TI. This does a
617/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000618bool SimplifyCFGOpt::
619SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000620 BasicBlock *Pred,
621 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000622 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
623 if (!PredVal) return false; // Not a value comparison in predecessor.
624
625 Value *ThisVal = isValueEqualityComparison(TI);
626 assert(ThisVal && "This isn't a value comparison!!");
627 if (ThisVal != PredVal) return false; // Different predicates.
628
Andrew Trick3051aa12012-08-29 21:46:38 +0000629 // TODO: Preserve branch weight metadata, similarly to how
630 // FoldValueComparisonIntoPredecessors preserves it.
631
Chris Lattner1cca9592005-02-24 06:17:52 +0000632 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000633 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000634 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
635 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000636 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000637
Chris Lattner1cca9592005-02-24 06:17:52 +0000638 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000639 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000640 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000641 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000642
643 // If TI's block is the default block from Pred's comparison, potentially
644 // simplify TI based on this knowledge.
645 if (PredDef == TI->getParent()) {
646 // If we are here, we know that the value is none of those cases listed in
647 // PredCases. If there are any cases in ThisCases that are in PredCases, we
648 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000649 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000650 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000651
Chris Lattner4088e2b2010-12-13 01:47:07 +0000652 if (isa<BranchInst>(TI)) {
653 // Okay, one of the successors of this condbr is dead. Convert it to a
654 // uncond br.
655 assert(ThisCases.size() == 1 && "Branch can only have one case!");
656 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000657 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000658 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000659
Chris Lattner4088e2b2010-12-13 01:47:07 +0000660 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000661 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000662
Chris Lattner4088e2b2010-12-13 01:47:07 +0000663 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
664 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000665
Chris Lattner4088e2b2010-12-13 01:47:07 +0000666 EraseTerminatorInstAndDCECond(TI);
667 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000668 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000669
Chris Lattner4088e2b2010-12-13 01:47:07 +0000670 SwitchInst *SI = cast<SwitchInst>(TI);
671 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000672 SmallPtrSet<Constant*, 16> DeadCases;
673 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
674 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000675
David Greene725c7c32010-01-05 01:26:52 +0000676 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000677 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000678
Manman Ren8691e522012-09-14 21:53:06 +0000679 // Collect branch weights into a vector.
680 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000681 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000682 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
683 if (HasWeight)
684 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
685 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000686 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000687 Weights.push_back(CI->getValue().getZExtValue());
688 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000689 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
690 --i;
691 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000692 if (HasWeight) {
693 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
694 Weights.pop_back();
695 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000696 i.getCaseSuccessor()->removePredecessor(TI->getParent());
697 SI->removeCase(i);
698 }
699 }
Manman Ren97c18762012-10-11 22:28:34 +0000700 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000701 SI->setMetadata(LLVMContext::MD_prof,
702 MDBuilder(SI->getParent()->getContext()).
703 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000704
705 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000706 return true;
707 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000708
Chris Lattner4088e2b2010-12-13 01:47:07 +0000709 // Otherwise, TI's block must correspond to some matched value. Find out
710 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000711 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000712 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000713 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
714 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000715 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000716 return false; // Cannot handle multiple values coming to this block.
717 TIV = PredCases[i].Value;
718 }
719 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000720
721 // Okay, we found the one constant that our value can be if we get into TI's
722 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000723 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000724 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
725 if (ThisCases[i].Value == TIV) {
726 TheRealDest = ThisCases[i].Dest;
727 break;
728 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000729
730 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000731 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000732
733 // Remove PHI node entries for dead edges.
734 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000735 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
736 if (*SI != CheckEdge)
737 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000738 else
Craig Topperf40110f2014-04-25 05:29:35 +0000739 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000740
741 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000742 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000743 (void) NI;
744
745 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
746 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
747
748 EraseTerminatorInstAndDCECond(TI);
749 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000750}
751
Dale Johannesen7f99d222009-03-12 21:01:11 +0000752namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000753 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000754 /// integers that does not depend on their address. This is important for
755 /// applications that sort ConstantInt's to ensure uniqueness.
756 struct ConstantIntOrdering {
757 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
758 return LHS->getValue().ult(RHS->getValue());
759 }
760 };
761}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000762
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000763static int ConstantIntSortPredicate(ConstantInt *const *P1,
764 ConstantInt *const *P2) {
765 const ConstantInt *LHS = *P1;
766 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000767 if (LHS->getValue().ult(RHS->getValue()))
768 return 1;
769 if (LHS->getValue() == RHS->getValue())
770 return 0;
771 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000772}
773
Andrew Trick3051aa12012-08-29 21:46:38 +0000774static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000775 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000776 if (ProfMD && ProfMD->getOperand(0))
777 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
778 return MDS->getString().equals("branch_weights");
779
780 return false;
781}
782
Manman Ren571d9e42012-09-11 17:43:35 +0000783/// Get Weights of a given TerminatorInst, the default weight is at the front
784/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
785/// metadata.
786static void GetBranchWeights(TerminatorInst *TI,
787 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000788 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000789 assert(MD);
790 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000791 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000792 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000793 }
794
Manman Ren571d9e42012-09-11 17:43:35 +0000795 // If TI is a conditional eq, the default case is the false case,
796 // and the corresponding branch-weight data is at index 2. We swap the
797 // default weight to be the first entry.
798 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
799 assert(Weights.size() == 2);
800 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
801 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
802 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000803 }
804}
805
Manman Renf1cb16e2014-01-27 23:39:03 +0000806/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000807static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000808 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
809 if (Max > UINT_MAX) {
810 unsigned Offset = 32 - countLeadingZeros(Max);
811 for (uint64_t &I : Weights)
812 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000813 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000814}
815
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000816/// The specified terminator is a value equality comparison instruction
817/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000818/// See if any of the predecessors of the terminator block are value comparisons
819/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000820bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
821 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000822 BasicBlock *BB = TI->getParent();
823 Value *CV = isValueEqualityComparison(TI); // CondVal
824 assert(CV && "Not a comparison?");
825 bool Changed = false;
826
Chris Lattner6b39cb92008-02-18 07:42:56 +0000827 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000828 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000829 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000830
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000831 // See if the predecessor is a comparison with the same value.
832 TerminatorInst *PTI = Pred->getTerminator();
833 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
834
835 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
836 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000837 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000838 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
839
Eric Christopherb65acc62012-07-02 23:22:21 +0000840 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000841 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
842
843 // Based on whether the default edge from PTI goes to BB or not, fill in
844 // PredCases and PredDefault with the new switch cases we would like to
845 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000846 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000847
Andrew Trick3051aa12012-08-29 21:46:38 +0000848 // Update the branch weight metadata along the way
849 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000850 bool PredHasWeights = HasBranchWeights(PTI);
851 bool SuccHasWeights = HasBranchWeights(TI);
852
Manman Ren5e5049d2012-09-14 19:05:19 +0000853 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000854 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000855 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000856 if (Weights.size() != 1 + PredCases.size())
857 PredHasWeights = SuccHasWeights = false;
858 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000859 // If there are no predecessor weights but there are successor weights,
860 // populate Weights with 1, which will later be scaled to the sum of
861 // successor's weights
862 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000863
Manman Ren571d9e42012-09-11 17:43:35 +0000864 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000865 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000866 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000867 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000868 if (SuccWeights.size() != 1 + BBCases.size())
869 PredHasWeights = SuccHasWeights = false;
870 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000871 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000872
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000873 if (PredDefault == BB) {
874 // If this is the default destination from PTI, only the edges in TI
875 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000876 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
877 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
878 if (PredCases[i].Dest != BB)
879 PTIHandled.insert(PredCases[i].Value);
880 else {
881 // The default destination is BB, we don't need explicit targets.
882 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000883
Manman Ren571d9e42012-09-11 17:43:35 +0000884 if (PredHasWeights || SuccHasWeights) {
885 // Increase weight for the default case.
886 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000887 std::swap(Weights[i+1], Weights.back());
888 Weights.pop_back();
889 }
890
Eric Christopherb65acc62012-07-02 23:22:21 +0000891 PredCases.pop_back();
892 --i; --e;
893 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000894
Eric Christopherb65acc62012-07-02 23:22:21 +0000895 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000896 if (PredDefault != BBDefault) {
897 PredDefault->removePredecessor(Pred);
898 PredDefault = BBDefault;
899 NewSuccessors.push_back(BBDefault);
900 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000901
Manman Ren571d9e42012-09-11 17:43:35 +0000902 unsigned CasesFromPred = Weights.size();
903 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000904 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
905 if (!PTIHandled.count(BBCases[i].Value) &&
906 BBCases[i].Dest != BBDefault) {
907 PredCases.push_back(BBCases[i]);
908 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000909 if (SuccHasWeights || PredHasWeights) {
910 // The default weight is at index 0, so weight for the ith case
911 // should be at index i+1. Scale the cases from successor by
912 // PredDefaultWeight (Weights[0]).
913 Weights.push_back(Weights[0] * SuccWeights[i+1]);
914 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000915 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000916 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000917
Manman Ren571d9e42012-09-11 17:43:35 +0000918 if (SuccHasWeights || PredHasWeights) {
919 ValidTotalSuccWeight += SuccWeights[0];
920 // Scale the cases from predecessor by ValidTotalSuccWeight.
921 for (unsigned i = 1; i < CasesFromPred; ++i)
922 Weights[i] *= ValidTotalSuccWeight;
923 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
924 Weights[0] *= SuccWeights[0];
925 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000926 } else {
927 // If this is not the default destination from PSI, only the edges
928 // in SI that occur in PSI with a destination of BB will be
929 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000930 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000931 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000932 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
933 if (PredCases[i].Dest == BB) {
934 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000935
936 if (PredHasWeights || SuccHasWeights) {
937 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
938 std::swap(Weights[i+1], Weights.back());
939 Weights.pop_back();
940 }
941
Eric Christopherb65acc62012-07-02 23:22:21 +0000942 std::swap(PredCases[i], PredCases.back());
943 PredCases.pop_back();
944 --i; --e;
945 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000946
947 // Okay, now we know which constants were sent to BB from the
948 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000949 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
950 if (PTIHandled.count(BBCases[i].Value)) {
951 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000952 if (PredHasWeights || SuccHasWeights)
953 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000954 PredCases.push_back(BBCases[i]);
955 NewSuccessors.push_back(BBCases[i].Dest);
956 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
957 }
958
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000959 // If there are any constants vectored to BB that TI doesn't handle,
960 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000961 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000962 PTIHandled.begin(),
963 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000964 if (PredHasWeights || SuccHasWeights)
965 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000966 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000967 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000968 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000969 }
970
971 // Okay, at this point, we know which new successor Pred will get. Make
972 // sure we update the number of entries in the PHI nodes for these
973 // successors.
974 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
975 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
976
Devang Patel58380552011-05-18 20:53:17 +0000977 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000978 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000979 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000980 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000981 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000982 }
983
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000984 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000985 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
986 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000987 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +0000988 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
989 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000990
Andrew Trick3051aa12012-08-29 21:46:38 +0000991 if (PredHasWeights || SuccHasWeights) {
992 // Halve the weights if any of them cannot fit in an uint32_t
993 FitWeights(Weights);
994
995 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
996
997 NewSI->setMetadata(LLVMContext::MD_prof,
998 MDBuilder(BB->getContext()).
999 createBranchWeights(MDWeights));
1000 }
1001
Eli Friedmancb61afb2008-12-16 20:54:32 +00001002 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001003
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001004 // Okay, last check. If BB is still a successor of PSI, then we must
1005 // have an infinite loop case. If so, add an infinitely looping block
1006 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001007 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001008 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1009 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001010 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001011 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001012 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001013 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1014 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001015 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001016 }
1017 NewSI->setSuccessor(i, InfLoopBlock);
1018 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001019
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001020 Changed = true;
1021 }
1022 }
1023 return Changed;
1024}
1025
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001026// If we would need to insert a select that uses the value of this invoke
1027// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1028// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001029static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1030 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001031 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001032 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001033 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001034 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1035 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1036 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1037 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1038 return false;
1039 }
1040 }
1041 }
1042 return true;
1043}
1044
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001045static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1046
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001047/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1048/// in the two blocks up into the branch block. The caller of this function
1049/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001050static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001051 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001052 // This does very trivial matching, with limited scanning, to find identical
1053 // instructions in the two blocks. In particular, we don't want to get into
1054 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1055 // such, we currently just scan for obviously identical instructions in an
1056 // identical order.
1057 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1058 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1059
Devang Patelf10e2872009-02-04 00:03:08 +00001060 BasicBlock::iterator BB1_Itr = BB1->begin();
1061 BasicBlock::iterator BB2_Itr = BB2->begin();
1062
1063 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001064 // Skip debug info if it is not identical.
1065 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1066 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1067 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1068 while (isa<DbgInfoIntrinsic>(I1))
1069 I1 = BB1_Itr++;
1070 while (isa<DbgInfoIntrinsic>(I2))
1071 I2 = BB2_Itr++;
1072 }
Devang Patele48ddf82011-04-07 00:30:15 +00001073 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001074 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001075 return false;
1076
Chris Lattner389cfac2004-11-30 00:29:14 +00001077 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001078
David Majnemerc82f27a2013-06-03 20:43:12 +00001079 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001080 do {
1081 // If we are hoisting the terminator instruction, don't move one (making a
1082 // broken BB), instead clone it, and remove BI.
1083 if (isa<TerminatorInst>(I1))
1084 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001085
Chad Rosier54390052015-02-23 19:15:16 +00001086 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1087 return Changed;
1088
Chris Lattner389cfac2004-11-30 00:29:14 +00001089 // For a normal instruction, we just move one to right before the branch,
1090 // then replace all uses of the other with the first. Finally, we remove
1091 // the now redundant second instruction.
1092 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1093 if (!I2->use_empty())
1094 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001095 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001096 unsigned KnownIDs[] = {
1097 LLVMContext::MD_tbaa,
1098 LLVMContext::MD_range,
1099 LLVMContext::MD_fpmath,
Philip Reamesd92c2a72014-10-22 16:37:13 +00001100 LLVMContext::MD_invariant_load,
1101 LLVMContext::MD_nonnull
Rafael Espindolaea46c322014-08-15 15:46:38 +00001102 };
1103 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001104 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001105 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001106
Devang Patelf10e2872009-02-04 00:03:08 +00001107 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001108 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001109 // Skip debug info if it is not identical.
1110 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1111 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1112 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1113 while (isa<DbgInfoIntrinsic>(I1))
1114 I1 = BB1_Itr++;
1115 while (isa<DbgInfoIntrinsic>(I2))
1116 I2 = BB2_Itr++;
1117 }
Devang Patele48ddf82011-04-07 00:30:15 +00001118 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001119
1120 return true;
1121
1122HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001123 // It may not be possible to hoist an invoke.
1124 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001125 return Changed;
1126
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001127 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001128 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001129 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001130 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1131 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1132 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1133 if (BB1V == BB2V)
1134 continue;
1135
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001136 // Check for passingValueIsAlwaysUndefined here because we would rather
1137 // eliminate undefined control flow then converting it to a select.
1138 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1139 passingValueIsAlwaysUndefined(BB2V, PN))
1140 return Changed;
1141
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001142 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001143 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001144 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001145 return Changed;
1146 }
1147 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001148
Chris Lattner389cfac2004-11-30 00:29:14 +00001149 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001150 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001151 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001152 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001153 I1->replaceAllUsesWith(NT);
1154 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001155 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001156 }
1157
Devang Patel1407fb42011-05-19 20:52:46 +00001158 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001159 // Hoisting one of the terminators from our successor is a great thing.
1160 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1161 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1162 // nodes, so we insert select instruction to compute the final result.
1163 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001164 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001165 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001166 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001167 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001168 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1169 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001170 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001171
Chris Lattner4088e2b2010-12-13 01:47:07 +00001172 // These values do not agree. Insert a select instruction before NT
1173 // that determines the right value.
1174 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001175 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001176 SI = cast<SelectInst>
1177 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1178 BB1V->getName()+"."+BB2V->getName()));
1179
Chris Lattner4088e2b2010-12-13 01:47:07 +00001180 // Make the PHI node use the select for all incoming values for BB1/BB2
1181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1182 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1183 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001184 }
1185 }
1186
1187 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001188 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1189 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001190
Eli Friedmancb61afb2008-12-16 20:54:32 +00001191 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001192 return true;
1193}
1194
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001195/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001196/// check whether BBEnd has only two predecessors and the other predecessor
1197/// ends with an unconditional branch. If it is true, sink any common code
1198/// in the two predecessors to BBEnd.
1199static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1200 assert(BI1->isUnconditional());
1201 BasicBlock *BB1 = BI1->getParent();
1202 BasicBlock *BBEnd = BI1->getSuccessor(0);
1203
1204 // Check that BBEnd has two predecessors and the other predecessor ends with
1205 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001206 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1207 BasicBlock *Pred0 = *PI++;
1208 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001209 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001210 BasicBlock *Pred1 = *PI++;
1211 if (PI != PE) // More than two predecessors.
1212 return false;
1213 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001214 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1215 if (!BI2 || !BI2->isUnconditional())
1216 return false;
1217
1218 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001219 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001220 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001221 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001222 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1223 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001224 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001225 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001226 } else {
1227 FirstNonPhiInBBEnd = &*I;
1228 break;
1229 }
1230 }
1231 if (!FirstNonPhiInBBEnd)
1232 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001233
Manman Ren93ab6492012-09-20 22:37:36 +00001234 // This does very trivial matching, with limited scanning, to find identical
1235 // instructions in the two blocks. We scan backward for obviously identical
1236 // instructions in an identical order.
1237 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001238 RE1 = BB1->getInstList().rend(),
1239 RI2 = BB2->getInstList().rbegin(),
1240 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001241 // Skip debug info.
1242 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1243 if (RI1 == RE1)
1244 return false;
1245 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1246 if (RI2 == RE2)
1247 return false;
1248 // Skip the unconditional branches.
1249 ++RI1;
1250 ++RI2;
1251
1252 bool Changed = false;
1253 while (RI1 != RE1 && RI2 != RE2) {
1254 // Skip debug info.
1255 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1256 if (RI1 == RE1)
1257 return Changed;
1258 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1259 if (RI2 == RE2)
1260 return Changed;
1261
1262 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001263 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001264 // I1 and I2 should have a single use in the same PHI node, and they
1265 // perform the same operation.
1266 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1267 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1268 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001269 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001270 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1271 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1272 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1273 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001274 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001275 return Changed;
1276
1277 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001278 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001279 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1280 bool SwapOpnds = false;
1281 if (ICmp1 && ICmp2 &&
1282 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1283 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1284 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1285 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1286 ICmp2->swapOperands();
1287 SwapOpnds = true;
1288 }
1289 if (!I1->isSameOperationAs(I2)) {
1290 if (SwapOpnds)
1291 ICmp2->swapOperands();
1292 return Changed;
1293 }
1294
1295 // The operands should be either the same or they need to be generated
1296 // with a PHI node after sinking. We only handle the case where there is
1297 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001298 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001299 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001300 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1301 if (I1->getOperand(I) == I2->getOperand(I))
1302 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001303 // Early exit if we have more-than one pair of different operands or if
1304 // we need a PHI node to replace a constant.
1305 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001306 isa<Constant>(I1->getOperand(I)) ||
1307 isa<Constant>(I2->getOperand(I))) {
1308 // If we can't sink the instructions, undo the swapping.
1309 if (SwapOpnds)
1310 ICmp2->swapOperands();
1311 return Changed;
1312 }
1313 DifferentOp1 = I1->getOperand(I);
1314 Op1Idx = I;
1315 DifferentOp2 = I2->getOperand(I);
1316 }
1317
Michael Liao5313da32014-12-23 08:26:55 +00001318 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1319 DEBUG(dbgs() << " " << *I2 << "\n");
1320
1321 // We insert the pair of different operands to JointValueMap and
1322 // remove (I1, I2) from JointValueMap.
1323 if (Op1Idx != ~0U) {
1324 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1325 if (!NewPN) {
1326 NewPN =
1327 PHINode::Create(DifferentOp1->getType(), 2,
1328 DifferentOp1->getName() + ".sink", BBEnd->begin());
1329 NewPN->addIncoming(DifferentOp1, BB1);
1330 NewPN->addIncoming(DifferentOp2, BB2);
1331 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1332 }
Manman Ren93ab6492012-09-20 22:37:36 +00001333 // I1 should use NewPN instead of DifferentOp1.
1334 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001335 }
Michael Liao5313da32014-12-23 08:26:55 +00001336 PHINode *OldPN = JointValueMap[InstPair];
1337 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001338
Manman Ren93ab6492012-09-20 22:37:36 +00001339 // We need to update RE1 and RE2 if we are going to sink the first
1340 // instruction in the basic block down.
1341 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1342 // Sink the instruction.
1343 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1344 if (!OldPN->use_empty())
1345 OldPN->replaceAllUsesWith(I1);
1346 OldPN->eraseFromParent();
1347
1348 if (!I2->use_empty())
1349 I2->replaceAllUsesWith(I1);
1350 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001351 // TODO: Use combineMetadata here to preserve what metadata we can
1352 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001353 I2->eraseFromParent();
1354
1355 if (UpdateRE1)
1356 RE1 = BB1->getInstList().rend();
1357 if (UpdateRE2)
1358 RE2 = BB2->getInstList().rend();
1359 FirstNonPhiInBBEnd = I1;
1360 NumSinkCommons++;
1361 Changed = true;
1362 }
1363 return Changed;
1364}
1365
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001366/// \brief Determine if we can hoist sink a sole store instruction out of a
1367/// conditional block.
1368///
1369/// We are looking for code like the following:
1370/// BrBB:
1371/// store i32 %add, i32* %arrayidx2
1372/// ... // No other stores or function calls (we could be calling a memory
1373/// ... // function).
1374/// %cmp = icmp ult %x, %y
1375/// br i1 %cmp, label %EndBB, label %ThenBB
1376/// ThenBB:
1377/// store i32 %add5, i32* %arrayidx2
1378/// br label EndBB
1379/// EndBB:
1380/// ...
1381/// We are going to transform this into:
1382/// BrBB:
1383/// store i32 %add, i32* %arrayidx2
1384/// ... //
1385/// %cmp = icmp ult %x, %y
1386/// %add.add5 = select i1 %cmp, i32 %add, %add5
1387/// store i32 %add.add5, i32* %arrayidx2
1388/// ...
1389///
1390/// \return The pointer to the value of the previous store if the store can be
1391/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001392static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1393 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001394 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1395 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001396 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001397
1398 // Volatile or atomic.
1399 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001400 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001401
1402 Value *StorePtr = StoreToHoist->getPointerOperand();
1403
1404 // Look for a store to the same pointer in BrBB.
1405 unsigned MaxNumInstToLookAt = 10;
1406 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1407 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1408 Instruction *CurI = &*RI;
1409
1410 // Could be calling an instruction that effects memory like free().
1411 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001412 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001413
1414 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1415 // Found the previous store make sure it stores to the same location.
1416 if (SI && SI->getPointerOperand() == StorePtr)
1417 // Found the previous store, return its value operand.
1418 return SI->getValueOperand();
1419 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001420 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001421 }
1422
Craig Topperf40110f2014-04-25 05:29:35 +00001423 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001424}
1425
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001426/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001427///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001428/// Note that this is a very risky transform currently. Speculating
1429/// instructions like this is most often not desirable. Instead, there is an MI
1430/// pass which can do it with full awareness of the resource constraints.
1431/// However, some cases are "obvious" and we should do directly. An example of
1432/// this is speculating a single, reasonably cheap instruction.
1433///
1434/// There is only one distinct advantage to flattening the CFG at the IR level:
1435/// it makes very common but simplistic optimizations such as are common in
1436/// instcombine and the DAG combiner more powerful by removing CFG edges and
1437/// modeling their effects with easier to reason about SSA value graphs.
1438///
1439///
1440/// An illustration of this transform is turning this IR:
1441/// \code
1442/// BB:
1443/// %cmp = icmp ult %x, %y
1444/// br i1 %cmp, label %EndBB, label %ThenBB
1445/// ThenBB:
1446/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001447/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001448/// EndBB:
1449/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1450/// ...
1451/// \endcode
1452///
1453/// Into this IR:
1454/// \code
1455/// BB:
1456/// %cmp = icmp ult %x, %y
1457/// %sub = sub %x, %y
1458/// %cond = select i1 %cmp, 0, %sub
1459/// ...
1460/// \endcode
1461///
1462/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001463static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001464 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001465 // Be conservative for now. FP select instruction can often be expensive.
1466 Value *BrCond = BI->getCondition();
1467 if (isa<FCmpInst>(BrCond))
1468 return false;
1469
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001470 BasicBlock *BB = BI->getParent();
1471 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1472
1473 // If ThenBB is actually on the false edge of the conditional branch, remember
1474 // to swap the select operands later.
1475 bool Invert = false;
1476 if (ThenBB != BI->getSuccessor(0)) {
1477 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1478 Invert = true;
1479 }
1480 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1481
Chandler Carruthceff2222013-01-25 05:40:09 +00001482 // Keep a count of how many times instructions are used within CondBB when
1483 // they are candidates for sinking into CondBB. Specifically:
1484 // - They are defined in BB, and
1485 // - They have no side effects, and
1486 // - All of their uses are in CondBB.
1487 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1488
Chandler Carruth7481ca82013-01-24 11:52:58 +00001489 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001490 Value *SpeculatedStoreValue = nullptr;
1491 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001492 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001493 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001494 BBI != BBE; ++BBI) {
1495 Instruction *I = BBI;
1496 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001497 if (isa<DbgInfoIntrinsic>(I))
1498 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001499
Mark Lacey274f48b2015-04-12 18:18:51 +00001500 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001501 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001502 ++SpeculationCost;
1503 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001504 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001505
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001506 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001507 if (!isSafeToSpeculativelyExecute(I) &&
1508 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1509 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001510 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001511 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001512 ComputeSpeculationCost(I, TTI) >
1513 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001514 return false;
1515
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001516 // Store the store speculation candidate.
1517 if (SpeculatedStoreValue)
1518 SpeculatedStore = cast<StoreInst>(I);
1519
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001520 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001521 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001522 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001523 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001524 i != e; ++i) {
1525 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001526 if (!OpI || OpI->getParent() != BB ||
1527 OpI->mayHaveSideEffects())
1528 continue; // Not a candidate for sinking.
1529
1530 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001531 }
1532 }
Evan Cheng89200c92008-06-07 08:52:29 +00001533
Chandler Carruthceff2222013-01-25 05:40:09 +00001534 // Consider any sink candidates which are only used in CondBB as costs for
1535 // speculation. Note, while we iterate over a DenseMap here, we are summing
1536 // and so iteration order isn't significant.
1537 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1538 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1539 I != E; ++I)
1540 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001541 ++SpeculationCost;
1542 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001543 return false;
1544 }
1545
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001546 // Check that the PHI nodes can be converted to selects.
1547 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001548 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001549 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001550 Value *OrigV = PN->getIncomingValueForBlock(BB);
1551 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001552
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001553 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001554 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001555 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001556 continue;
1557
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001558 // Don't convert to selects if we could remove undefined behavior instead.
1559 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1560 passingValueIsAlwaysUndefined(ThenV, PN))
1561 return false;
1562
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001563 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001564 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1565 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1566 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001567 continue; // Known safe and cheap.
1568
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001569 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1570 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001571 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001572 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1573 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001574 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1575 TargetTransformInfo::TCC_Basic;
1576 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001577 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001578
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001579 // Account for the cost of an unfolded ConstantExpr which could end up
1580 // getting expanded into Instructions.
1581 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001582 // constant expression.
1583 ++SpeculationCost;
1584 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001585 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001586 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001587
1588 // If there are no PHIs to process, bail early. This helps ensure idempotence
1589 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001590 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001591 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001592
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001593 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001594 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001595
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001596 // Insert a select of the value of the speculated store.
1597 if (SpeculatedStoreValue) {
1598 IRBuilder<true, NoFolder> Builder(BI);
1599 Value *TrueV = SpeculatedStore->getValueOperand();
1600 Value *FalseV = SpeculatedStoreValue;
1601 if (Invert)
1602 std::swap(TrueV, FalseV);
1603 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1604 "." + FalseV->getName());
1605 SpeculatedStore->setOperand(0, S);
1606 }
1607
Chandler Carruth7481ca82013-01-24 11:52:58 +00001608 // Hoist the instructions.
1609 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001610 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001611
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001612 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001613 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001614 for (BasicBlock::iterator I = EndBB->begin();
1615 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1616 unsigned OrigI = PN->getBasicBlockIndex(BB);
1617 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1618 Value *OrigV = PN->getIncomingValue(OrigI);
1619 Value *ThenV = PN->getIncomingValue(ThenI);
1620
1621 // Skip PHIs which are trivial.
1622 if (OrigV == ThenV)
1623 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001624
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001625 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001626 // false value is the preexisting value. Swap them if the branch
1627 // destinations were inverted.
1628 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001629 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001630 std::swap(TrueV, FalseV);
1631 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1632 TrueV->getName() + "." + FalseV->getName());
1633 PN->setIncomingValue(OrigI, V);
1634 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001635 }
1636
Evan Cheng89553cc2008-06-12 21:15:59 +00001637 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001638 return true;
1639}
1640
Tom Stellarde1631dd2013-10-21 20:07:30 +00001641/// \returns True if this block contains a CallInst with the NoDuplicate
1642/// attribute.
1643static bool HasNoDuplicateCall(const BasicBlock *BB) {
1644 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1645 const CallInst *CI = dyn_cast<CallInst>(I);
1646 if (!CI)
1647 continue;
1648 if (CI->cannotDuplicate())
1649 return true;
1650 }
1651 return false;
1652}
1653
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001654/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001655static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1656 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001657 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001658
Devang Patel84fceff2009-03-10 18:00:05 +00001659 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001660 if (isa<DbgInfoIntrinsic>(BBI))
1661 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001662 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001663 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001664
Dale Johannesened6f5a82009-03-12 23:18:09 +00001665 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001666 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001667 for (User *U : BBI->users()) {
1668 Instruction *UI = cast<Instruction>(U);
1669 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001670 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001671
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001672 // Looks ok, continue checking.
1673 }
Chris Lattner6c701062005-09-20 01:48:40 +00001674
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001675 return true;
1676}
1677
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001678/// If we have a conditional branch on a PHI node value that is defined in the
1679/// same block as the branch and if any PHI entries are constants, thread edges
1680/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001681static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001682 BasicBlock *BB = BI->getParent();
1683 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001684 // NOTE: we currently cannot transform this case if the PHI node is used
1685 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001686 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1687 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001688
Chris Lattner748f9032005-09-19 23:49:37 +00001689 // Degenerate case of a single entry PHI.
1690 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001691 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001692 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001693 }
1694
1695 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001696 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001697
Tom Stellarde1631dd2013-10-21 20:07:30 +00001698 if (HasNoDuplicateCall(BB)) return false;
1699
Chris Lattner748f9032005-09-19 23:49:37 +00001700 // Okay, this is a simple enough basic block. See if any phi values are
1701 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001703 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001704 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001705
Chris Lattner4088e2b2010-12-13 01:47:07 +00001706 // Okay, we now know that all edges from PredBB should be revectored to
1707 // branch to RealDest.
1708 BasicBlock *PredBB = PN->getIncomingBlock(i);
1709 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001710
Chris Lattner4088e2b2010-12-13 01:47:07 +00001711 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001712 // Skip if the predecessor's terminator is an indirect branch.
1713 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001714
Chris Lattner4088e2b2010-12-13 01:47:07 +00001715 // The dest block might have PHI nodes, other predecessors and other
1716 // difficult cases. Instead of being smart about this, just insert a new
1717 // block that jumps to the destination block, effectively splitting
1718 // the edge we are about to create.
1719 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1720 RealDest->getName()+".critedge",
1721 RealDest->getParent(), RealDest);
1722 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001723
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001724 // Update PHI nodes.
1725 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001726
1727 // BB may have instructions that are being threaded over. Clone these
1728 // instructions into EdgeBB. We know that there will be no uses of the
1729 // cloned instructions outside of EdgeBB.
1730 BasicBlock::iterator InsertPt = EdgeBB->begin();
1731 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1732 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1733 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1734 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1735 continue;
1736 }
1737 // Clone the instruction.
1738 Instruction *N = BBI->clone();
1739 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001740
Chris Lattner4088e2b2010-12-13 01:47:07 +00001741 // Update operands due to translation.
1742 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1743 i != e; ++i) {
1744 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1745 if (PI != TranslateMap.end())
1746 *i = PI->second;
1747 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001748
Chris Lattner4088e2b2010-12-13 01:47:07 +00001749 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001750 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001751 TranslateMap[BBI] = V;
1752 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001753 } else {
1754 // Insert the new instruction into its new home.
1755 EdgeBB->getInstList().insert(InsertPt, N);
1756 if (!BBI->use_empty())
1757 TranslateMap[BBI] = N;
1758 }
1759 }
1760
1761 // Loop over all of the edges from PredBB to BB, changing them to branch
1762 // to EdgeBB instead.
1763 TerminatorInst *PredBBTI = PredBB->getTerminator();
1764 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1765 if (PredBBTI->getSuccessor(i) == BB) {
1766 BB->removePredecessor(PredBB);
1767 PredBBTI->setSuccessor(i, EdgeBB);
1768 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001769
Chris Lattner4088e2b2010-12-13 01:47:07 +00001770 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001771 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001772 }
Chris Lattner748f9032005-09-19 23:49:37 +00001773
1774 return false;
1775}
1776
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001777/// Given a BB that starts with the specified two-entry PHI node,
1778/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001779static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1780 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001781 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1782 // statement", which has a very simple dominance structure. Basically, we
1783 // are trying to find the condition that is being branched on, which
1784 // subsequently causes this merge to happen. We really want control
1785 // dependence information for this check, but simplifycfg can't keep it up
1786 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001787 BasicBlock *BB = PN->getParent();
1788 BasicBlock *IfTrue, *IfFalse;
1789 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001790 if (!IfCond ||
1791 // Don't bother if the branch will be constant folded trivially.
1792 isa<ConstantInt>(IfCond))
1793 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001794
Chris Lattner95adf8f12006-11-18 19:19:36 +00001795 // Okay, we found that we can merge this two-entry phi node into a select.
1796 // Doing so would require us to fold *all* two entry phi nodes in this block.
1797 // At some point this becomes non-profitable (particularly if the target
1798 // doesn't support cmov's). Only do this transformation if there are two or
1799 // fewer PHI nodes in this block.
1800 unsigned NumPhis = 0;
1801 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1802 if (NumPhis > 2)
1803 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001804
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001805 // Loop over the PHI's seeing if we can promote them all to select
1806 // instructions. While we are at it, keep track of the instructions
1807 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001808 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001809 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1810 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001811 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1812 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001813
Chris Lattner7499b452010-12-14 08:46:09 +00001814 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1815 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001816 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001817 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001818 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001819 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001820 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001821
Peter Collingbournee3511e12011-04-29 18:47:31 +00001822 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001823 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001824 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001825 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001826 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001827 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001828
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001829 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001830 // we ran out of PHIs then we simplified them all.
1831 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001832 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001833
Chris Lattner7499b452010-12-14 08:46:09 +00001834 // Don't fold i1 branches on PHIs which contain binary operators. These can
1835 // often be turned into switches and other things.
1836 if (PN->getType()->isIntegerTy(1) &&
1837 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1838 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1839 isa<BinaryOperator>(IfCond)))
1840 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001841
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001842 // If we all PHI nodes are promotable, check to make sure that all
1843 // instructions in the predecessor blocks can be promoted as well. If
1844 // not, we won't be able to get rid of the control flow, so it's not
1845 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001846 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001847 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1848 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1849 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001850 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001851 } else {
1852 DomBlock = *pred_begin(IfBlock1);
1853 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001854 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001855 // This is not an aggressive instruction that we can promote.
1856 // Because of this, we won't be able to get rid of the control
1857 // flow, so the xform is not worth it.
1858 return false;
1859 }
1860 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001861
Chris Lattner9ac168d2010-12-14 07:41:39 +00001862 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001863 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001864 } else {
1865 DomBlock = *pred_begin(IfBlock2);
1866 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001867 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001868 // This is not an aggressive instruction that we can promote.
1869 // Because of this, we won't be able to get rid of the control
1870 // flow, so the xform is not worth it.
1871 return false;
1872 }
1873 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001874
Chris Lattner9fd838d2010-12-14 07:23:10 +00001875 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001876 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001877
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001878 // If we can still promote the PHI nodes after this gauntlet of tests,
1879 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001880 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001881 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001882
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001883 // Move all 'aggressive' instructions, which are defined in the
1884 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001885 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001886 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001887 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001888 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001889 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001890 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001891 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001892 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001893
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001894 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1895 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001896 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1897 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001898
1899 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001900 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001901 PN->replaceAllUsesWith(NV);
1902 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001903 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001904 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001905
Chris Lattner335f0e42010-12-14 08:01:53 +00001906 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1907 // has been flattened. Change DomBlock to jump directly to our new block to
1908 // avoid other simplifycfg's kicking in on the diamond.
1909 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001910 Builder.SetInsertPoint(OldTI);
1911 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001912 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001913 return true;
1914}
Chris Lattner748f9032005-09-19 23:49:37 +00001915
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001916/// If we found a conditional branch that goes to two returning blocks,
1917/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001918/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001919static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001920 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001921 assert(BI->isConditional() && "Must be a conditional branch");
1922 BasicBlock *TrueSucc = BI->getSuccessor(0);
1923 BasicBlock *FalseSucc = BI->getSuccessor(1);
1924 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1925 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001926
Chris Lattner86bbf332008-04-24 00:01:19 +00001927 // Check to ensure both blocks are empty (just a return) or optionally empty
1928 // with PHI nodes. If there are other instructions, merging would cause extra
1929 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001930 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001931 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001932 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001933 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001934
Devang Pateldd14e0f2011-05-18 21:33:11 +00001935 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001936 // Okay, we found a branch that is going to two return nodes. If
1937 // there is no return value for this function, just change the
1938 // branch into a return.
1939 if (FalseRet->getNumOperands() == 0) {
1940 TrueSucc->removePredecessor(BI->getParent());
1941 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001942 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001943 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001944 return true;
1945 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001946
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001947 // Otherwise, figure out what the true and false return values are
1948 // so we can insert a new select instruction.
1949 Value *TrueValue = TrueRet->getReturnValue();
1950 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001951
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001952 // Unwrap any PHI nodes in the return blocks.
1953 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1954 if (TVPN->getParent() == TrueSucc)
1955 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1956 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1957 if (FVPN->getParent() == FalseSucc)
1958 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001959
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001960 // In order for this transformation to be safe, we must be able to
1961 // unconditionally execute both operands to the return. This is
1962 // normally the case, but we could have a potentially-trapping
1963 // constant expression that prevents this transformation from being
1964 // safe.
1965 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1966 if (TCV->canTrap())
1967 return false;
1968 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1969 if (FCV->canTrap())
1970 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001971
Chris Lattner86bbf332008-04-24 00:01:19 +00001972 // Okay, we collected all the mapped values and checked them for sanity, and
1973 // defined to really do this transformation. First, update the CFG.
1974 TrueSucc->removePredecessor(BI->getParent());
1975 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001976
Chris Lattner86bbf332008-04-24 00:01:19 +00001977 // Insert select instructions where needed.
1978 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001979 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001980 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001981 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1982 } else if (isa<UndefValue>(TrueValue)) {
1983 TrueValue = FalseValue;
1984 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001985 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1986 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001987 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001988 }
1989
Andrew Trickf3cf1932012-08-29 21:46:36 +00001990 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001991 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1992
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00001993 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001994
David Greene725c7c32010-01-05 01:26:52 +00001995 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00001996 << "\n " << *BI << "NewRet = " << *RI
1997 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001998
Eli Friedmancb61afb2008-12-16 20:54:32 +00001999 EraseTerminatorInstAndDCECond(BI);
2000
Chris Lattner86bbf332008-04-24 00:01:19 +00002001 return true;
2002}
2003
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002004/// Given a conditional BranchInstruction, retrieve the probabilities of the
2005/// branch taking each edge. Fills in the two APInt parameters and returns true,
2006/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002007static bool ExtractBranchMetadata(BranchInst *BI,
2008 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2009 assert(BI->isConditional() &&
2010 "Looking for probabilities on unconditional branch?");
2011 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2012 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002013 ConstantInt *CITrue =
2014 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2015 ConstantInt *CIFalse =
2016 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002017 if (!CITrue || !CIFalse) return false;
2018 ProbTrue = CITrue->getValue().getZExtValue();
2019 ProbFalse = CIFalse->getValue().getZExtValue();
2020 return true;
2021}
2022
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002023/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002024/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002025static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002026 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2027 return false;
2028 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2029 Instruction *PBI = &*I;
2030 // Check whether Inst and PBI generate the same value.
2031 if (Inst->isIdenticalTo(PBI)) {
2032 Inst->replaceAllUsesWith(PBI);
2033 Inst->eraseFromParent();
2034 return true;
2035 }
2036 }
2037 return false;
2038}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002039
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002040/// If this basic block is simple enough, and if a predecessor branches to us
2041/// and one of our successors, fold the block into the predecessor and use
2042/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002043bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002044 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002045
Craig Topperf40110f2014-04-25 05:29:35 +00002046 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002047 if (BI->isConditional())
2048 Cond = dyn_cast<Instruction>(BI->getCondition());
2049 else {
2050 // For unconditional branch, check for a simple CFG pattern, where
2051 // BB has a single predecessor and BB's successor is also its predecessor's
2052 // successor. If such pattern exisits, check for CSE between BB and its
2053 // predecessor.
2054 if (BasicBlock *PB = BB->getSinglePredecessor())
2055 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2056 if (PBI->isConditional() &&
2057 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2058 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2059 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2060 I != E; ) {
2061 Instruction *Curr = I++;
2062 if (isa<CmpInst>(Curr)) {
2063 Cond = Curr;
2064 break;
2065 }
2066 // Quit if we can't remove this instruction.
2067 if (!checkCSEInPredecessor(Curr, PB))
2068 return false;
2069 }
2070 }
2071
Craig Topperf40110f2014-04-25 05:29:35 +00002072 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002073 return false;
2074 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002075
Craig Topperf40110f2014-04-25 05:29:35 +00002076 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2077 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002078 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002079
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002080 // Make sure the instruction after the condition is the cond branch.
2081 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002082
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002083 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002084 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002085
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002086 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002087 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002088
Jingyue Wufc029672014-09-30 22:23:38 +00002089 // Only allow this transformation if computing the condition doesn't involve
2090 // too many instructions and these involved instructions can be executed
2091 // unconditionally. We denote all involved instructions except the condition
2092 // as "bonus instructions", and only allow this transformation when the
2093 // number of the bonus instructions does not exceed a certain threshold.
2094 unsigned NumBonusInsts = 0;
2095 for (auto I = BB->begin(); Cond != I; ++I) {
2096 // Ignore dbg intrinsics.
2097 if (isa<DbgInfoIntrinsic>(I))
2098 continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002099 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
Jingyue Wufc029672014-09-30 22:23:38 +00002100 return false;
2101 // I has only one use and can be executed unconditionally.
2102 Instruction *User = dyn_cast<Instruction>(I->user_back());
2103 if (User == nullptr || User->getParent() != BB)
2104 return false;
2105 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2106 // to use any other instruction, User must be an instruction between next(I)
2107 // and Cond.
2108 ++NumBonusInsts;
2109 // Early exits once we reach the limit.
2110 if (NumBonusInsts > BonusInstThreshold)
2111 return false;
2112 }
2113
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002114 // Cond is known to be a compare or binary operator. Check to make sure that
2115 // neither operand is a potentially-trapping constant expression.
2116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2117 if (CE->canTrap())
2118 return false;
2119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2120 if (CE->canTrap())
2121 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002122
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002123 // Finally, don't infinitely unroll conditional loops.
2124 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002125 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002126 if (TrueDest == BB || FalseDest == BB)
2127 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002128
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002129 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2130 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002131 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002132
Chris Lattner80b03a12008-07-13 22:23:11 +00002133 // Check that we have two conditional branches. If there is a PHI node in
2134 // the common successor, verify that the same value flows in from both
2135 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002136 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002137 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002138 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002139 !SafeToMergeTerminators(BI, PBI)) ||
2140 (!BI->isConditional() &&
2141 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002142 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002143
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002144 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002145 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002146 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002147
Manman Rend33f4ef2012-06-13 05:43:29 +00002148 if (BI->isConditional()) {
2149 if (PBI->getSuccessor(0) == TrueDest)
2150 Opc = Instruction::Or;
2151 else if (PBI->getSuccessor(1) == FalseDest)
2152 Opc = Instruction::And;
2153 else if (PBI->getSuccessor(0) == FalseDest)
2154 Opc = Instruction::And, InvertPredCond = true;
2155 else if (PBI->getSuccessor(1) == TrueDest)
2156 Opc = Instruction::Or, InvertPredCond = true;
2157 else
2158 continue;
2159 } else {
2160 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2161 continue;
2162 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002163
David Greene725c7c32010-01-05 01:26:52 +00002164 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002165 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002166
Chris Lattner55eaae12008-07-13 21:20:19 +00002167 // If we need to invert the condition in the pred block to match, do so now.
2168 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002169 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002170
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002171 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2172 CmpInst *CI = cast<CmpInst>(NewCond);
2173 CI->setPredicate(CI->getInversePredicate());
2174 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002175 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002176 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002177 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002179 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002180 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002181 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002182
Jingyue Wufc029672014-09-30 22:23:38 +00002183 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002184 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002185 // bonus instructions to a predecessor block.
2186 ValueToValueMapTy VMap; // maps original values to cloned values
2187 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002188 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002189 // instructions.
2190 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2191 if (isa<DbgInfoIntrinsic>(BonusInst))
2192 continue;
2193 Instruction *NewBonusInst = BonusInst->clone();
2194 RemapInstruction(NewBonusInst, VMap,
2195 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2196 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002197
2198 // If we moved a load, we cannot any longer claim any knowledge about
2199 // its potential value. The previous information might have been valid
2200 // only given the branch precondition.
2201 // For an analogous reason, we must also drop all the metadata whose
2202 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002203 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002204
Jingyue Wufc029672014-09-30 22:23:38 +00002205 PredBlock->getInstList().insert(PBI, NewBonusInst);
2206 NewBonusInst->takeName(BonusInst);
2207 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002208 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002209
Chris Lattner55eaae12008-07-13 21:20:19 +00002210 // Clone Cond into the predecessor basic block, and or/and the
2211 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002212 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002213 RemapInstruction(New, VMap,
2214 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002215 PredBlock->getInstList().insert(PBI, New);
2216 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002217 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002218
Manman Rend33f4ef2012-06-13 05:43:29 +00002219 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002220 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002221 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002222 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002223 PBI->setCondition(NewCond);
2224
Manman Renbfb9d432012-09-15 00:39:57 +00002225 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002226 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2227 PredFalseWeight);
2228 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2229 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002230 SmallVector<uint64_t, 8> NewWeights;
2231
Manman Rend33f4ef2012-06-13 05:43:29 +00002232 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002233 if (PredHasWeights && SuccHasWeights) {
2234 // PBI: br i1 %x, BB, FalseDest
2235 // BI: br i1 %y, TrueDest, FalseDest
2236 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2237 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2238 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2239 // TrueWeight for PBI * FalseWeight for BI.
2240 // We assume that total weights of a BranchInst can fit into 32 bits.
2241 // Therefore, we will not have overflow using 64-bit arithmetic.
2242 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2243 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2244 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002245 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2246 PBI->setSuccessor(0, TrueDest);
2247 }
2248 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002249 if (PredHasWeights && SuccHasWeights) {
2250 // PBI: br i1 %x, TrueDest, BB
2251 // BI: br i1 %y, TrueDest, FalseDest
2252 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2253 // FalseWeight for PBI * TrueWeight for BI.
2254 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2255 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2256 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2257 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2258 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002259 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2260 PBI->setSuccessor(1, FalseDest);
2261 }
Manman Renbfb9d432012-09-15 00:39:57 +00002262 if (NewWeights.size() == 2) {
2263 // Halve the weights if any of them cannot fit in an uint32_t
2264 FitWeights(NewWeights);
2265
2266 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2267 PBI->setMetadata(LLVMContext::MD_prof,
2268 MDBuilder(BI->getContext()).
2269 createBranchWeights(MDWeights));
2270 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002271 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002272 } else {
2273 // Update PHI nodes in the common successors.
2274 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002275 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002276 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2277 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002278 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002279 if (PBI->getSuccessor(0) == TrueDest) {
2280 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2281 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2282 // is false: !PBI_Cond and BI_Value
2283 Instruction *NotCond =
2284 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2285 "not.cond"));
2286 MergedCond =
2287 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2288 NotCond, New,
2289 "and.cond"));
2290 if (PBI_C->isOne())
2291 MergedCond =
2292 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2293 PBI->getCondition(), MergedCond,
2294 "or.cond"));
2295 } else {
2296 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2297 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2298 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002299 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002300 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2301 PBI->getCondition(), New,
2302 "and.cond"));
2303 if (PBI_C->isOne()) {
2304 Instruction *NotCond =
2305 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2306 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002307 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002308 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2309 NotCond, MergedCond,
2310 "or.cond"));
2311 }
2312 }
2313 // Update PHI Node.
2314 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2315 MergedCond);
2316 }
2317 // Change PBI from Conditional to Unconditional.
2318 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2319 EraseTerminatorInstAndDCECond(PBI);
2320 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002321 }
Devang Pateld715ec82011-04-06 22:37:20 +00002322
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002323 // TODO: If BB is reachable from all paths through PredBlock, then we
2324 // could replace PBI's branch probabilities with BI's.
2325
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002326 // Copy any debug value intrinsics into the end of PredBlock.
2327 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2328 if (isa<DbgInfoIntrinsic>(*I))
2329 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002330
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002331 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002332 }
2333 return false;
2334}
2335
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002336/// If we have a conditional branch as a predecessor of another block,
2337/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002338/// that PBI and BI are both conditional branches, and BI is in one of the
2339/// successor blocks of PBI - PBI branches to BI.
2340static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2341 assert(PBI->isConditional() && BI->isConditional());
2342 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002343
Chris Lattner9aada1d2008-07-13 21:53:26 +00002344 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002345 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002346 // this conditional branch redundant.
2347 if (PBI->getCondition() == BI->getCondition() &&
2348 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2349 // Okay, the outcome of this conditional branch is statically
2350 // knowable. If this block had a single pred, handle specially.
2351 if (BB->getSinglePredecessor()) {
2352 // Turn this into a branch on constant.
2353 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002354 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002355 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002356 return true; // Nuke the branch on constant.
2357 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002358
Chris Lattner9aada1d2008-07-13 21:53:26 +00002359 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2360 // in the constant and simplify the block result. Subsequent passes of
2361 // simplifycfg will thread the block.
2362 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002363 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002364 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002365 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002366 BI->getCondition()->getName() + ".pr",
2367 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002368 // Okay, we're going to insert the PHI node. Since PBI is not the only
2369 // predecessor, compute the PHI'd conditional value for all of the preds.
2370 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002371 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002372 BasicBlock *P = *PI;
2373 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002374 PBI != BI && PBI->isConditional() &&
2375 PBI->getCondition() == BI->getCondition() &&
2376 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2377 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002378 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002379 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002380 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002381 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002382 }
Gabor Greif8629f122010-07-12 10:59:23 +00002383 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002384
Chris Lattner9aada1d2008-07-13 21:53:26 +00002385 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002386 return true;
2387 }
2388 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002389
Chris Lattner9aada1d2008-07-13 21:53:26 +00002390 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002391 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002392 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002393 BasicBlock::iterator BBI = BB->begin();
2394 // Ignore dbg intrinsics.
2395 while (isa<DbgInfoIntrinsic>(BBI))
2396 ++BBI;
2397 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002398 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002399
Andrew Trickf3cf1932012-08-29 21:46:36 +00002400
Chris Lattnerc59945b2009-01-20 01:15:41 +00002401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2402 if (CE->canTrap())
2403 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002404
Chris Lattner834ab4e2008-07-13 22:04:41 +00002405 int PBIOp, BIOp;
2406 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2407 PBIOp = BIOp = 0;
2408 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2409 PBIOp = 0, BIOp = 1;
2410 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2411 PBIOp = 1, BIOp = 0;
2412 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2413 PBIOp = BIOp = 1;
2414 else
2415 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002416
Chris Lattner834ab4e2008-07-13 22:04:41 +00002417 // Check to make sure that the other destination of this branch
2418 // isn't BB itself. If so, this is an infinite loop that will
2419 // keep getting unwound.
2420 if (PBI->getSuccessor(PBIOp) == BB)
2421 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002422
2423 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002424 // insertion of a large number of select instructions. For targets
2425 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002426
Sanjay Patela932da82014-07-07 21:19:00 +00002427 // Also do not perform this transformation if any phi node in the common
2428 // destination block can trap when reached by BB or PBB (PR17073). In that
2429 // case, it would be unsafe to hoist the operation into a select instruction.
2430
2431 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002432 unsigned NumPhis = 0;
2433 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002434 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002435 if (NumPhis > 2) // Disable this xform.
2436 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002437
Sanjay Patela932da82014-07-07 21:19:00 +00002438 PHINode *PN = cast<PHINode>(II);
2439 Value *BIV = PN->getIncomingValueForBlock(BB);
2440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2441 if (CE->canTrap())
2442 return false;
2443
2444 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2445 Value *PBIV = PN->getIncomingValue(PBBIdx);
2446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2447 if (CE->canTrap())
2448 return false;
2449 }
2450
Chris Lattner834ab4e2008-07-13 22:04:41 +00002451 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002452 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002453
David Greene725c7c32010-01-05 01:26:52 +00002454 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002455 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002456
2457
Chris Lattner80b03a12008-07-13 22:23:11 +00002458 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2459 // branch in it, where one edge (OtherDest) goes back to itself but the other
2460 // exits. We don't *know* that the program avoids the infinite loop
2461 // (even though that seems likely). If we do this xform naively, we'll end up
2462 // recursively unpeeling the loop. Since we know that (after the xform is
2463 // done) that the block *is* infinite if reached, we just make it an obviously
2464 // infinite loop with no cond branch.
2465 if (OtherDest == BB) {
2466 // Insert it at the end of the function, because it's either code,
2467 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002468 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2469 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002470 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2471 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002472 }
2473
David Greene725c7c32010-01-05 01:26:52 +00002474 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002475
Chris Lattner834ab4e2008-07-13 22:04:41 +00002476 // BI may have other predecessors. Because of this, we leave
2477 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002478
Chris Lattner834ab4e2008-07-13 22:04:41 +00002479 // Make sure we get to CommonDest on True&True directions.
2480 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002481 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002482 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002483 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2484
Chris Lattner834ab4e2008-07-13 22:04:41 +00002485 Value *BICond = BI->getCondition();
2486 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002487 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2488
Chris Lattner834ab4e2008-07-13 22:04:41 +00002489 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002490 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002491
Chris Lattner834ab4e2008-07-13 22:04:41 +00002492 // Modify PBI to branch on the new condition to the new dests.
2493 PBI->setCondition(Cond);
2494 PBI->setSuccessor(0, CommonDest);
2495 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002496
Manman Ren2d4c10f2012-09-17 21:30:40 +00002497 // Update branch weight for PBI.
2498 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002499 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2500 PredFalseWeight);
2501 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2502 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002503 if (PredHasWeights && SuccHasWeights) {
2504 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2505 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2506 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2507 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2508 // The weight to CommonDest should be PredCommon * SuccTotal +
2509 // PredOther * SuccCommon.
2510 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002511 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2512 PredOther * SuccCommon,
2513 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002514 // Halve the weights if any of them cannot fit in an uint32_t
2515 FitWeights(NewWeights);
2516
Manman Ren2d4c10f2012-09-17 21:30:40 +00002517 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002518 MDBuilder(BI->getContext())
2519 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002520 }
2521
Chris Lattner834ab4e2008-07-13 22:04:41 +00002522 // OtherDest may have phi nodes. If so, add an entry from PBI's
2523 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002524 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002525
Chris Lattner834ab4e2008-07-13 22:04:41 +00002526 // We know that the CommonDest already had an edge from PBI to
2527 // it. If it has PHIs though, the PHIs may have different
2528 // entries for BB and PBI's BB. If so, insert a select to make
2529 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002530 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002531 for (BasicBlock::iterator II = CommonDest->begin();
2532 (PN = dyn_cast<PHINode>(II)); ++II) {
2533 Value *BIV = PN->getIncomingValueForBlock(BB);
2534 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2535 Value *PBIV = PN->getIncomingValue(PBBIdx);
2536 if (BIV != PBIV) {
2537 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002538 Value *NV = cast<SelectInst>
2539 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002540 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002541 }
2542 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002543
David Greene725c7c32010-01-05 01:26:52 +00002544 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2545 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002546
Chris Lattner834ab4e2008-07-13 22:04:41 +00002547 // This basic block is probably dead. We know it has at least
2548 // one fewer predecessor.
2549 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002550}
2551
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002552// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2553// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002554// Takes care of updating the successors and removing the old terminator.
2555// Also makes sure not to introduce new successors by assuming that edges to
2556// non-successor TrueBBs and FalseBBs aren't reachable.
2557static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002558 BasicBlock *TrueBB, BasicBlock *FalseBB,
2559 uint32_t TrueWeight,
2560 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002561 // Remove any superfluous successor edges from the CFG.
2562 // First, figure out which successors to preserve.
2563 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2564 // successor.
2565 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002566 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002567
2568 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002569 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002570 // Make sure only to keep exactly one copy of each edge.
2571 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002572 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002573 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002574 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002575 else
2576 Succ->removePredecessor(OldTerm->getParent());
2577 }
2578
Devang Patel2c2ea222011-05-18 18:43:31 +00002579 IRBuilder<> Builder(OldTerm);
2580 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2581
Frits van Bommel8e158492011-01-11 12:52:11 +00002582 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002583 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002584 if (TrueBB == FalseBB)
2585 // We were only looking for one successor, and it was present.
2586 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002587 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002588 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002589 // We found both of the successors we were looking for.
2590 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002591 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2592 if (TrueWeight != FalseWeight)
2593 NewBI->setMetadata(LLVMContext::MD_prof,
2594 MDBuilder(OldTerm->getContext()).
2595 createBranchWeights(TrueWeight, FalseWeight));
2596 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002597 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2598 // Neither of the selected blocks were successors, so this
2599 // terminator must be unreachable.
2600 new UnreachableInst(OldTerm->getContext(), OldTerm);
2601 } else {
2602 // One of the selected values was a successor, but the other wasn't.
2603 // Insert an unconditional branch to the one that was found;
2604 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002605 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002606 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002607 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002608 else
2609 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002610 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002611 }
2612
2613 EraseTerminatorInstAndDCECond(OldTerm);
2614 return true;
2615}
2616
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002617// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002618// (switch (select cond, X, Y)) on constant X, Y
2619// with a branch - conditional if X and Y lead to distinct BBs,
2620// unconditional otherwise.
2621static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2622 // Check for constant integer values in the select.
2623 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2624 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2625 if (!TrueVal || !FalseVal)
2626 return false;
2627
2628 // Find the relevant condition and destinations.
2629 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002630 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2631 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002632
Manman Ren774246a2012-09-17 22:28:55 +00002633 // Get weight for TrueBB and FalseBB.
2634 uint32_t TrueWeight = 0, FalseWeight = 0;
2635 SmallVector<uint64_t, 8> Weights;
2636 bool HasWeights = HasBranchWeights(SI);
2637 if (HasWeights) {
2638 GetBranchWeights(SI, Weights);
2639 if (Weights.size() == 1 + SI->getNumCases()) {
2640 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2641 getSuccessorIndex()];
2642 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2643 getSuccessorIndex()];
2644 }
2645 }
2646
Frits van Bommel8ae07992011-02-28 09:44:07 +00002647 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002648 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2649 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002650}
2651
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002652// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002653// (indirectbr (select cond, blockaddress(@fn, BlockA),
2654// blockaddress(@fn, BlockB)))
2655// with
2656// (br cond, BlockA, BlockB).
2657static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2658 // Check that both operands of the select are block addresses.
2659 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2660 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2661 if (!TBA || !FBA)
2662 return false;
2663
2664 // Extract the actual blocks.
2665 BasicBlock *TrueBB = TBA->getBasicBlock();
2666 BasicBlock *FalseBB = FBA->getBasicBlock();
2667
Frits van Bommel8e158492011-01-11 12:52:11 +00002668 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002669 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2670 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002671}
2672
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002673/// This is called when we find an icmp instruction
2674/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002675/// block that ends with an uncond branch. We are looking for a very specific
2676/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2677/// this case, we merge the first two "or's of icmp" into a switch, but then the
2678/// default value goes to an uncond block with a seteq in it, we get something
2679/// like:
2680///
2681/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2682/// DEFAULT:
2683/// %tmp = icmp eq i8 %A, 92
2684/// br label %end
2685/// end:
2686/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002687///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002688/// We prefer to split the edge to 'end' so that there is a true/false entry to
2689/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002690static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002691 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
2692 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
2693 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002694 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002695
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002696 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2697 // complex.
2698 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2699
2700 Value *V = ICI->getOperand(0);
2701 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002702
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002703 // The pattern we're looking for is where our only predecessor is a switch on
2704 // 'V' and this block is the default case for the switch. In this case we can
2705 // fold the compared value into the switch to simplify things.
2706 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002707 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002708
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002709 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2710 if (SI->getCondition() != V)
2711 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002712
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002713 // If BB is reachable on a non-default case, then we simply know the value of
2714 // V in this block. Substitute it and constant fold the icmp instruction
2715 // away.
2716 if (SI->getDefaultDest() != BB) {
2717 ConstantInt *VVal = SI->findCaseDest(BB);
2718 assert(VVal && "Should have a unique destination value");
2719 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002720
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002721 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002722 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002723 ICI->eraseFromParent();
2724 }
2725 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002726 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002727 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002728
Chris Lattner62cc76e2010-12-13 03:43:57 +00002729 // Ok, the block is reachable from the default dest. If the constant we're
2730 // comparing exists in one of the other edges, then we can constant fold ICI
2731 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002732 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002733 Value *V;
2734 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2735 V = ConstantInt::getFalse(BB->getContext());
2736 else
2737 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002738
Chris Lattner62cc76e2010-12-13 03:43:57 +00002739 ICI->replaceAllUsesWith(V);
2740 ICI->eraseFromParent();
2741 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002742 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002743 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002744
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002745 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2746 // the block.
2747 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002748 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002749 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002750 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2751 return false;
2752
2753 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2754 // true in the PHI.
2755 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2756 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2757
2758 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2759 std::swap(DefaultCst, NewCst);
2760
2761 // Replace ICI (which is used by the PHI for the default value) with true or
2762 // false depending on if it is EQ or NE.
2763 ICI->replaceAllUsesWith(DefaultCst);
2764 ICI->eraseFromParent();
2765
2766 // Okay, the switch goes to this block on a default value. Add an edge from
2767 // the switch to the merge point on the compared value.
2768 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2769 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002770 SmallVector<uint64_t, 8> Weights;
2771 bool HasWeights = HasBranchWeights(SI);
2772 if (HasWeights) {
2773 GetBranchWeights(SI, Weights);
2774 if (Weights.size() == 1 + SI->getNumCases()) {
2775 // Split weight for default case to case for "Cst".
2776 Weights[0] = (Weights[0]+1) >> 1;
2777 Weights.push_back(Weights[0]);
2778
2779 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2780 SI->setMetadata(LLVMContext::MD_prof,
2781 MDBuilder(SI->getContext()).
2782 createBranchWeights(MDWeights));
2783 }
2784 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002785 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002786
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002787 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002788 Builder.SetInsertPoint(NewBB);
2789 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2790 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002791 PHIUse->addIncoming(NewCst, NewBB);
2792 return true;
2793}
2794
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002795/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00002796/// Check to see if it is branching on an or/and chain of icmp instructions, and
2797/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002798static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
2799 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002800 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002801 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002802
Chris Lattnera69c4432010-12-13 05:03:41 +00002803 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2804 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2805 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002806
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002807 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00002808 ConstantComparesGatherer ConstantCompare(Cond, DL);
2809 // Unpack the result
2810 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2811 Value *CompVal = ConstantCompare.CompValue;
2812 unsigned UsedICmps = ConstantCompare.UsedICmps;
2813 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002814
Chris Lattnera69c4432010-12-13 05:03:41 +00002815 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002816 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002817
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002818 // Avoid turning single icmps into a switch.
2819 if (UsedICmps <= 1)
2820 return false;
2821
Mehdi Aminiffd01002014-11-20 22:40:25 +00002822 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2823
Chris Lattnera69c4432010-12-13 05:03:41 +00002824 // There might be duplicate constants in the list, which the switch
2825 // instruction can't handle, remove them now.
2826 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2827 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002828
Chris Lattnera69c4432010-12-13 05:03:41 +00002829 // If Extra was used, we require at least two switch values to do the
2830 // transformation. A switch with one value is just an cond branch.
2831 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002832
Andrew Trick3051aa12012-08-29 21:46:38 +00002833 // TODO: Preserve branch weight metadata, similarly to how
2834 // FoldValueComparisonIntoPredecessors preserves it.
2835
Chris Lattnera69c4432010-12-13 05:03:41 +00002836 // Figure out which block is which destination.
2837 BasicBlock *DefaultBB = BI->getSuccessor(1);
2838 BasicBlock *EdgeBB = BI->getSuccessor(0);
2839 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002840
Chris Lattnera69c4432010-12-13 05:03:41 +00002841 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002842
Chris Lattnerd7beca32010-12-14 06:17:25 +00002843 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002844 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002845
Chris Lattnera69c4432010-12-13 05:03:41 +00002846 // If there are any extra values that couldn't be folded into the switch
2847 // then we evaluate them with an explicit branch first. Split the block
2848 // right before the condbr to handle it.
2849 if (ExtraCase) {
2850 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2851 // Remove the uncond branch added to the old block.
2852 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002853 Builder.SetInsertPoint(OldTI);
2854
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002855 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002856 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002857 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002858 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002859
Chris Lattnera69c4432010-12-13 05:03:41 +00002860 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002861
Chris Lattnercb570f82010-12-13 05:34:18 +00002862 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2863 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002864 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002865
Chris Lattnerd7beca32010-12-14 06:17:25 +00002866 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2867 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002868 BB = NewBB;
2869 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002870
2871 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002872 // Convert pointer to int before we switch.
2873 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002874 CompVal = Builder.CreatePtrToInt(
2875 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002876 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002877
Chris Lattnera69c4432010-12-13 05:03:41 +00002878 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002879 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002880
Chris Lattnera69c4432010-12-13 05:03:41 +00002881 // Add all of the 'cases' to the switch instruction.
2882 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2883 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002884
Chris Lattnera69c4432010-12-13 05:03:41 +00002885 // We added edges from PI to the EdgeBB. As such, if there were any
2886 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2887 // the number of edges added.
2888 for (BasicBlock::iterator BBI = EdgeBB->begin();
2889 isa<PHINode>(BBI); ++BBI) {
2890 PHINode *PN = cast<PHINode>(BBI);
2891 Value *InVal = PN->getIncomingValueForBlock(BB);
2892 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2893 PN->addIncoming(InVal, BB);
2894 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002895
Chris Lattnera69c4432010-12-13 05:03:41 +00002896 // Erase the old branch instruction.
2897 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002898
Chris Lattnerd7beca32010-12-14 06:17:25 +00002899 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002900 return true;
2901}
2902
Andrew Kaylor50e4e862015-09-04 23:39:40 +00002903// FIXME: This seems like a pretty common thing to want to do. Consider
2904// whether there is a more accessible place to put this.
2905static void convertInvokeToCall(InvokeInst *II) {
2906 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2907 // Insert a call instruction before the invoke.
2908 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2909 Call->takeName(II);
2910 Call->setCallingConv(II->getCallingConv());
2911 Call->setAttributes(II->getAttributes());
2912 Call->setDebugLoc(II->getDebugLoc());
2913
2914 // Anything that used the value produced by the invoke instruction now uses
2915 // the value produced by the call instruction. Note that we do this even
2916 // for void functions and calls with no uses so that the callgraph edge is
2917 // updated.
2918 II->replaceAllUsesWith(Call);
2919 II->getUnwindDest()->removePredecessor(II->getParent());
2920
2921 // Insert a branch to the normal destination right before the invoke.
2922 BranchInst::Create(II->getNormalDest(), II);
2923
2924 // Finally, delete the invoke instruction!
2925 II->eraseFromParent();
2926}
2927
Duncan Sands29192d02011-09-05 12:57:57 +00002928bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2929 // If this is a trivial landing pad that just continues unwinding the caught
2930 // exception then zap the landing pad, turning its invokes into calls.
2931 BasicBlock *BB = RI->getParent();
2932 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2933 if (RI->getValue() != LPInst)
2934 // Not a landing pad, or the resume is not unwinding the exception that
2935 // caused control to branch here.
2936 return false;
2937
2938 // Check that there are no other instructions except for debug intrinsics.
2939 BasicBlock::iterator I = LPInst, E = RI;
2940 while (++I != E)
2941 if (!isa<DbgInfoIntrinsic>(I))
2942 return false;
2943
2944 // Turn all invokes that unwind here into calls and delete the basic block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002945 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2946 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Andrew Kaylor50e4e862015-09-04 23:39:40 +00002947 convertInvokeToCall(II);
Duncan Sands29192d02011-09-05 12:57:57 +00002948 }
2949
Reid Klecknerf12b3342015-01-22 19:29:46 +00002950 // The landingpad is now unreachable. Zap it.
2951 BB->eraseFromParent();
2952 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00002953}
2954
Andrew Kaylor50e4e862015-09-04 23:39:40 +00002955bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
2956 // If this is a trivial cleanup pad that executes no instructions, it can be
2957 // eliminated. If the cleanup pad continues to the caller, any predecessor
2958 // that is an EH pad will be updated to continue to the caller and any
2959 // predecessor that terminates with an invoke instruction will have its invoke
2960 // instruction converted to a call instruction. If the cleanup pad being
2961 // simplified does not continue to the caller, each predecessor will be
2962 // updated to continue to the unwind destination of the cleanup pad being
2963 // simplified.
2964 BasicBlock *BB = RI->getParent();
2965 Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI());
2966 if (!CPInst)
2967 // This isn't an empty cleanup.
2968 return false;
2969
2970 // Check that there are no other instructions except for debug intrinsics.
2971 BasicBlock::iterator I = CPInst, E = RI;
2972 while (++I != E)
2973 if (!isa<DbgInfoIntrinsic>(I))
2974 return false;
2975
2976 // If the cleanup return we are simplifying unwinds to the caller, this
2977 // will set UnwindDest to nullptr.
2978 BasicBlock *UnwindDest = RI->getUnwindDest();
2979
2980 // We're about to remove BB from the control flow. Before we do, sink any
2981 // PHINodes into the unwind destination. Doing this before changing the
2982 // control flow avoids some potentially slow checks, since we can currently
2983 // be certain that UnwindDest and BB have no common predecessors (since they
2984 // are both EH pads).
2985 if (UnwindDest) {
2986 // First, go through the PHI nodes in UnwindDest and update any nodes that
2987 // reference the block we are removing
2988 for (BasicBlock::iterator I = UnwindDest->begin(),
2989 IE = UnwindDest->getFirstNonPHI();
2990 I != IE; ++I) {
2991 PHINode *DestPN = cast<PHINode>(I);
2992
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00002993 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00002994 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00002995 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00002996 // This PHI node has an incoming value that corresponds to a control
2997 // path through the cleanup pad we are removing. If the incoming
2998 // value is in the cleanup pad, it must be a PHINode (because we
2999 // verified above that the block is otherwise empty). Otherwise, the
3000 // value is either a constant or a value that dominates the cleanup
3001 // pad being removed.
3002 //
3003 // Because BB and UnwindDest are both EH pads, all of their
3004 // predecessors must unwind to these blocks, and since no instruction
3005 // can have multiple unwind destinations, there will be no overlap in
3006 // incoming blocks between SrcPN and DestPN.
3007 Value *SrcVal = DestPN->getIncomingValue(Idx);
3008 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3009
3010 // Remove the entry for the block we are deleting.
3011 DestPN->removeIncomingValue(Idx, false);
3012
3013 if (SrcPN && SrcPN->getParent() == BB) {
3014 // If the incoming value was a PHI node in the cleanup pad we are
3015 // removing, we need to merge that PHI node's incoming values into
3016 // DestPN.
3017 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3018 SrcIdx != SrcE; ++SrcIdx) {
3019 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3020 SrcPN->getIncomingBlock(SrcIdx));
3021 }
3022 } else {
3023 // Otherwise, the incoming value came from above BB and
3024 // so we can just reuse it. We must associate all of BB's
3025 // predecessors with this value.
3026 for (auto *pred : predecessors(BB)) {
3027 DestPN->addIncoming(SrcVal, pred);
3028 }
3029 }
3030 }
3031
3032 // Sink any remaining PHI nodes directly into UnwindDest.
3033 Instruction *InsertPt = UnwindDest->getFirstNonPHI();
3034 for (BasicBlock::iterator I = BB->begin(), IE = BB->getFirstNonPHI();
3035 I != IE;) {
3036 // The iterator must be incremented here because the instructions are
3037 // being moved to another block.
3038 PHINode *PN = cast<PHINode>(I++);
3039 if (PN->use_empty())
3040 // If the PHI node has no uses, just leave it. It will be erased
3041 // when we erase BB below.
3042 continue;
3043
3044 // Otherwise, sink this PHI node into UnwindDest.
3045 // Any predecessors to UnwindDest which are not already represented
3046 // must be back edges which inherit the value from the path through
3047 // BB. In this case, the PHI value must reference itself.
3048 for (auto *pred : predecessors(UnwindDest))
3049 if (pred != BB)
3050 PN->addIncoming(PN, pred);
3051 PN->moveBefore(InsertPt);
3052 }
3053 }
3054
3055 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3056 // The iterator must be updated here because we are removing this pred.
3057 BasicBlock *PredBB = *PI++;
3058 TerminatorInst *TI = PredBB->getTerminator();
3059 if (UnwindDest == nullptr) {
3060 if (auto *II = dyn_cast<InvokeInst>(TI)) {
3061 // The cleanup return being simplified continues to the caller and this
3062 // predecessor terminated with an invoke instruction. Convert the
3063 // invoke to a call.
3064 // This call updates the predecessor/successor chain.
3065 convertInvokeToCall(II);
3066 } else {
3067 // In the remaining cases the predecessor's terminator unwinds to the
3068 // block we are removing. We need to create a new instruction that
3069 // unwinds to the caller. Simply setting the unwind destination to
3070 // nullptr would leave the objects internal data in an inconsistent
3071 // state.
3072 // FIXME: Consider whether it is better to update setUnwindDest to
3073 // keep things consistent.
3074 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3075 auto *NewCRI = CleanupReturnInst::Create(CRI->getCleanupPad(),
3076 nullptr, CRI);
3077 NewCRI->takeName(CRI);
3078 NewCRI->setDebugLoc(CRI->getDebugLoc());
3079 CRI->eraseFromParent();
3080 } else if (auto *CEP = dyn_cast<CatchEndPadInst>(TI)) {
3081 auto *NewCEP = CatchEndPadInst::Create(CEP->getContext(), nullptr,
3082 CEP);
3083 NewCEP->takeName(CEP);
3084 NewCEP->setDebugLoc(CEP->getDebugLoc());
3085 CEP->eraseFromParent();
3086 } else if (auto *TPI = dyn_cast<TerminatePadInst>(TI)) {
3087 SmallVector<Value *, 3> TerminatePadArgs;
3088 for (Value *Operand : TPI->arg_operands())
3089 TerminatePadArgs.push_back(Operand);
3090 auto *NewTPI = TerminatePadInst::Create(TPI->getContext(), nullptr,
3091 TerminatePadArgs, TPI);
3092 NewTPI->takeName(TPI);
3093 NewTPI->setDebugLoc(TPI->getDebugLoc());
3094 TPI->eraseFromParent();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003095 } else {
3096 llvm_unreachable("Unexpected predecessor to cleanup pad.");
3097 }
3098 }
3099 } else {
3100 // If the predecessor did not terminate with an invoke instruction, it
3101 // must be some variety of EH pad.
3102 TerminatorInst *TI = PredBB->getTerminator();
3103 // FIXME: Introducing an EH terminator base class would simplify this.
3104 if (auto *II = dyn_cast<InvokeInst>(TI))
3105 II->setUnwindDest(UnwindDest);
3106 else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
3107 CRI->setUnwindDest(UnwindDest);
3108 else if (auto *CEP = dyn_cast<CatchEndPadInst>(TI))
3109 CEP->setUnwindDest(UnwindDest);
3110 else if (auto *TPI = dyn_cast<TerminatePadInst>(TI))
3111 TPI->setUnwindDest(UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003112 else
3113 llvm_unreachable("Unexpected predecessor to cleanup pad.");
3114 }
3115 }
3116
3117 // The cleanup pad is now unreachable. Zap it.
3118 BB->eraseFromParent();
3119 return true;
3120}
3121
Devang Pateldd14e0f2011-05-18 21:33:11 +00003122bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003123 BasicBlock *BB = RI->getParent();
3124 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003125
Chris Lattner25c3af32010-12-13 06:25:44 +00003126 // Find predecessors that end with branches.
3127 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3128 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003129 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3130 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003131 TerminatorInst *PTI = P->getTerminator();
3132 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3133 if (BI->isUnconditional())
3134 UncondBranchPreds.push_back(P);
3135 else
3136 CondBranchPreds.push_back(BI);
3137 }
3138 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003139
Chris Lattner25c3af32010-12-13 06:25:44 +00003140 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003141 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003142 while (!UncondBranchPreds.empty()) {
3143 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3144 DEBUG(dbgs() << "FOLDING: " << *BB
3145 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003146 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003147 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003148
Chris Lattner25c3af32010-12-13 06:25:44 +00003149 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003150 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003151 // We know there are no successors, so just nuke the block.
3152 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003153
Chris Lattner25c3af32010-12-13 06:25:44 +00003154 return true;
3155 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003156
Chris Lattner25c3af32010-12-13 06:25:44 +00003157 // Check out all of the conditional branches going to this return
3158 // instruction. If any of them just select between returns, change the
3159 // branch itself into a select/return pair.
3160 while (!CondBranchPreds.empty()) {
3161 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003162
Chris Lattner25c3af32010-12-13 06:25:44 +00003163 // Check to see if the non-BB successor is also a return block.
3164 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3165 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003166 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003167 return true;
3168 }
3169 return false;
3170}
3171
Chris Lattner25c3af32010-12-13 06:25:44 +00003172bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3173 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003174
Chris Lattner25c3af32010-12-13 06:25:44 +00003175 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003176
Chris Lattner25c3af32010-12-13 06:25:44 +00003177 // If there are any instructions immediately before the unreachable that can
3178 // be removed, do so.
3179 while (UI != BB->begin()) {
3180 BasicBlock::iterator BBI = UI;
3181 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003182 // Do not delete instructions that can have side effects which might cause
3183 // the unreachable to not be reachable; specifically, calls and volatile
3184 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003185 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003186
3187 if (BBI->mayHaveSideEffects()) {
3188 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3189 if (SI->isVolatile())
3190 break;
3191 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3192 if (LI->isVolatile())
3193 break;
3194 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3195 if (RMWI->isVolatile())
3196 break;
3197 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3198 if (CXI->isVolatile())
3199 break;
3200 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3201 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003202 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003203 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003204 // Note that deleting LandingPad's here is in fact okay, although it
3205 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3206 // all the predecessors of this block will be the unwind edges of Invokes,
3207 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003208 }
3209
Eli Friedmanaac35b32011-03-09 00:48:33 +00003210 // Delete this instruction (any uses are guaranteed to be dead)
3211 if (!BBI->use_empty())
3212 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003213 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003214 Changed = true;
3215 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003216
Chris Lattner25c3af32010-12-13 06:25:44 +00003217 // If the unreachable instruction is the first in the block, take a gander
3218 // at all of the predecessors of this instruction, and simplify them.
3219 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003220
Chris Lattner25c3af32010-12-13 06:25:44 +00003221 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3222 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3223 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003224 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003225 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3226 if (BI->isUnconditional()) {
3227 if (BI->getSuccessor(0) == BB) {
3228 new UnreachableInst(TI->getContext(), TI);
3229 TI->eraseFromParent();
3230 Changed = true;
3231 }
3232 } else {
3233 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003234 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003235 EraseTerminatorInstAndDCECond(BI);
3236 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003237 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003238 EraseTerminatorInstAndDCECond(BI);
3239 Changed = true;
3240 }
3241 }
3242 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003243 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003244 i != e; ++i)
3245 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003246 BB->removePredecessor(SI->getParent());
3247 SI->removeCase(i);
3248 --i; --e;
3249 Changed = true;
3250 }
Chris Lattner25c3af32010-12-13 06:25:44 +00003251 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3252 if (II->getUnwindDest() == BB) {
3253 // Convert the invoke to a call instruction. This would be a good
3254 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003255 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003256 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003257
Chris Lattner25c3af32010-12-13 06:25:44 +00003258 // Insert the call now...
3259 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003260 Builder.SetInsertPoint(BI);
3261 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003262 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003263 CI->setCallingConv(II->getCallingConv());
3264 CI->setAttributes(II->getAttributes());
3265 // If the invoke produced a value, the call does now instead.
3266 II->replaceAllUsesWith(CI);
3267 delete II;
3268 Changed = true;
3269 }
3270 }
3271 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003272
Chris Lattner25c3af32010-12-13 06:25:44 +00003273 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003274 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003275 BB != &BB->getParent()->getEntryBlock()) {
3276 // We know there are no successors, so just nuke the block.
3277 BB->eraseFromParent();
3278 return true;
3279 }
3280
3281 return Changed;
3282}
3283
Hans Wennborg68000082015-01-26 19:52:32 +00003284static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3285 assert(Cases.size() >= 1);
3286
3287 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3288 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3289 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3290 return false;
3291 }
3292 return true;
3293}
3294
3295/// Turn a switch with two reachable destinations into an integer range
3296/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003297static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003298 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003299
Hans Wennborg68000082015-01-26 19:52:32 +00003300 bool HasDefault =
3301 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003302
Hans Wennborg68000082015-01-26 19:52:32 +00003303 // Partition the cases into two sets with different destinations.
3304 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3305 BasicBlock *DestB = nullptr;
3306 SmallVector <ConstantInt *, 16> CasesA;
3307 SmallVector <ConstantInt *, 16> CasesB;
3308
3309 for (SwitchInst::CaseIt I : SI->cases()) {
3310 BasicBlock *Dest = I.getCaseSuccessor();
3311 if (!DestA) DestA = Dest;
3312 if (Dest == DestA) {
3313 CasesA.push_back(I.getCaseValue());
3314 continue;
3315 }
3316 if (!DestB) DestB = Dest;
3317 if (Dest == DestB) {
3318 CasesB.push_back(I.getCaseValue());
3319 continue;
3320 }
3321 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003322 }
3323
Hans Wennborg68000082015-01-26 19:52:32 +00003324 assert(DestA && DestB && "Single-destination switch should have been folded.");
3325 assert(DestA != DestB);
3326 assert(DestB != SI->getDefaultDest());
3327 assert(!CasesB.empty() && "There must be non-default cases.");
3328 assert(!CasesA.empty() || HasDefault);
3329
3330 // Figure out if one of the sets of cases form a contiguous range.
3331 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3332 BasicBlock *ContiguousDest = nullptr;
3333 BasicBlock *OtherDest = nullptr;
3334 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3335 ContiguousCases = &CasesA;
3336 ContiguousDest = DestA;
3337 OtherDest = DestB;
3338 } else if (CasesAreContiguous(CasesB)) {
3339 ContiguousCases = &CasesB;
3340 ContiguousDest = DestB;
3341 OtherDest = DestA;
3342 } else
3343 return false;
3344
3345 // Start building the compare and branch.
3346
3347 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3348 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003349
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003350 Value *Sub = SI->getCondition();
3351 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003352 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3353
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003354 Value *Cmp;
3355 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003356 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003357 Cmp = ConstantInt::getTrue(SI->getContext());
3358 else
3359 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003360 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003361
Manman Ren56575552012-09-18 00:47:33 +00003362 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003363 if (HasBranchWeights(SI)) {
3364 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003365 GetBranchWeights(SI, Weights);
3366 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003367 uint64_t TrueWeight = 0;
3368 uint64_t FalseWeight = 0;
3369 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3370 if (SI->getSuccessor(I) == ContiguousDest)
3371 TrueWeight += Weights[I];
3372 else
3373 FalseWeight += Weights[I];
3374 }
3375 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3376 TrueWeight /= 2;
3377 FalseWeight /= 2;
3378 }
Manman Ren56575552012-09-18 00:47:33 +00003379 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003380 MDBuilder(SI->getContext()).createBranchWeights(
3381 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003382 }
3383 }
3384
Hans Wennborg68000082015-01-26 19:52:32 +00003385 // Prune obsolete incoming values off the successors' PHI nodes.
3386 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3387 unsigned PreviousEdges = ContiguousCases->size();
3388 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3389 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003390 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3391 }
Hans Wennborg68000082015-01-26 19:52:32 +00003392 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3393 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3394 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3395 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3396 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3397 }
3398
3399 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003400 SI->eraseFromParent();
3401
3402 return true;
3403}
Chris Lattner25c3af32010-12-13 06:25:44 +00003404
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003405/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003406/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003407static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3408 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003409 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003410 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003411 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003412 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003413
3414 // Gather dead cases.
3415 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003416 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003417 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3418 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3419 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003420 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003421 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003422 }
3423 }
3424
Philip Reames98a2dab2015-08-26 23:56:46 +00003425 // If we can prove that the cases must cover all possible values, the
3426 // default destination becomes dead and we can remove it.
3427 bool HasDefault =
3428 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3429 if (HasDefault && Bits < 64 /* avoid overflow */ &&
3430 SI->getNumCases() == (1ULL << Bits)) {
3431 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3432 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3433 SI->getParent(), "");
3434 SI->setDefaultDest(NewDefault);
3435 SplitBlock(NewDefault, NewDefault->begin());
3436 auto *OldTI = NewDefault->getTerminator();
3437 new UnreachableInst(SI->getContext(), OldTI);
3438 EraseTerminatorInstAndDCECond(OldTI);
3439 return true;
3440 }
3441
Manman Ren56575552012-09-18 00:47:33 +00003442 SmallVector<uint64_t, 8> Weights;
3443 bool HasWeight = HasBranchWeights(SI);
3444 if (HasWeight) {
3445 GetBranchWeights(SI, Weights);
3446 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3447 }
3448
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003449 // Remove dead cases from the switch.
3450 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003451 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003452 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003453 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003454 if (HasWeight) {
3455 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3456 Weights.pop_back();
3457 }
3458
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003459 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003460 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003461 SI->removeCase(Case);
3462 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003463 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003464 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3465 SI->setMetadata(LLVMContext::MD_prof,
3466 MDBuilder(SI->getParent()->getContext()).
3467 createBranchWeights(MDWeights));
3468 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003469
3470 return !DeadCases.empty();
3471}
3472
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003473/// If BB would be eligible for simplification by
3474/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003475/// by an unconditional branch), look at the phi node for BB in the successor
3476/// block and see if the incoming value is equal to CaseValue. If so, return
3477/// the phi node, and set PhiIndex to BB's index in the phi node.
3478static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3479 BasicBlock *BB,
3480 int *PhiIndex) {
3481 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003482 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003483 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003484 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003485
3486 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3487 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003488 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003489
3490 BasicBlock *Succ = Branch->getSuccessor(0);
3491
3492 BasicBlock::iterator I = Succ->begin();
3493 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3494 int Idx = PHI->getBasicBlockIndex(BB);
3495 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3496
3497 Value *InValue = PHI->getIncomingValue(Idx);
3498 if (InValue != CaseValue) continue;
3499
3500 *PhiIndex = Idx;
3501 return PHI;
3502 }
3503
Craig Topperf40110f2014-04-25 05:29:35 +00003504 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003505}
3506
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003507/// Try to forward the condition of a switch instruction to a phi node
3508/// dominated by the switch, if that would mean that some of the destination
3509/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003510/// Returns true if a change is made.
3511static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3512 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3513 ForwardingNodesMap ForwardingNodes;
3514
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003515 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003516 ConstantInt *CaseValue = I.getCaseValue();
3517 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003518
3519 int PhiIndex;
3520 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3521 &PhiIndex);
3522 if (!PHI) continue;
3523
3524 ForwardingNodes[PHI].push_back(PhiIndex);
3525 }
3526
3527 bool Changed = false;
3528
3529 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3530 E = ForwardingNodes.end(); I != E; ++I) {
3531 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003532 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003533
3534 if (Indexes.size() < 2) continue;
3535
3536 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3537 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3538 Changed = true;
3539 }
3540
3541 return Changed;
3542}
3543
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003544/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003545/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003546static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003547 if (C->isThreadDependent())
3548 return false;
3549 if (C->isDLLImportDependent())
3550 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003551
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3553 return CE->isGEPWithNoNotionalOverIndexing();
3554
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003555 return isa<ConstantFP>(C) ||
3556 isa<ConstantInt>(C) ||
3557 isa<ConstantPointerNull>(C) ||
3558 isa<GlobalValue>(C) ||
3559 isa<UndefValue>(C);
3560}
3561
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003562/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003563/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003564static Constant *LookupConstant(Value *V,
3565 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3566 if (Constant *C = dyn_cast<Constant>(V))
3567 return C;
3568 return ConstantPool.lookup(V);
3569}
3570
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003571/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003572/// simple instructions such as binary operations where both operands are
3573/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003574/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003575static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003576ConstantFold(Instruction *I, const DataLayout &DL,
3577 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003578 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003579 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3580 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003581 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003582 if (A->isAllOnesValue())
3583 return LookupConstant(Select->getTrueValue(), ConstantPool);
3584 if (A->isNullValue())
3585 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003586 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003587 }
3588
Benjamin Kramer7c302602013-11-12 12:24:36 +00003589 SmallVector<Constant *, 4> COps;
3590 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3591 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3592 COps.push_back(A);
3593 else
Craig Topperf40110f2014-04-25 05:29:35 +00003594 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003595 }
3596
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003597 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003598 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3599 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003600 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003601
3602 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003603}
3604
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003605/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003606/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003607/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003608/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003609static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003610GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00003611 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003612 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3613 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003614 // The block from which we enter the common destination.
3615 BasicBlock *Pred = SI->getParent();
3616
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003617 // If CaseDest is empty except for some side-effect free instructions through
3618 // which we can constant-propagate the CaseVal, continue to its successor.
3619 SmallDenseMap<Value*, Constant*> ConstantPool;
3620 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3621 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3622 ++I) {
3623 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3624 // If the terminator is a simple branch, continue to the next block.
3625 if (T->getNumSuccessors() != 1)
3626 return false;
3627 Pred = CaseDest;
3628 CaseDest = T->getSuccessor(0);
3629 } else if (isa<DbgInfoIntrinsic>(I)) {
3630 // Skip debug intrinsic.
3631 continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003632 } else if (Constant *C = ConstantFold(I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003633 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003634
3635 // If the instruction has uses outside this block or a phi node slot for
3636 // the block, it is not safe to bypass the instruction since it would then
3637 // no longer dominate all its uses.
3638 for (auto &Use : I->uses()) {
3639 User *User = Use.getUser();
3640 if (Instruction *I = dyn_cast<Instruction>(User))
3641 if (I->getParent() == CaseDest)
3642 continue;
3643 if (PHINode *Phi = dyn_cast<PHINode>(User))
3644 if (Phi->getIncomingBlock(Use) == CaseDest)
3645 continue;
3646 return false;
3647 }
3648
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003649 ConstantPool.insert(std::make_pair(I, C));
3650 } else {
3651 break;
3652 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003653 }
3654
3655 // If we did not have a CommonDest before, use the current one.
3656 if (!*CommonDest)
3657 *CommonDest = CaseDest;
3658 // If the destination isn't the common one, abort.
3659 if (CaseDest != *CommonDest)
3660 return false;
3661
3662 // Get the values for this case from phi nodes in the destination block.
3663 BasicBlock::iterator I = (*CommonDest)->begin();
3664 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3665 int Idx = PHI->getBasicBlockIndex(Pred);
3666 if (Idx == -1)
3667 continue;
3668
Hans Wennborg09acdb92012-10-31 15:14:39 +00003669 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3670 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003671 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003672 return false;
3673
3674 // Be conservative about which kinds of constants we support.
3675 if (!ValidLookupTableConstant(ConstVal))
3676 return false;
3677
3678 Res.push_back(std::make_pair(PHI, ConstVal));
3679 }
3680
Hans Wennborgac114a32014-01-12 00:44:41 +00003681 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003682}
3683
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003684// Helper function used to add CaseVal to the list of cases that generate
3685// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003686static void MapCaseToResult(ConstantInt *CaseVal,
3687 SwitchCaseResultVectorTy &UniqueResults,
3688 Constant *Result) {
3689 for (auto &I : UniqueResults) {
3690 if (I.first == Result) {
3691 I.second.push_back(CaseVal);
3692 return;
3693 }
3694 }
3695 UniqueResults.push_back(std::make_pair(Result,
3696 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3697}
3698
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003699// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003700// results for the PHI node of the common destination block for a switch
3701// instruction. Returns false if multiple PHI nodes have been found or if
3702// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003703static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
3704 BasicBlock *&CommonDest,
3705 SwitchCaseResultVectorTy &UniqueResults,
3706 Constant *&DefaultResult,
3707 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003708 for (auto &I : SI->cases()) {
3709 ConstantInt *CaseVal = I.getCaseValue();
3710
3711 // Resulting value at phi nodes for this case value.
3712 SwitchCaseResultsTy Results;
3713 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3714 DL))
3715 return false;
3716
3717 // Only one value per case is permitted
3718 if (Results.size() > 1)
3719 return false;
3720 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3721
3722 // Check the PHI consistency.
3723 if (!PHI)
3724 PHI = Results[0].first;
3725 else if (PHI != Results[0].first)
3726 return false;
3727 }
3728 // Find the default result value.
3729 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3730 BasicBlock *DefaultDest = SI->getDefaultDest();
3731 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3732 DL);
3733 // If the default value is not found abort unless the default destination
3734 // is unreachable.
3735 DefaultResult =
3736 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3737 if ((!DefaultResult &&
3738 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3739 return false;
3740
3741 return true;
3742}
3743
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003744// Helper function that checks if it is possible to transform a switch with only
3745// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003746// Example:
3747// switch (a) {
3748// case 10: %0 = icmp eq i32 %a, 10
3749// return 10; %1 = select i1 %0, i32 10, i32 4
3750// case 20: ----> %2 = icmp eq i32 %a, 20
3751// return 2; %3 = select i1 %2, i32 2, i32 %1
3752// default:
3753// return 4;
3754// }
3755static Value *
3756ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3757 Constant *DefaultResult, Value *Condition,
3758 IRBuilder<> &Builder) {
3759 assert(ResultVector.size() == 2 &&
3760 "We should have exactly two unique results at this point");
3761 // If we are selecting between only two cases transform into a simple
3762 // select or a two-way select if default is possible.
3763 if (ResultVector[0].second.size() == 1 &&
3764 ResultVector[1].second.size() == 1) {
3765 ConstantInt *const FirstCase = ResultVector[0].second[0];
3766 ConstantInt *const SecondCase = ResultVector[1].second[0];
3767
3768 bool DefaultCanTrigger = DefaultResult;
3769 Value *SelectValue = ResultVector[1].first;
3770 if (DefaultCanTrigger) {
3771 Value *const ValueCompare =
3772 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3773 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3774 DefaultResult, "switch.select");
3775 }
3776 Value *const ValueCompare =
3777 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3778 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3779 "switch.select");
3780 }
3781
3782 return nullptr;
3783}
3784
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003785// Helper function to cleanup a switch instruction that has been converted into
3786// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003787static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3788 Value *SelectValue,
3789 IRBuilder<> &Builder) {
3790 BasicBlock *SelectBB = SI->getParent();
3791 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3792 PHI->removeIncomingValue(SelectBB);
3793 PHI->addIncoming(SelectValue, SelectBB);
3794
3795 Builder.CreateBr(PHI->getParent());
3796
3797 // Remove the switch.
3798 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3799 BasicBlock *Succ = SI->getSuccessor(i);
3800
3801 if (Succ == PHI->getParent())
3802 continue;
3803 Succ->removePredecessor(SelectBB);
3804 }
3805 SI->eraseFromParent();
3806}
3807
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003808/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003809/// phi nodes in a common successor block with only two different
3810/// constant values, replace the switch with select.
3811static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003812 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003813 Value *const Cond = SI->getCondition();
3814 PHINode *PHI = nullptr;
3815 BasicBlock *CommonDest = nullptr;
3816 Constant *DefaultResult;
3817 SwitchCaseResultVectorTy UniqueResults;
3818 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003819 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
3820 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003821 return false;
3822 // Selects choose between maximum two values.
3823 if (UniqueResults.size() != 2)
3824 return false;
3825 assert(PHI != nullptr && "PHI for value select not found");
3826
3827 Builder.SetInsertPoint(SI);
3828 Value *SelectValue = ConvertTwoCaseSwitch(
3829 UniqueResults,
3830 DefaultResult, Cond, Builder);
3831 if (SelectValue) {
3832 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3833 return true;
3834 }
3835 // The switch couldn't be converted into a select.
3836 return false;
3837}
3838
Hans Wennborg776d7122012-09-26 09:34:53 +00003839namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003840 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00003841 class SwitchLookupTable {
3842 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003843 /// Create a lookup table to use as a switch replacement with the contents
3844 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003845 SwitchLookupTable(
3846 Module &M, uint64_t TableSize, ConstantInt *Offset,
3847 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3848 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003849
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003850 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00003851 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003852 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003853
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003854 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00003855 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003856 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00003857 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003858
Hans Wennborg776d7122012-09-26 09:34:53 +00003859 private:
3860 // Depending on the contents of the table, it can be represented in
3861 // different ways.
3862 enum {
3863 // For tables where each element contains the same value, we just have to
3864 // store that single value and return it for each lookup.
3865 SingleValueKind,
3866
Erik Eckstein105374f2014-11-17 09:13:57 +00003867 // For tables where there is a linear relationship between table index
3868 // and values. We calculate the result with a simple multiplication
3869 // and addition instead of a table lookup.
3870 LinearMapKind,
3871
Hans Wennborg39583b82012-09-26 09:44:49 +00003872 // For small tables with integer elements, we can pack them into a bitmap
3873 // that fits into a target-legal register. Values are retrieved by
3874 // shift and mask operations.
3875 BitMapKind,
3876
Hans Wennborg776d7122012-09-26 09:34:53 +00003877 // The table is stored as an array of values. Values are retrieved by load
3878 // instructions from the table.
3879 ArrayKind
3880 } Kind;
3881
3882 // For SingleValueKind, this is the single value.
3883 Constant *SingleValue;
3884
Hans Wennborg39583b82012-09-26 09:44:49 +00003885 // For BitMapKind, this is the bitmap.
3886 ConstantInt *BitMap;
3887 IntegerType *BitMapElementTy;
3888
Erik Eckstein105374f2014-11-17 09:13:57 +00003889 // For LinearMapKind, these are the constants used to derive the value.
3890 ConstantInt *LinearOffset;
3891 ConstantInt *LinearMultiplier;
3892
Hans Wennborg776d7122012-09-26 09:34:53 +00003893 // For ArrayKind, this is the array.
3894 GlobalVariable *Array;
3895 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003896}
Hans Wennborg776d7122012-09-26 09:34:53 +00003897
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003898SwitchLookupTable::SwitchLookupTable(
3899 Module &M, uint64_t TableSize, ConstantInt *Offset,
3900 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3901 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003902 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003903 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003904 assert(Values.size() && "Can't build lookup table without values!");
3905 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003906
3907 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003908 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003909
Hans Wennborgac114a32014-01-12 00:44:41 +00003910 Type *ValueType = Values.begin()->second->getType();
3911
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003912 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003913 SmallVector<Constant*, 64> TableContents(TableSize);
3914 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3915 ConstantInt *CaseVal = Values[I].first;
3916 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003917 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003918
Hans Wennborg776d7122012-09-26 09:34:53 +00003919 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3920 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003921 TableContents[Idx] = CaseRes;
3922
Hans Wennborg776d7122012-09-26 09:34:53 +00003923 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003924 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003925 }
3926
3927 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003928 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003929 assert(DefaultValue &&
3930 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003931 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003932 for (uint64_t I = 0; I < TableSize; ++I) {
3933 if (!TableContents[I])
3934 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003935 }
3936
Hans Wennborg776d7122012-09-26 09:34:53 +00003937 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003938 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003939 }
3940
Hans Wennborg776d7122012-09-26 09:34:53 +00003941 // If each element in the table contains the same value, we only need to store
3942 // that single value.
3943 if (SingleValue) {
3944 Kind = SingleValueKind;
3945 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003946 }
3947
Erik Eckstein105374f2014-11-17 09:13:57 +00003948 // Check if we can derive the value with a linear transformation from the
3949 // table index.
3950 if (isa<IntegerType>(ValueType)) {
3951 bool LinearMappingPossible = true;
3952 APInt PrevVal;
3953 APInt DistToPrev;
3954 assert(TableSize >= 2 && "Should be a SingleValue table.");
3955 // Check if there is the same distance between two consecutive values.
3956 for (uint64_t I = 0; I < TableSize; ++I) {
3957 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3958 if (!ConstVal) {
3959 // This is an undef. We could deal with it, but undefs in lookup tables
3960 // are very seldom. It's probably not worth the additional complexity.
3961 LinearMappingPossible = false;
3962 break;
3963 }
3964 APInt Val = ConstVal->getValue();
3965 if (I != 0) {
3966 APInt Dist = Val - PrevVal;
3967 if (I == 1) {
3968 DistToPrev = Dist;
3969 } else if (Dist != DistToPrev) {
3970 LinearMappingPossible = false;
3971 break;
3972 }
3973 }
3974 PrevVal = Val;
3975 }
3976 if (LinearMappingPossible) {
3977 LinearOffset = cast<ConstantInt>(TableContents[0]);
3978 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3979 Kind = LinearMapKind;
3980 ++NumLinearMaps;
3981 return;
3982 }
3983 }
3984
Hans Wennborg39583b82012-09-26 09:44:49 +00003985 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003986 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003987 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003988 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3989 for (uint64_t I = TableSize; I > 0; --I) {
3990 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003991 // Insert values into the bitmap. Undef values are set to zero.
3992 if (!isa<UndefValue>(TableContents[I - 1])) {
3993 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3994 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3995 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003996 }
3997 BitMap = ConstantInt::get(M.getContext(), TableInt);
3998 BitMapElementTy = IT;
3999 Kind = BitMapKind;
4000 ++NumBitMaps;
4001 return;
4002 }
4003
Hans Wennborg776d7122012-09-26 09:34:53 +00004004 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004005 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004006 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4007
Hans Wennborg776d7122012-09-26 09:34:53 +00004008 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4009 GlobalVariable::PrivateLinkage,
4010 Initializer,
4011 "switch.table");
4012 Array->setUnnamedAddr(true);
4013 Kind = ArrayKind;
4014}
4015
Manman Ren4d189fb2014-07-24 21:13:20 +00004016Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004017 switch (Kind) {
4018 case SingleValueKind:
4019 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004020 case LinearMapKind: {
4021 // Derive the result value from the input value.
4022 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4023 false, "switch.idx.cast");
4024 if (!LinearMultiplier->isOne())
4025 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4026 if (!LinearOffset->isZero())
4027 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4028 return Result;
4029 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004030 case BitMapKind: {
4031 // Type of the bitmap (e.g. i59).
4032 IntegerType *MapTy = BitMap->getType();
4033
4034 // Cast Index to the same type as the bitmap.
4035 // Note: The Index is <= the number of elements in the table, so
4036 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004037 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004038
4039 // Multiply the shift amount by the element width.
4040 ShiftAmt = Builder.CreateMul(ShiftAmt,
4041 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4042 "switch.shiftamt");
4043
4044 // Shift down.
4045 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4046 "switch.downshift");
4047 // Mask off.
4048 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4049 "switch.masked");
4050 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004051 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004052 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004053 IntegerType *IT = cast<IntegerType>(Index->getType());
4054 uint64_t TableSize = Array->getInitializer()->getType()
4055 ->getArrayNumElements();
4056 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4057 Index = Builder.CreateZExt(Index,
4058 IntegerType::get(IT->getContext(),
4059 IT->getBitWidth() + 1),
4060 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004061
Hans Wennborg776d7122012-09-26 09:34:53 +00004062 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004063 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4064 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004065 return Builder.CreateLoad(GEP, "switch.load");
4066 }
4067 }
4068 llvm_unreachable("Unknown lookup table kind!");
4069}
4070
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004071bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004072 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004073 Type *ElementType) {
4074 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004075 if (!IT)
4076 return false;
4077 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4078 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004079
4080 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4081 if (TableSize >= UINT_MAX/IT->getBitWidth())
4082 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004083 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004084}
4085
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004086/// Determine whether a lookup table should be built for this switch, based on
4087/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004088static bool
4089ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4090 const TargetTransformInfo &TTI, const DataLayout &DL,
4091 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004092 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4093 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004094
Chandler Carruth77d433d2012-11-30 09:26:25 +00004095 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004096 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004097 for (const auto &I : ResultTypes) {
4098 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004099
4100 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004101 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004102
4103 // Saturate this flag to false.
4104 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004105 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004106
4107 // If both flags saturate, we're done. NOTE: This *only* works with
4108 // saturating flags, and all flags have to saturate first due to the
4109 // non-deterministic behavior of iterating over a dense map.
4110 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004111 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004112 }
Evan Cheng65df8082012-11-30 02:02:42 +00004113
Chandler Carruth77d433d2012-11-30 09:26:25 +00004114 // If each table would fit in a register, we should build it anyway.
4115 if (AllTablesFitInRegister)
4116 return true;
4117
4118 // Don't build a table that doesn't fit in-register if it has illegal types.
4119 if (HasIllegalType)
4120 return false;
4121
4122 // The table density should be at least 40%. This is the same criterion as for
4123 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4124 // FIXME: Find the best cut-off.
4125 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004126}
4127
Erik Eckstein0d86c762014-11-27 15:13:14 +00004128/// Try to reuse the switch table index compare. Following pattern:
4129/// \code
4130/// if (idx < tablesize)
4131/// r = table[idx]; // table does not contain default_value
4132/// else
4133/// r = default_value;
4134/// if (r != default_value)
4135/// ...
4136/// \endcode
4137/// Is optimized to:
4138/// \code
4139/// cond = idx < tablesize;
4140/// if (cond)
4141/// r = table[idx];
4142/// else
4143/// r = default_value;
4144/// if (cond)
4145/// ...
4146/// \endcode
4147/// Jump threading will then eliminate the second if(cond).
4148static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4149 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4150 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4151
4152 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4153 if (!CmpInst)
4154 return;
4155
4156 // We require that the compare is in the same block as the phi so that jump
4157 // threading can do its work afterwards.
4158 if (CmpInst->getParent() != PhiBlock)
4159 return;
4160
4161 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4162 if (!CmpOp1)
4163 return;
4164
4165 Value *RangeCmp = RangeCheckBranch->getCondition();
4166 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4167 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4168
4169 // Check if the compare with the default value is constant true or false.
4170 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4171 DefaultValue, CmpOp1, true);
4172 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4173 return;
4174
4175 // Check if the compare with the case values is distinct from the default
4176 // compare result.
4177 for (auto ValuePair : Values) {
4178 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4179 ValuePair.second, CmpOp1, true);
4180 if (!CaseConst || CaseConst == DefaultConst)
4181 return;
4182 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4183 "Expect true or false as compare result.");
4184 }
4185
4186 // Check if the branch instruction dominates the phi node. It's a simple
4187 // dominance check, but sufficient for our needs.
4188 // Although this check is invariant in the calling loops, it's better to do it
4189 // at this late stage. Practically we do it at most once for a switch.
4190 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4191 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4192 BasicBlock *Pred = *PI;
4193 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4194 return;
4195 }
4196
4197 if (DefaultConst == FalseConst) {
4198 // The compare yields the same result. We can replace it.
4199 CmpInst->replaceAllUsesWith(RangeCmp);
4200 ++NumTableCmpReuses;
4201 } else {
4202 // The compare yields the same result, just inverted. We can replace it.
4203 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4204 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4205 RangeCheckBranch);
4206 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4207 ++NumTableCmpReuses;
4208 }
4209}
4210
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004211/// If the switch is only used to initialize one or more phi nodes in a common
4212/// successor block with different constant values, replace the switch with
4213/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004214static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4215 const DataLayout &DL,
4216 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004217 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004218
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004219 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004220 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004221 return false;
4222
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004223 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4224 // split off a dense part and build a lookup table for that.
4225
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004226 // FIXME: This creates arrays of GEPs to constant strings, which means each
4227 // GEP needs a runtime relocation in PIC code. We should just build one big
4228 // string and lookup indices into that.
4229
Hans Wennborg4744ac12014-01-15 05:00:27 +00004230 // Ignore switches with less than three cases. Lookup tables will not make them
4231 // faster, so we don't analyze them.
4232 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004233 return false;
4234
4235 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004236 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004237 assert(SI->case_begin() != SI->case_end());
4238 SwitchInst::CaseIt CI = SI->case_begin();
4239 ConstantInt *MinCaseVal = CI.getCaseValue();
4240 ConstantInt *MaxCaseVal = CI.getCaseValue();
4241
Craig Topperf40110f2014-04-25 05:29:35 +00004242 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004243 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004244 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4245 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4246 SmallDenseMap<PHINode*, Type*> ResultTypes;
4247 SmallVector<PHINode*, 4> PHIs;
4248
4249 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4250 ConstantInt *CaseVal = CI.getCaseValue();
4251 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4252 MinCaseVal = CaseVal;
4253 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4254 MaxCaseVal = CaseVal;
4255
4256 // Resulting value at phi nodes for this case value.
4257 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4258 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004259 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004260 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004261 return false;
4262
4263 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004264 for (const auto &I : Results) {
4265 PHINode *PHI = I.first;
4266 Constant *Value = I.second;
4267 if (!ResultLists.count(PHI))
4268 PHIs.push_back(PHI);
4269 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004270 }
4271 }
4272
Hans Wennborgac114a32014-01-12 00:44:41 +00004273 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004274 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004275 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4276 }
4277
4278 uint64_t NumResults = ResultLists[PHIs[0]].size();
4279 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4280 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4281 bool TableHasHoles = (NumResults < TableSize);
4282
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004283 // If the table has holes, we need a constant result for the default case
4284 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004285 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004286 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004287 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004288
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004289 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4290 if (NeedMask) {
4291 // As an extra penalty for the validity test we require more cases.
4292 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4293 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004294 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004295 return false;
4296 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004297
Hans Wennborga6a11a92014-11-18 02:37:11 +00004298 for (const auto &I : DefaultResultsList) {
4299 PHINode *PHI = I.first;
4300 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004301 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004302 }
4303
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004304 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004305 return false;
4306
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004307 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004308 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004309 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4310 "switch.lookup",
4311 CommonDest->getParent(),
4312 CommonDest);
4313
Michael Gottesmanc024f322013-10-20 07:04:37 +00004314 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004315 Builder.SetInsertPoint(SI);
4316 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4317 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004318
4319 // Compute the maximum table size representable by the integer type we are
4320 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004321 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004322 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004323 assert(MaxTableSize >= TableSize &&
4324 "It is impossible for a switch to have more entries than the max "
4325 "representable value of its input integer type's size.");
4326
Hans Wennborgb64cb272015-01-26 19:52:34 +00004327 // If the default destination is unreachable, or if the lookup table covers
4328 // all values of the conditional variable, branch directly to the lookup table
4329 // BB. Otherwise, check that the condition is within the case range.
4330 const bool DefaultIsReachable =
4331 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4332 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004333 BranchInst *RangeCheckBranch = nullptr;
4334
Hans Wennborgb64cb272015-01-26 19:52:34 +00004335 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004336 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004337 // Note: We call removeProdecessor later since we need to be able to get the
4338 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004339 } else {
4340 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004341 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004342 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004343 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004344
4345 // Populate the BB that does the lookups.
4346 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004347
4348 if (NeedMask) {
4349 // Before doing the lookup we do the hole check.
4350 // The LookupBB is therefore re-purposed to do the hole check
4351 // and we create a new LookupBB.
4352 BasicBlock *MaskBB = LookupBB;
4353 MaskBB->setName("switch.hole_check");
4354 LookupBB = BasicBlock::Create(Mod.getContext(),
4355 "switch.lookup",
4356 CommonDest->getParent(),
4357 CommonDest);
4358
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004359 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4360 // unnecessary illegal types.
4361 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4362 APInt MaskInt(TableSizePowOf2, 0);
4363 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004364 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004365 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4366 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4367 uint64_t Idx = (ResultList[I].first->getValue() -
4368 MinCaseVal->getValue()).getLimitedValue();
4369 MaskInt |= One << Idx;
4370 }
4371 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4372
4373 // Get the TableIndex'th bit of the bitmask.
4374 // If this bit is 0 (meaning hole) jump to the default destination,
4375 // else continue with table lookup.
4376 IntegerType *MapTy = TableMask->getType();
4377 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4378 "switch.maskindex");
4379 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4380 "switch.shifted");
4381 Value *LoBit = Builder.CreateTrunc(Shifted,
4382 Type::getInt1Ty(Mod.getContext()),
4383 "switch.lobit");
4384 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4385
4386 Builder.SetInsertPoint(LookupBB);
4387 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4388 }
4389
Hans Wennborg86ac6302015-04-24 20:57:56 +00004390 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4391 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4392 // do not delete PHINodes here.
4393 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4394 /*DontDeleteUselessPHIs=*/true);
4395 }
4396
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004397 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004398 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4399 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004400 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004401
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004402 // If using a bitmask, use any value to fill the lookup table holes.
4403 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004404 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004405
Manman Ren4d189fb2014-07-24 21:13:20 +00004406 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004407
Hans Wennborgf744fa92012-09-19 14:24:21 +00004408 // If the result is used to return immediately from the function, we want to
4409 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004410 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4411 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004412 Builder.CreateRet(Result);
4413 ReturnedEarly = true;
4414 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004415 }
4416
Erik Eckstein0d86c762014-11-27 15:13:14 +00004417 // Do a small peephole optimization: re-use the switch table compare if
4418 // possible.
4419 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4420 BasicBlock *PhiBlock = PHI->getParent();
4421 // Search for compare instructions which use the phi.
4422 for (auto *User : PHI->users()) {
4423 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4424 }
4425 }
4426
Hans Wennborgf744fa92012-09-19 14:24:21 +00004427 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004428 }
4429
4430 if (!ReturnedEarly)
4431 Builder.CreateBr(CommonDest);
4432
4433 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004434 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004435 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004436
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004437 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004438 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004439 Succ->removePredecessor(SI->getParent());
4440 }
4441 SI->eraseFromParent();
4442
4443 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004444 if (NeedMask)
4445 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004446 return true;
4447}
4448
Devang Patela7ec47d2011-05-18 20:35:38 +00004449bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004450 BasicBlock *BB = SI->getParent();
4451
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004452 if (isValueEqualityComparison(SI)) {
4453 // If we only have one predecessor, and if it is a branch on this value,
4454 // see if that predecessor totally determines the outcome of this switch.
4455 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4456 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004457 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004458
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004459 Value *Cond = SI->getCondition();
4460 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4461 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004462 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004463
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004464 // If the block only contains the switch, see if we can fold the block
4465 // away into any preds.
4466 BasicBlock::iterator BBI = BB->begin();
4467 // Ignore dbg intrinsics.
4468 while (isa<DbgInfoIntrinsic>(BBI))
4469 ++BBI;
4470 if (SI == &*BBI)
4471 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004472 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004473 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004474
4475 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004476 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004477 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004478
4479 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004480 if (EliminateDeadSwitchCases(SI, AC, DL))
4481 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004482
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004483 if (SwitchToSelect(SI, Builder, AC, DL))
4484 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004485
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004486 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004487 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004488
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004489 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4490 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004491
Chris Lattner25c3af32010-12-13 06:25:44 +00004492 return false;
4493}
4494
4495bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4496 BasicBlock *BB = IBI->getParent();
4497 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004498
Chris Lattner25c3af32010-12-13 06:25:44 +00004499 // Eliminate redundant destinations.
4500 SmallPtrSet<Value *, 8> Succs;
4501 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4502 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004503 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004504 Dest->removePredecessor(BB);
4505 IBI->removeDestination(i);
4506 --i; --e;
4507 Changed = true;
4508 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004509 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004510
4511 if (IBI->getNumDestinations() == 0) {
4512 // If the indirectbr has no successors, change it to unreachable.
4513 new UnreachableInst(IBI->getContext(), IBI);
4514 EraseTerminatorInstAndDCECond(IBI);
4515 return true;
4516 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004517
Chris Lattner25c3af32010-12-13 06:25:44 +00004518 if (IBI->getNumDestinations() == 1) {
4519 // If the indirectbr has one successor, change it to a direct branch.
4520 BranchInst::Create(IBI->getDestination(0), IBI);
4521 EraseTerminatorInstAndDCECond(IBI);
4522 return true;
4523 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004524
Chris Lattner25c3af32010-12-13 06:25:44 +00004525 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4526 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004527 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004528 }
4529 return Changed;
4530}
4531
Philip Reames2b969d72015-03-24 22:28:45 +00004532/// Given an block with only a single landing pad and a unconditional branch
4533/// try to find another basic block which this one can be merged with. This
4534/// handles cases where we have multiple invokes with unique landing pads, but
4535/// a shared handler.
4536///
4537/// We specifically choose to not worry about merging non-empty blocks
4538/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4539/// practice, the optimizer produces empty landing pad blocks quite frequently
4540/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4541/// sinking in this file)
4542///
4543/// This is primarily a code size optimization. We need to avoid performing
4544/// any transform which might inhibit optimization (such as our ability to
4545/// specialize a particular handler via tail commoning). We do this by not
4546/// merging any blocks which require us to introduce a phi. Since the same
4547/// values are flowing through both blocks, we don't loose any ability to
4548/// specialize. If anything, we make such specialization more likely.
4549///
4550/// TODO - This transformation could remove entries from a phi in the target
4551/// block when the inputs in the phi are the same for the two blocks being
4552/// merged. In some cases, this could result in removal of the PHI entirely.
4553static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4554 BasicBlock *BB) {
4555 auto Succ = BB->getUniqueSuccessor();
4556 assert(Succ);
4557 // If there's a phi in the successor block, we'd likely have to introduce
4558 // a phi into the merged landing pad block.
4559 if (isa<PHINode>(*Succ->begin()))
4560 return false;
4561
4562 for (BasicBlock *OtherPred : predecessors(Succ)) {
4563 if (BB == OtherPred)
4564 continue;
4565 BasicBlock::iterator I = OtherPred->begin();
4566 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4567 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4568 continue;
4569 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4570 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4571 if (!BI2 || !BI2->isIdenticalTo(BI))
4572 continue;
4573
4574 // We've found an identical block. Update our predeccessors to take that
4575 // path instead and make ourselves dead.
4576 SmallSet<BasicBlock *, 16> Preds;
4577 Preds.insert(pred_begin(BB), pred_end(BB));
4578 for (BasicBlock *Pred : Preds) {
4579 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4580 assert(II->getNormalDest() != BB &&
4581 II->getUnwindDest() == BB && "unexpected successor");
4582 II->setUnwindDest(OtherPred);
4583 }
4584
4585 // The debug info in OtherPred doesn't cover the merged control flow that
4586 // used to go through BB. We need to delete it or update it.
4587 for (auto I = OtherPred->begin(), E = OtherPred->end();
4588 I != E;) {
4589 Instruction &Inst = *I; I++;
4590 if (isa<DbgInfoIntrinsic>(Inst))
4591 Inst.eraseFromParent();
4592 }
4593
4594 SmallSet<BasicBlock *, 16> Succs;
4595 Succs.insert(succ_begin(BB), succ_end(BB));
4596 for (BasicBlock *Succ : Succs) {
4597 Succ->removePredecessor(BB);
4598 }
4599
4600 IRBuilder<> Builder(BI);
4601 Builder.CreateUnreachable();
4602 BI->eraseFromParent();
4603 return true;
4604 }
4605 return false;
4606}
4607
Devang Patel767f6932011-05-18 18:28:48 +00004608bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004609 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004610
Manman Ren93ab6492012-09-20 22:37:36 +00004611 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4612 return true;
4613
Chris Lattner25c3af32010-12-13 06:25:44 +00004614 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004615 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004616 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4617 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4618 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004619
Chris Lattner25c3af32010-12-13 06:25:44 +00004620 // If the only instruction in the block is a seteq/setne comparison
4621 // against a constant, try to simplify the block.
4622 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4623 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4624 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4625 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004626 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004627 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4628 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004629 return true;
4630 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004631
Philip Reames2b969d72015-03-24 22:28:45 +00004632 // See if we can merge an empty landing pad block with another which is
4633 // equivalent.
4634 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4635 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4636 if (I->isTerminator() &&
4637 TryToMergeLandingPad(LPad, BI, BB))
4638 return true;
4639 }
4640
Manman Rend33f4ef2012-06-13 05:43:29 +00004641 // If this basic block is ONLY a compare and a branch, and if a predecessor
4642 // branches to us and our successor, fold the comparison into the
4643 // predecessor and use logical operations to update the incoming value
4644 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004645 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4646 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004647 return false;
4648}
4649
4650
Devang Patela7ec47d2011-05-18 20:35:38 +00004651bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004652 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004653
Chris Lattner25c3af32010-12-13 06:25:44 +00004654 // Conditional branch
4655 if (isValueEqualityComparison(BI)) {
4656 // If we only have one predecessor, and if it is a branch on this value,
4657 // see if that predecessor totally determines the outcome of this
4658 // switch.
4659 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004660 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004661 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004662
Chris Lattner25c3af32010-12-13 06:25:44 +00004663 // This block must be empty, except for the setcond inst, if it exists.
4664 // Ignore dbg intrinsics.
4665 BasicBlock::iterator I = BB->begin();
4666 // Ignore dbg intrinsics.
4667 while (isa<DbgInfoIntrinsic>(I))
4668 ++I;
4669 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004670 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004671 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004672 } else if (&*I == cast<Instruction>(BI->getCondition())){
4673 ++I;
4674 // Ignore dbg intrinsics.
4675 while (isa<DbgInfoIntrinsic>(I))
4676 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004677 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004678 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004679 }
4680 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004681
Chris Lattner25c3af32010-12-13 06:25:44 +00004682 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004683 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004684 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004685
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004686 // If this basic block is ONLY a compare and a branch, and if a predecessor
4687 // branches to us and one of our successors, fold the comparison into the
4688 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004689 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4690 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004691
Chris Lattner25c3af32010-12-13 06:25:44 +00004692 // We have a conditional branch to two blocks that are only reachable
4693 // from BI. We know that the condbr dominates the two blocks, so see if
4694 // there is any identical code in the "then" and "else" blocks. If so, we
4695 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004696 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4697 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004698 if (HoistThenElseCodeToIf(BI, TTI))
4699 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004700 } else {
4701 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004702 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004703 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4704 if (Succ0TI->getNumSuccessors() == 1 &&
4705 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004706 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
4707 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004708 }
Craig Topperf40110f2014-04-25 05:29:35 +00004709 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004710 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004711 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004712 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4713 if (Succ1TI->getNumSuccessors() == 1 &&
4714 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004715 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
4716 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004717 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004718
Chris Lattner25c3af32010-12-13 06:25:44 +00004719 // If this is a branch on a phi node in the current block, thread control
4720 // through this block if any PHI node entries are constants.
4721 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4722 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004723 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004724 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004725
Chris Lattner25c3af32010-12-13 06:25:44 +00004726 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004727 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4728 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004729 if (PBI != BI && PBI->isConditional())
4730 if (SimplifyCondBranchToCondBranch(PBI, BI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004731 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004732
4733 return false;
4734}
4735
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004736/// Check if passing a value to an instruction will cause undefined behavior.
4737static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4738 Constant *C = dyn_cast<Constant>(V);
4739 if (!C)
4740 return false;
4741
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004742 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004743 return false;
4744
4745 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004746 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004747 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004748
4749 // Now make sure that there are no instructions in between that can alter
4750 // control flow (eg. calls)
4751 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004752 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004753 return false;
4754
4755 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4756 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4757 if (GEP->getPointerOperand() == I)
4758 return passingValueIsAlwaysUndefined(V, GEP);
4759
4760 // Look through bitcasts.
4761 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4762 return passingValueIsAlwaysUndefined(V, BC);
4763
Benjamin Kramer0655b782011-08-26 02:25:55 +00004764 // Load from null is undefined.
4765 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004766 if (!LI->isVolatile())
4767 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004768
Benjamin Kramer0655b782011-08-26 02:25:55 +00004769 // Store to null is undefined.
4770 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004771 if (!SI->isVolatile())
4772 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004773 }
4774 return false;
4775}
4776
4777/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004778/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004779static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4780 for (BasicBlock::iterator i = BB->begin();
4781 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4782 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4783 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4784 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4785 IRBuilder<> Builder(T);
4786 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4787 BB->removePredecessor(PHI->getIncomingBlock(i));
4788 // Turn uncoditional branches into unreachables and remove the dead
4789 // destination from conditional branches.
4790 if (BI->isUnconditional())
4791 Builder.CreateUnreachable();
4792 else
4793 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4794 BI->getSuccessor(0));
4795 BI->eraseFromParent();
4796 return true;
4797 }
4798 // TODO: SwitchInst.
4799 }
4800
4801 return false;
4802}
4803
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004804bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004805 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004806
Chris Lattnerd7beca32010-12-14 06:17:25 +00004807 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004808 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004809
Dan Gohman4a63fad2010-08-14 00:29:42 +00004810 // Remove basic blocks that have no predecessors (except the entry block)...
4811 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00004812 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00004813 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004814 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004815 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004816 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004817 return true;
4818 }
4819
Chris Lattner031340a2003-08-17 19:41:53 +00004820 // Check to see if we can constant propagate this terminator instruction
4821 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004822 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004823
Dan Gohman1a951062009-10-30 22:39:04 +00004824 // Check for and eliminate duplicate PHI nodes in this block.
4825 Changed |= EliminateDuplicatePHINodes(BB);
4826
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004827 // Check for and remove branches that will always cause undefined behavior.
4828 Changed |= removeUndefIntroducingPredecessor(BB);
4829
Chris Lattner2e3832d2010-12-13 05:10:48 +00004830 // Merge basic blocks into their predecessor if there is only one distinct
4831 // pred, and if there is only one distinct successor of the predecessor, and
4832 // if there are no PHI nodes.
4833 //
4834 if (MergeBlockIntoPredecessor(BB))
4835 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004836
Devang Patel15ad6762011-05-18 18:01:27 +00004837 IRBuilder<> Builder(BB);
4838
Dan Gohman20af5a02008-03-11 21:53:06 +00004839 // If there is a trivial two-entry PHI node in this basic block, and we can
4840 // eliminate it, do so now.
4841 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4842 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004843 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004844
Devang Patela7ec47d2011-05-18 20:35:38 +00004845 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004846 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004847 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004848 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004849 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004850 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004851 }
4852 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004853 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004854 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4855 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00004856 } else if (CleanupReturnInst *RI =
4857 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
4858 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004859 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004860 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004861 } else if (UnreachableInst *UI =
4862 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4863 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004864 } else if (IndirectBrInst *IBI =
4865 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4866 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004867 }
4868
Chris Lattner031340a2003-08-17 19:41:53 +00004869 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004870}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004871
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004872/// This function is used to do simplification of a CFG.
4873/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004874/// eliminates unreachable basic blocks, and does other "peephole" optimization
4875/// of the CFG. It returns true if a modification was made.
4876///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004877bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004878 unsigned BonusInstThreshold, AssumptionCache *AC) {
4879 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
4880 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004881}