blob: 1c27bc67cfbfc14c9fae1aafa89c92c448d2a4c1 [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
James Molloy4de84dd2015-11-04 15:28:04 +000017#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000022#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000028#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000040#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000042#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000044#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Jingyue Wufc029672014-09-30 22:23:38 +000048#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000049#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000050#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000052using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000053using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "simplifycfg"
56
James Molloy1b6207e2015-02-13 10:48:30 +000057// Chosen as 2 so as to be cheap, but still to have enough power to fold
58// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59// To catch this, we need to fold a compare and a select, hence '2' being the
60// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000061static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000062PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000064
Evan Chengd983eba2011-01-29 04:46:23 +000065static cl::opt<bool>
66DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
68
Manman Ren93ab6492012-09-20 22:37:36 +000069static cl::opt<bool>
70SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
72
Alp Tokercb402912014-01-24 17:20:08 +000073static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000076
James Molloy4de84dd2015-11-04 15:28:04 +000077static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
81 "predicated store"));
82
83static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
87
David Majnemerfccf5c62016-01-27 02:59:41 +000088static cl::opt<bool> SpeculateOneExpensiveInst(
89 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
90 cl::desc("Allow exactly one expensive instruction to be speculatively "
91 "executed"));
92
Sanjay Patel5264cc72016-01-27 19:22:45 +000093static cl::opt<unsigned> MaxSpeculationDepth(
94 "max-speculation-depth", cl::Hidden, cl::init(10),
95 cl::desc("Limit maximum recursion depth when calculating costs of "
96 "speculatively executed instructions"));
97
Hans Wennborg39583b82012-09-26 09:44:49 +000098STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000099STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000100STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +0000101STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000102STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +0000103STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000104STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000105
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000106namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000107 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +0000108 // case group is selected, and the second field is a vector containing the
109 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000110 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
111 SwitchCaseResultVectorTy;
112 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000113 // and the second field contains the value generated for a certain case in the
114 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000115 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
116
Eric Christopherb65acc62012-07-02 23:22:21 +0000117 /// ValueEqualityComparisonCase - Represents a case of a switch.
118 struct ValueEqualityComparisonCase {
119 ConstantInt *Value;
120 BasicBlock *Dest;
121
122 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
123 : Value(Value), Dest(Dest) {}
124
125 bool operator<(ValueEqualityComparisonCase RHS) const {
126 // Comparing pointers is ok as we only rely on the order for uniquing.
127 return Value < RHS.Value;
128 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000129
130 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000131 };
132
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000134 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000136 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000137 AssumptionCache *AC;
Hyojin Sung4673f102016-03-29 04:08:57 +0000138 SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000139 Value *isValueEqualityComparison(TerminatorInst *TI);
140 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000141 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000142 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000143 BasicBlock *Pred,
144 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000145 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
146 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000147
Devang Pateldd14e0f2011-05-18 21:33:11 +0000148 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000149 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000150 bool SimplifySingleResume(ResumeInst *RI);
151 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000152 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000153 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000154 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000155 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000156 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000157 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000158
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000159public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000160 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
Hyojin Sung4673f102016-03-29 04:08:57 +0000161 unsigned BonusInstThreshold, AssumptionCache *AC,
162 SmallPtrSetImpl<BasicBlock *> *LoopHeaders)
163 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC),
164 LoopHeaders(LoopHeaders) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000165 bool run(BasicBlock *BB);
166};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000167}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000168
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000169/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000170/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000171static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
172 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000173
Chris Lattner76dc2042005-08-03 00:19:45 +0000174 // It is not safe to merge these two switch instructions if they have a common
175 // successor, and if that successor has a PHI node, and if *that* PHI node has
176 // conflicting incoming values from the two switch blocks.
177 BasicBlock *SI1BB = SI1->getParent();
178 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000179 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000180
Sanjay Patel5781d842016-03-12 16:52:17 +0000181 for (BasicBlock *Succ : successors(SI2BB))
182 if (SI1Succs.count(Succ))
183 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000184 PHINode *PN = cast<PHINode>(BBI);
185 if (PN->getIncomingValueForBlock(SI1BB) !=
186 PN->getIncomingValueForBlock(SI2BB))
187 return false;
188 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000189
Chris Lattner76dc2042005-08-03 00:19:45 +0000190 return true;
191}
192
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000193/// Return true if it is safe and profitable to merge these two terminator
194/// instructions together, where SI1 is an unconditional branch. PhiNodes will
195/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000196static bool isProfitableToFoldUnconditional(BranchInst *SI1,
197 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000198 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000199 SmallVectorImpl<PHINode*> &PhiNodes) {
200 if (SI1 == SI2) return false; // Can't merge with self!
201 assert(SI1->isUnconditional() && SI2->isConditional());
202
203 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000204 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000205 // 1> We have a constant incoming value for the conditional branch;
206 // 2> We have "Cond" as the incoming value for the unconditional branch;
207 // 3> SI2->getCondition() and Cond have same operands.
208 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
209 if (!Ci2) return false;
210 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
211 Cond->getOperand(1) == Ci2->getOperand(1)) &&
212 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
213 Cond->getOperand(1) == Ci2->getOperand(0)))
214 return false;
215
216 BasicBlock *SI1BB = SI1->getParent();
217 BasicBlock *SI2BB = SI2->getParent();
218 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Sanjay Patel5781d842016-03-12 16:52:17 +0000219 for (BasicBlock *Succ : successors(SI2BB))
220 if (SI1Succs.count(Succ))
221 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Manman Rend33f4ef2012-06-13 05:43:29 +0000222 PHINode *PN = cast<PHINode>(BBI);
223 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000224 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000225 return false;
226 PhiNodes.push_back(PN);
227 }
228 return true;
229}
230
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000231/// Update PHI nodes in Succ to indicate that there will now be entries in it
232/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
233/// will be the same as those coming in from ExistPred, an existing predecessor
234/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000235static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
236 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000237 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000238
Chris Lattner80b03a12008-07-13 22:23:11 +0000239 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +0000240 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
Chris Lattner80b03a12008-07-13 22:23:11 +0000241 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000242}
243
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000244/// Compute an abstract "cost" of speculating the given instruction,
245/// which is assumed to be safe to speculate. TCC_Free means cheap,
246/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000247/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000249 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000251 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000252 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000253}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000254
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000255/// If we have a merge point of an "if condition" as accepted above,
256/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000257/// don't handle the true generality of domination here, just a special case
258/// which works well enough for us.
259///
260/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000261/// see if V (which must be an instruction) and its recursive operands
262/// that do not dominate BB have a combined cost lower than CostRemaining and
263/// are non-trapping. If both are true, the instruction is inserted into the
264/// set and true is returned.
265///
266/// The cost for most non-trapping instructions is defined as 1 except for
267/// Select whose cost is 2.
268///
269/// After this function returns, CostRemaining is decreased by the cost of
270/// V plus its non-dominating operands. If that cost is greater than
271/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000272static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000273 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000274 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000275 const TargetTransformInfo &TTI,
276 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000277 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
278 // so limit the recursion depth.
279 // TODO: While this recursion limit does prevent pathological behavior, it
280 // would be better to track visited instructions to avoid cycles.
281 if (Depth == MaxSpeculationDepth)
282 return false;
283
Chris Lattner0aa56562004-04-09 22:50:22 +0000284 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000285 if (!I) {
286 // Non-instructions all dominate instructions, but not all constantexprs
287 // can be executed unconditionally.
288 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
289 if (C->canTrap())
290 return false;
291 return true;
292 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000293 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000294
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000295 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000296 // the bottom of this block.
297 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000298
Chris Lattner0aa56562004-04-09 22:50:22 +0000299 // If this instruction is defined in a block that contains an unconditional
300 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000301 // statement". If not, it definitely dominates the region.
302 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000303 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000304 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000305
Chris Lattner9ac168d2010-12-14 07:41:39 +0000306 // If we aren't allowing aggressive promotion anymore, then don't consider
307 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000308 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000309
Peter Collingbournee3511e12011-04-29 18:47:31 +0000310 // If we have seen this instruction before, don't count it again.
311 if (AggressiveInsts->count(I)) return true;
312
Chris Lattner9ac168d2010-12-14 07:41:39 +0000313 // Okay, it looks like the instruction IS in the "condition". Check to
314 // see if it's a cheap instruction to unconditionally compute, and if it
315 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000317 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000320
David Majnemerfccf5c62016-01-27 02:59:41 +0000321 // Allow exactly one instruction to be speculated regardless of its cost
322 // (as long as it is safe to do so).
323 // This is intended to flatten the CFG even if the instruction is a division
324 // or other expensive operation. The speculation of an expensive instruction
325 // is expected to be undone in CodeGenPrepare if the speculation has not
326 // enabled further IR optimizations.
327 if (Cost > CostRemaining &&
328 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000329 return false;
330
David Majnemerfccf5c62016-01-27 02:59:41 +0000331 // Avoid unsigned wrap.
332 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000333
334 // Okay, we can only really hoist these out if their operands do
335 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000336 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000337 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
338 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000339 return false;
340 // Okay, it's safe to do this! Remember this instruction.
341 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000342 return true;
343}
Chris Lattner466a0492002-05-21 20:50:24 +0000344
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000345/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000346/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000348 // Normal constant int.
349 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000350 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000351 return CI;
352
353 // This is some kind of pointer constant. Turn it into a pointer-sized
354 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000355 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000356
357 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
358 if (isa<ConstantPointerNull>(V))
359 return ConstantInt::get(PtrTy, 0);
360
361 // IntToPtr const int.
362 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
363 if (CE->getOpcode() == Instruction::IntToPtr)
364 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
365 // The constant is very likely to have the right type already.
366 if (CI->getType() == PtrTy)
367 return CI;
368 else
369 return cast<ConstantInt>
370 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
371 }
Craig Topperf40110f2014-04-25 05:29:35 +0000372 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000373}
374
Mehdi Aminiffd01002014-11-20 22:40:25 +0000375namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000376
Mehdi Aminiffd01002014-11-20 22:40:25 +0000377/// Given a chain of or (||) or and (&&) comparison of a value against a
378/// constant, this will try to recover the information required for a switch
379/// structure.
380/// It will depth-first traverse the chain of comparison, seeking for patterns
381/// like %a == 12 or %a < 4 and combine them to produce a set of integer
382/// representing the different cases for the switch.
383/// Note that if the chain is composed of '||' it will build the set of elements
384/// that matches the comparisons (i.e. any of this value validate the chain)
385/// while for a chain of '&&' it will build the set elements that make the test
386/// fail.
387struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000388 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000389 Value *CompValue; /// Value found for the switch comparison
390 Value *Extra; /// Extra clause to be checked before the switch
391 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
392 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000393
Mehdi Aminiffd01002014-11-20 22:40:25 +0000394 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
396 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
397 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000398 }
399
Mehdi Aminiffd01002014-11-20 22:40:25 +0000400 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000401 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000402 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000403 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000404
Mehdi Aminiffd01002014-11-20 22:40:25 +0000405private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000406
Mehdi Aminiffd01002014-11-20 22:40:25 +0000407 /// Try to set the current value used for the comparison, it succeeds only if
408 /// it wasn't set before or if the new value is the same as the old one
409 bool setValueOnce(Value *NewVal) {
Sanjay Patel2e002772016-03-12 18:05:53 +0000410 if (CompValue && CompValue != NewVal) return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000411 CompValue = NewVal;
412 return (CompValue != nullptr);
413 }
414
415 /// Try to match Instruction "I" as a comparison against a constant and
416 /// populates the array Vals with the set of values that match (or do not
417 /// match depending on isEQ).
418 /// Return false on failure. On success, the Value the comparison matched
419 /// against is placed in CompValue.
420 /// If CompValue is already set, the function is expected to fail if a match
421 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000423 // If this is an icmp against a constant, handle this as one of the cases.
424 ICmpInst *ICI;
425 ConstantInt *C;
426 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
427 (C = GetConstantInt(I->getOperand(1), DL)))) {
428 return false;
429 }
430
431 Value *RHSVal;
432 ConstantInt *RHSC;
433
434 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000435 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000436 // This undoes a transformation done by instcombine to fuse 2 compares.
437 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
438 if (match(ICI->getOperand(0),
439 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
440 APInt Not = ~RHSC->getValue();
David Majnemerc761afd2016-01-27 02:43:28 +0000441 if (Not.isPowerOf2() && C->getValue().isPowerOf2() &&
442 Not != C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000443 // If we already have a value for the switch, it has to match!
444 if(!setValueOnce(RHSVal))
445 return false;
446
447 Vals.push_back(C);
448 Vals.push_back(ConstantInt::get(C->getContext(),
449 C->getValue() | Not));
450 UsedICmps++;
451 return true;
452 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000453 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000454
455 // If we already have a value for the switch, it has to match!
456 if(!setValueOnce(ICI->getOperand(0)))
457 return false;
458
459 UsedICmps++;
460 Vals.push_back(C);
461 return ICI->getOperand(0);
462 }
463
464 // 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 +0000465 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
466 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000467
468 // Shift the range if the compare is fed by an add. This is the range
469 // compare idiom as emitted by instcombine.
470 Value *CandidateVal = I->getOperand(0);
471 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
472 Span = Span.subtract(RHSC->getValue());
473 CandidateVal = RHSVal;
474 }
475
476 // If this is an and/!= check, then we are looking to build the set of
477 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
478 // x != 0 && x != 1.
479 if (!isEQ)
480 Span = Span.inverse();
481
482 // If there are a ton of values, we don't want to make a ginormous switch.
483 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
484 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000485 }
486
487 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000488 if(!setValueOnce(CandidateVal))
489 return false;
490
491 // Add all values from the range to the set
492 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
493 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000494
495 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000496 return true;
497
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000498 }
499
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000500 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000501 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
502 /// the value being compared, and stick the list constants into the Vals
503 /// vector.
504 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000505 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000506 Instruction *I = dyn_cast<Instruction>(V);
507 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000508
Mehdi Aminiffd01002014-11-20 22:40:25 +0000509 // Keep a stack (SmallVector for efficiency) for depth-first traversal
510 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000511 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000512
Mehdi Aminiffd01002014-11-20 22:40:25 +0000513 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000514 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000515 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000516
Mehdi Aminiffd01002014-11-20 22:40:25 +0000517 while(!DFT.empty()) {
518 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000519
Mehdi Aminiffd01002014-11-20 22:40:25 +0000520 if (Instruction *I = dyn_cast<Instruction>(V)) {
521 // If it is a || (or && depending on isEQ), process the operands.
522 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000523 if (Visited.insert(I->getOperand(1)).second)
524 DFT.push_back(I->getOperand(1));
525 if (Visited.insert(I->getOperand(0)).second)
526 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000527 continue;
528 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000529
Mehdi Aminiffd01002014-11-20 22:40:25 +0000530 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000531 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000532 // Match succeed, continue the loop
533 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000534 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000535
Mehdi Aminiffd01002014-11-20 22:40:25 +0000536 // One element of the sequence of || (or &&) could not be match as a
537 // comparison against the same value as the others.
538 // We allow only one "Extra" case to be checked before the switch
539 if (!Extra) {
540 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000541 continue;
542 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000543 // Failed to parse a proper sequence, abort now
544 CompValue = nullptr;
545 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000546 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000547 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000548};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000549
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000550}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000551
Eli Friedmancb61afb2008-12-16 20:54:32 +0000552static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000553 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
555 Cond = dyn_cast<Instruction>(SI->getCondition());
556 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
557 if (BI->isConditional())
558 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000559 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
560 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000561 }
562
563 TI->eraseFromParent();
564 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
565}
566
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000567/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000568/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000569Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000570 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000571 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
572 // Do not permit merging of large switch instructions into their
573 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000574 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
575 pred_end(SI->getParent())) <= 128)
576 CV = SI->getCondition();
577 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000578 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000579 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000580 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000581 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000582 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000583
584 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000586 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
587 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000589 CV = Ptr;
590 }
591 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000592 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000593}
594
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000595/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000596/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000597BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000598GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000599 std::vector<ValueEqualityComparisonCase>
600 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000601 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000602 Cases.reserve(SI->getNumCases());
603 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
604 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
605 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000606 return SI->getDefaultDest();
607 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000608
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000609 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000610 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000611 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
612 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000613 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000614 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000615 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000616}
617
Eric Christopherb65acc62012-07-02 23:22:21 +0000618
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000619/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000620/// in the list that match the specified block.
621static void EliminateBlockCases(BasicBlock *BB,
622 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000623 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000624}
625
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000626/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000627static bool
628ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
629 std::vector<ValueEqualityComparisonCase > &C2) {
630 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
631
632 // Make V1 be smaller than V2.
633 if (V1->size() > V2->size())
634 std::swap(V1, V2);
635
636 if (V1->size() == 0) return false;
637 if (V1->size() == 1) {
638 // Just scan V2.
639 ConstantInt *TheVal = (*V1)[0].Value;
640 for (unsigned i = 0, e = V2->size(); i != e; ++i)
641 if (TheVal == (*V2)[i].Value)
642 return true;
643 }
644
645 // Otherwise, just sort both lists and compare element by element.
646 array_pod_sort(V1->begin(), V1->end());
647 array_pod_sort(V2->begin(), V2->end());
648 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
649 while (i1 != e1 && i2 != e2) {
650 if ((*V1)[i1].Value == (*V2)[i2].Value)
651 return true;
652 if ((*V1)[i1].Value < (*V2)[i2].Value)
653 ++i1;
654 else
655 ++i2;
656 }
657 return false;
658}
659
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000660/// If TI is known to be a terminator instruction and its block is known to
661/// only have a single predecessor block, check to see if that predecessor is
662/// also a value comparison with the same value, and if that comparison
663/// determines the outcome of this comparison. If so, simplify TI. This does a
664/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000665bool SimplifyCFGOpt::
666SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000667 BasicBlock *Pred,
668 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000669 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
670 if (!PredVal) return false; // Not a value comparison in predecessor.
671
672 Value *ThisVal = isValueEqualityComparison(TI);
673 assert(ThisVal && "This isn't a value comparison!!");
674 if (ThisVal != PredVal) return false; // Different predicates.
675
Andrew Trick3051aa12012-08-29 21:46:38 +0000676 // TODO: Preserve branch weight metadata, similarly to how
677 // FoldValueComparisonIntoPredecessors preserves it.
678
Chris Lattner1cca9592005-02-24 06:17:52 +0000679 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000680 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000681 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
682 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000683 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000684
Chris Lattner1cca9592005-02-24 06:17:52 +0000685 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000686 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000687 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000688 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000689
690 // If TI's block is the default block from Pred's comparison, potentially
691 // simplify TI based on this knowledge.
692 if (PredDef == TI->getParent()) {
693 // If we are here, we know that the value is none of those cases listed in
694 // PredCases. If there are any cases in ThisCases that are in PredCases, we
695 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000696 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000697 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000698
Chris Lattner4088e2b2010-12-13 01:47:07 +0000699 if (isa<BranchInst>(TI)) {
700 // Okay, one of the successors of this condbr is dead. Convert it to a
701 // uncond br.
702 assert(ThisCases.size() == 1 && "Branch can only have one case!");
703 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000704 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000705 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000706
Chris Lattner4088e2b2010-12-13 01:47:07 +0000707 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000708 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000709
Chris Lattner4088e2b2010-12-13 01:47:07 +0000710 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
711 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000712
Chris Lattner4088e2b2010-12-13 01:47:07 +0000713 EraseTerminatorInstAndDCECond(TI);
714 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000715 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000716
Chris Lattner4088e2b2010-12-13 01:47:07 +0000717 SwitchInst *SI = cast<SwitchInst>(TI);
718 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000719 SmallPtrSet<Constant*, 16> DeadCases;
720 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
721 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000722
David Greene725c7c32010-01-05 01:26:52 +0000723 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000724 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000725
Manman Ren8691e522012-09-14 21:53:06 +0000726 // Collect branch weights into a vector.
727 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000728 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000729 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
730 if (HasWeight)
731 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
732 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000733 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000734 Weights.push_back(CI->getValue().getZExtValue());
735 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000736 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
737 --i;
738 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000739 if (HasWeight) {
740 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
741 Weights.pop_back();
742 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000743 i.getCaseSuccessor()->removePredecessor(TI->getParent());
744 SI->removeCase(i);
745 }
746 }
Manman Ren97c18762012-10-11 22:28:34 +0000747 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000748 SI->setMetadata(LLVMContext::MD_prof,
749 MDBuilder(SI->getParent()->getContext()).
750 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000751
752 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000753 return true;
754 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000755
Chris Lattner4088e2b2010-12-13 01:47:07 +0000756 // Otherwise, TI's block must correspond to some matched value. Find out
757 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000758 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000759 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000760 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
761 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000762 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000763 return false; // Cannot handle multiple values coming to this block.
764 TIV = PredCases[i].Value;
765 }
766 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000767
768 // Okay, we found the one constant that our value can be if we get into TI's
769 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000770 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000771 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
772 if (ThisCases[i].Value == TIV) {
773 TheRealDest = ThisCases[i].Dest;
774 break;
775 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000776
777 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000778 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000779
780 // Remove PHI node entries for dead edges.
781 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000782 for (BasicBlock *Succ : successors(TIBB))
783 if (Succ != CheckEdge)
784 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000785 else
Craig Topperf40110f2014-04-25 05:29:35 +0000786 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000787
788 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000789 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000790 (void) NI;
791
792 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
793 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
794
795 EraseTerminatorInstAndDCECond(TI);
796 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000797}
798
Dale Johannesen7f99d222009-03-12 21:01:11 +0000799namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000800 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000801 /// integers that does not depend on their address. This is important for
802 /// applications that sort ConstantInt's to ensure uniqueness.
803 struct ConstantIntOrdering {
804 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
805 return LHS->getValue().ult(RHS->getValue());
806 }
807 };
808}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000809
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000810static int ConstantIntSortPredicate(ConstantInt *const *P1,
811 ConstantInt *const *P2) {
812 const ConstantInt *LHS = *P1;
813 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000814 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000815 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000816 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000817}
818
Andrew Trick3051aa12012-08-29 21:46:38 +0000819static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000820 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000821 if (ProfMD && ProfMD->getOperand(0))
822 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
823 return MDS->getString().equals("branch_weights");
824
825 return false;
826}
827
Manman Ren571d9e42012-09-11 17:43:35 +0000828/// Get Weights of a given TerminatorInst, the default weight is at the front
829/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
830/// metadata.
831static void GetBranchWeights(TerminatorInst *TI,
832 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000833 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000834 assert(MD);
835 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000836 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000837 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000838 }
839
Manman Ren571d9e42012-09-11 17:43:35 +0000840 // If TI is a conditional eq, the default case is the false case,
841 // and the corresponding branch-weight data is at index 2. We swap the
842 // default weight to be the first entry.
843 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
844 assert(Weights.size() == 2);
845 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
846 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
847 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000848 }
849}
850
Manman Renf1cb16e2014-01-27 23:39:03 +0000851/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000852static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000853 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
854 if (Max > UINT_MAX) {
855 unsigned Offset = 32 - countLeadingZeros(Max);
856 for (uint64_t &I : Weights)
857 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000858 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000859}
860
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000861/// The specified terminator is a value equality comparison instruction
862/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000863/// See if any of the predecessors of the terminator block are value comparisons
864/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000865bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
866 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000867 BasicBlock *BB = TI->getParent();
868 Value *CV = isValueEqualityComparison(TI); // CondVal
869 assert(CV && "Not a comparison?");
870 bool Changed = false;
871
Chris Lattner6b39cb92008-02-18 07:42:56 +0000872 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000873 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000874 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000875
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000876 // See if the predecessor is a comparison with the same value.
877 TerminatorInst *PTI = Pred->getTerminator();
878 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
879
880 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
881 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000882 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000883 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
884
Eric Christopherb65acc62012-07-02 23:22:21 +0000885 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000886 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
887
888 // Based on whether the default edge from PTI goes to BB or not, fill in
889 // PredCases and PredDefault with the new switch cases we would like to
890 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000891 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000892
Andrew Trick3051aa12012-08-29 21:46:38 +0000893 // Update the branch weight metadata along the way
894 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000895 bool PredHasWeights = HasBranchWeights(PTI);
896 bool SuccHasWeights = HasBranchWeights(TI);
897
Manman Ren5e5049d2012-09-14 19:05:19 +0000898 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000899 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000900 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000901 if (Weights.size() != 1 + PredCases.size())
902 PredHasWeights = SuccHasWeights = false;
903 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000904 // If there are no predecessor weights but there are successor weights,
905 // populate Weights with 1, which will later be scaled to the sum of
906 // successor's weights
907 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000908
Manman Ren571d9e42012-09-11 17:43:35 +0000909 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000910 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000911 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000912 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000913 if (SuccWeights.size() != 1 + BBCases.size())
914 PredHasWeights = SuccHasWeights = false;
915 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000916 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000917
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000918 if (PredDefault == BB) {
919 // If this is the default destination from PTI, only the edges in TI
920 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000921 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
922 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
923 if (PredCases[i].Dest != BB)
924 PTIHandled.insert(PredCases[i].Value);
925 else {
926 // The default destination is BB, we don't need explicit targets.
927 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000928
Manman Ren571d9e42012-09-11 17:43:35 +0000929 if (PredHasWeights || SuccHasWeights) {
930 // Increase weight for the default case.
931 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000932 std::swap(Weights[i+1], Weights.back());
933 Weights.pop_back();
934 }
935
Eric Christopherb65acc62012-07-02 23:22:21 +0000936 PredCases.pop_back();
937 --i; --e;
938 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000939
Eric Christopherb65acc62012-07-02 23:22:21 +0000940 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000941 if (PredDefault != BBDefault) {
942 PredDefault->removePredecessor(Pred);
943 PredDefault = BBDefault;
944 NewSuccessors.push_back(BBDefault);
945 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000946
Manman Ren571d9e42012-09-11 17:43:35 +0000947 unsigned CasesFromPred = Weights.size();
948 uint64_t ValidTotalSuccWeight = 0;
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 BBCases[i].Dest != BBDefault) {
952 PredCases.push_back(BBCases[i]);
953 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000954 if (SuccHasWeights || PredHasWeights) {
955 // The default weight is at index 0, so weight for the ith case
956 // should be at index i+1. Scale the cases from successor by
957 // PredDefaultWeight (Weights[0]).
958 Weights.push_back(Weights[0] * SuccWeights[i+1]);
959 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000960 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000961 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000962
Manman Ren571d9e42012-09-11 17:43:35 +0000963 if (SuccHasWeights || PredHasWeights) {
964 ValidTotalSuccWeight += SuccWeights[0];
965 // Scale the cases from predecessor by ValidTotalSuccWeight.
966 for (unsigned i = 1; i < CasesFromPred; ++i)
967 Weights[i] *= ValidTotalSuccWeight;
968 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
969 Weights[0] *= SuccWeights[0];
970 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000971 } else {
972 // If this is not the default destination from PSI, only the edges
973 // in SI that occur in PSI with a destination of BB will be
974 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000975 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000976 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000977 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
978 if (PredCases[i].Dest == BB) {
979 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000980
981 if (PredHasWeights || SuccHasWeights) {
982 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
983 std::swap(Weights[i+1], Weights.back());
984 Weights.pop_back();
985 }
986
Eric Christopherb65acc62012-07-02 23:22:21 +0000987 std::swap(PredCases[i], PredCases.back());
988 PredCases.pop_back();
989 --i; --e;
990 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000991
992 // Okay, now we know which constants were sent to BB from the
993 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000994 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
995 if (PTIHandled.count(BBCases[i].Value)) {
996 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000997 if (PredHasWeights || SuccHasWeights)
998 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000999 PredCases.push_back(BBCases[i]);
1000 NewSuccessors.push_back(BBCases[i].Dest);
1001 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
1002 }
1003
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001004 // If there are any constants vectored to BB that TI doesn't handle,
1005 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001006 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +00001007 PTIHandled.begin(),
1008 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +00001009 if (PredHasWeights || SuccHasWeights)
1010 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001011 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001012 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001013 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001014 }
1015
1016 // Okay, at this point, we know which new successor Pred will get. Make
1017 // sure we update the number of entries in the PHI nodes for these
1018 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001019 for (BasicBlock *NewSuccessor : NewSuccessors)
1020 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001021
Devang Patel58380552011-05-18 20:53:17 +00001022 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001023 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001024 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001025 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001026 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001027 }
1028
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001029 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +00001030 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1031 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001032 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001033 for (ValueEqualityComparisonCase &V : PredCases)
1034 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001035
Andrew Trick3051aa12012-08-29 21:46:38 +00001036 if (PredHasWeights || SuccHasWeights) {
1037 // Halve the weights if any of them cannot fit in an uint32_t
1038 FitWeights(Weights);
1039
1040 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1041
1042 NewSI->setMetadata(LLVMContext::MD_prof,
1043 MDBuilder(BB->getContext()).
1044 createBranchWeights(MDWeights));
1045 }
1046
Eli Friedmancb61afb2008-12-16 20:54:32 +00001047 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001048
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001049 // Okay, last check. If BB is still a successor of PSI, then we must
1050 // have an infinite loop case. If so, add an infinitely looping block
1051 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001052 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001053 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1054 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001055 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001056 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001057 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001058 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1059 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001060 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001061 }
1062 NewSI->setSuccessor(i, InfLoopBlock);
1063 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001064
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001065 Changed = true;
1066 }
1067 }
1068 return Changed;
1069}
1070
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001071// If we would need to insert a select that uses the value of this invoke
1072// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1073// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001074static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1075 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001076 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001077 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001078 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001079 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1080 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1081 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1082 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1083 return false;
1084 }
1085 }
1086 }
1087 return true;
1088}
1089
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001090static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1091
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001092/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1093/// in the two blocks up into the branch block. The caller of this function
1094/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001095static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001096 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001097 // This does very trivial matching, with limited scanning, to find identical
1098 // instructions in the two blocks. In particular, we don't want to get into
1099 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1100 // such, we currently just scan for obviously identical instructions in an
1101 // identical order.
1102 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1103 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1104
Devang Patelf10e2872009-02-04 00:03:08 +00001105 BasicBlock::iterator BB1_Itr = BB1->begin();
1106 BasicBlock::iterator BB2_Itr = BB2->begin();
1107
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001108 Instruction *I1 = &*BB1_Itr++, *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))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001114 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001115 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001116 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001117 }
Devang Patele48ddf82011-04-07 00:30:15 +00001118 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001119 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001120 return false;
1121
Chris Lattner389cfac2004-11-30 00:29:14 +00001122 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001123
David Majnemerc82f27a2013-06-03 20:43:12 +00001124 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001125 do {
1126 // If we are hoisting the terminator instruction, don't move one (making a
1127 // broken BB), instead clone it, and remove BI.
1128 if (isa<TerminatorInst>(I1))
1129 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001130
Chad Rosier54390052015-02-23 19:15:16 +00001131 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1132 return Changed;
1133
Chris Lattner389cfac2004-11-30 00:29:14 +00001134 // For a normal instruction, we just move one to right before the branch,
1135 // then replace all uses of the other with the first. Finally, we remove
1136 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001137 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001138 if (!I2->use_empty())
1139 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001140 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001141 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001142 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1143 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001144 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1145 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1146 LLVMContext::MD_dereferenceable_or_null};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001147 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001148 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001149 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001150
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001151 I1 = &*BB1_Itr++;
1152 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001153 // Skip debug info if it is not identical.
1154 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1155 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1156 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1157 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001158 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001159 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001160 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001161 }
Devang Patele48ddf82011-04-07 00:30:15 +00001162 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001163
1164 return true;
1165
1166HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001167 // It may not be possible to hoist an invoke.
1168 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001169 return Changed;
1170
Sanjay Patel5781d842016-03-12 16:52:17 +00001171 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001172 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001173 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001174 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1175 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1176 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1177 if (BB1V == BB2V)
1178 continue;
1179
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001180 // Check for passingValueIsAlwaysUndefined here because we would rather
1181 // eliminate undefined control flow then converting it to a select.
1182 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1183 passingValueIsAlwaysUndefined(BB2V, PN))
1184 return Changed;
1185
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001186 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001187 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001188 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001189 return Changed;
1190 }
1191 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001192
Chris Lattner389cfac2004-11-30 00:29:14 +00001193 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001194 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001195 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001196 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001197 I1->replaceAllUsesWith(NT);
1198 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001199 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001200 }
1201
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001202 IRBuilder<NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001203 // Hoisting one of the terminators from our successor is a great thing.
1204 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1205 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1206 // nodes, so we insert select instruction to compute the final result.
1207 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001208 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001209 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001210 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001211 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001212 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1213 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001214 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001215
Chris Lattner4088e2b2010-12-13 01:47:07 +00001216 // These values do not agree. Insert a select instruction before NT
1217 // that determines the right value.
1218 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001219 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001220 SI = cast<SelectInst>
1221 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
Sanjay Patel2e002772016-03-12 18:05:53 +00001222 BB1V->getName() + "." + BB2V->getName()));
Devang Patel1407fb42011-05-19 20:52:46 +00001223
Chris Lattner4088e2b2010-12-13 01:47:07 +00001224 // Make the PHI node use the select for all incoming values for BB1/BB2
1225 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1226 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1227 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001228 }
1229 }
1230
1231 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001232 for (BasicBlock *Succ : successors(BB1))
1233 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001234
Eli Friedmancb61afb2008-12-16 20:54:32 +00001235 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001236 return true;
1237}
1238
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001239/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001240/// check whether BBEnd has only two predecessors and the other predecessor
1241/// ends with an unconditional branch. If it is true, sink any common code
1242/// in the two predecessors to BBEnd.
1243static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1244 assert(BI1->isUnconditional());
1245 BasicBlock *BB1 = BI1->getParent();
1246 BasicBlock *BBEnd = BI1->getSuccessor(0);
1247
1248 // Check that BBEnd has two predecessors and the other predecessor ends with
1249 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001250 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1251 BasicBlock *Pred0 = *PI++;
1252 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001253 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001254 BasicBlock *Pred1 = *PI++;
1255 if (PI != PE) // More than two predecessors.
1256 return false;
1257 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001258 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1259 if (!BI2 || !BI2->isUnconditional())
1260 return false;
1261
1262 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001263 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001264 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001265 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001266 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1267 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001268 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001269 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001270 } else {
1271 FirstNonPhiInBBEnd = &*I;
1272 break;
1273 }
1274 }
1275 if (!FirstNonPhiInBBEnd)
1276 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001277
Manman Ren93ab6492012-09-20 22:37:36 +00001278 // This does very trivial matching, with limited scanning, to find identical
1279 // instructions in the two blocks. We scan backward for obviously identical
1280 // instructions in an identical order.
1281 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001282 RE1 = BB1->getInstList().rend(),
1283 RI2 = BB2->getInstList().rbegin(),
1284 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001285 // Skip debug info.
1286 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1287 if (RI1 == RE1)
1288 return false;
1289 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1290 if (RI2 == RE2)
1291 return false;
1292 // Skip the unconditional branches.
1293 ++RI1;
1294 ++RI2;
1295
1296 bool Changed = false;
1297 while (RI1 != RE1 && RI2 != RE2) {
1298 // Skip debug info.
1299 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1300 if (RI1 == RE1)
1301 return Changed;
1302 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1303 if (RI2 == RE2)
1304 return Changed;
1305
1306 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001307 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001308 // I1 and I2 should have a single use in the same PHI node, and they
1309 // perform the same operation.
1310 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1311 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1312 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001313 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001314 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1315 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1316 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1317 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001318 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001319 return Changed;
1320
1321 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001322 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001323 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1324 bool SwapOpnds = false;
1325 if (ICmp1 && ICmp2 &&
1326 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1327 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1328 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1329 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1330 ICmp2->swapOperands();
1331 SwapOpnds = true;
1332 }
1333 if (!I1->isSameOperationAs(I2)) {
1334 if (SwapOpnds)
1335 ICmp2->swapOperands();
1336 return Changed;
1337 }
1338
1339 // The operands should be either the same or they need to be generated
1340 // with a PHI node after sinking. We only handle the case where there is
1341 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001342 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001343 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001344 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1345 if (I1->getOperand(I) == I2->getOperand(I))
1346 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001347 // Early exit if we have more-than one pair of different operands or if
1348 // we need a PHI node to replace a constant.
1349 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001350 isa<Constant>(I1->getOperand(I)) ||
1351 isa<Constant>(I2->getOperand(I))) {
1352 // If we can't sink the instructions, undo the swapping.
1353 if (SwapOpnds)
1354 ICmp2->swapOperands();
1355 return Changed;
1356 }
1357 DifferentOp1 = I1->getOperand(I);
1358 Op1Idx = I;
1359 DifferentOp2 = I2->getOperand(I);
1360 }
1361
Michael Liao5313da32014-12-23 08:26:55 +00001362 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1363 DEBUG(dbgs() << " " << *I2 << "\n");
1364
1365 // We insert the pair of different operands to JointValueMap and
1366 // remove (I1, I2) from JointValueMap.
1367 if (Op1Idx != ~0U) {
1368 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1369 if (!NewPN) {
1370 NewPN =
1371 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001372 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001373 NewPN->addIncoming(DifferentOp1, BB1);
1374 NewPN->addIncoming(DifferentOp2, BB2);
1375 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1376 }
Manman Ren93ab6492012-09-20 22:37:36 +00001377 // I1 should use NewPN instead of DifferentOp1.
1378 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001379 }
Michael Liao5313da32014-12-23 08:26:55 +00001380 PHINode *OldPN = JointValueMap[InstPair];
1381 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001382
Manman Ren93ab6492012-09-20 22:37:36 +00001383 // We need to update RE1 and RE2 if we are going to sink the first
1384 // instruction in the basic block down.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001385 bool UpdateRE1 = (I1 == &BB1->front()), UpdateRE2 = (I2 == &BB2->front());
Manman Ren93ab6492012-09-20 22:37:36 +00001386 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001387 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1388 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001389 if (!OldPN->use_empty())
1390 OldPN->replaceAllUsesWith(I1);
1391 OldPN->eraseFromParent();
1392
1393 if (!I2->use_empty())
1394 I2->replaceAllUsesWith(I1);
1395 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001396 // TODO: Use combineMetadata here to preserve what metadata we can
1397 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001398 I2->eraseFromParent();
1399
1400 if (UpdateRE1)
1401 RE1 = BB1->getInstList().rend();
1402 if (UpdateRE2)
1403 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001404 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001405 NumSinkCommons++;
1406 Changed = true;
1407 }
1408 return Changed;
1409}
1410
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001411/// \brief Determine if we can hoist sink a sole store instruction out of a
1412/// conditional block.
1413///
1414/// We are looking for code like the following:
1415/// BrBB:
1416/// store i32 %add, i32* %arrayidx2
1417/// ... // No other stores or function calls (we could be calling a memory
1418/// ... // function).
1419/// %cmp = icmp ult %x, %y
1420/// br i1 %cmp, label %EndBB, label %ThenBB
1421/// ThenBB:
1422/// store i32 %add5, i32* %arrayidx2
1423/// br label EndBB
1424/// EndBB:
1425/// ...
1426/// We are going to transform this into:
1427/// BrBB:
1428/// store i32 %add, i32* %arrayidx2
1429/// ... //
1430/// %cmp = icmp ult %x, %y
1431/// %add.add5 = select i1 %cmp, i32 %add, %add5
1432/// store i32 %add.add5, i32* %arrayidx2
1433/// ...
1434///
1435/// \return The pointer to the value of the previous store if the store can be
1436/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001437static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1438 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001439 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1440 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001441 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001442
1443 // Volatile or atomic.
1444 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001445 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001446
1447 Value *StorePtr = StoreToHoist->getPointerOperand();
1448
1449 // Look for a store to the same pointer in BrBB.
1450 unsigned MaxNumInstToLookAt = 10;
1451 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1452 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1453 Instruction *CurI = &*RI;
1454
1455 // Could be calling an instruction that effects memory like free().
1456 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001457 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001458
1459 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1460 // Found the previous store make sure it stores to the same location.
1461 if (SI && SI->getPointerOperand() == StorePtr)
1462 // Found the previous store, return its value operand.
1463 return SI->getValueOperand();
1464 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001465 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001466 }
1467
Craig Topperf40110f2014-04-25 05:29:35 +00001468 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001469}
1470
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001471/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001472///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001473/// Note that this is a very risky transform currently. Speculating
1474/// instructions like this is most often not desirable. Instead, there is an MI
1475/// pass which can do it with full awareness of the resource constraints.
1476/// However, some cases are "obvious" and we should do directly. An example of
1477/// this is speculating a single, reasonably cheap instruction.
1478///
1479/// There is only one distinct advantage to flattening the CFG at the IR level:
1480/// it makes very common but simplistic optimizations such as are common in
1481/// instcombine and the DAG combiner more powerful by removing CFG edges and
1482/// modeling their effects with easier to reason about SSA value graphs.
1483///
1484///
1485/// An illustration of this transform is turning this IR:
1486/// \code
1487/// BB:
1488/// %cmp = icmp ult %x, %y
1489/// br i1 %cmp, label %EndBB, label %ThenBB
1490/// ThenBB:
1491/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001492/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001493/// EndBB:
1494/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1495/// ...
1496/// \endcode
1497///
1498/// Into this IR:
1499/// \code
1500/// BB:
1501/// %cmp = icmp ult %x, %y
1502/// %sub = sub %x, %y
1503/// %cond = select i1 %cmp, 0, %sub
1504/// ...
1505/// \endcode
1506///
1507/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001508static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001509 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001510 // Be conservative for now. FP select instruction can often be expensive.
1511 Value *BrCond = BI->getCondition();
1512 if (isa<FCmpInst>(BrCond))
1513 return false;
1514
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001515 BasicBlock *BB = BI->getParent();
1516 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1517
1518 // If ThenBB is actually on the false edge of the conditional branch, remember
1519 // to swap the select operands later.
1520 bool Invert = false;
1521 if (ThenBB != BI->getSuccessor(0)) {
1522 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1523 Invert = true;
1524 }
1525 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1526
Chandler Carruthceff2222013-01-25 05:40:09 +00001527 // Keep a count of how many times instructions are used within CondBB when
1528 // they are candidates for sinking into CondBB. Specifically:
1529 // - They are defined in BB, and
1530 // - They have no side effects, and
1531 // - All of their uses are in CondBB.
1532 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1533
Chandler Carruth7481ca82013-01-24 11:52:58 +00001534 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001535 Value *SpeculatedStoreValue = nullptr;
1536 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001537 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001538 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001539 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001540 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001541 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001542 if (isa<DbgInfoIntrinsic>(I))
1543 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001544
Mark Lacey274f48b2015-04-12 18:18:51 +00001545 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001546 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001547 ++SpeculationCost;
1548 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001549 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001550
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001551 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001552 if (!isSafeToSpeculativelyExecute(I) &&
1553 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1554 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001555 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001556 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001557 ComputeSpeculationCost(I, TTI) >
1558 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001559 return false;
1560
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001561 // Store the store speculation candidate.
1562 if (SpeculatedStoreValue)
1563 SpeculatedStore = cast<StoreInst>(I);
1564
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001565 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001566 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001567 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001568 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001569 i != e; ++i) {
1570 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001571 if (!OpI || OpI->getParent() != BB ||
1572 OpI->mayHaveSideEffects())
1573 continue; // Not a candidate for sinking.
1574
1575 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001576 }
1577 }
Evan Cheng89200c92008-06-07 08:52:29 +00001578
Chandler Carruthceff2222013-01-25 05:40:09 +00001579 // Consider any sink candidates which are only used in CondBB as costs for
1580 // speculation. Note, while we iterate over a DenseMap here, we are summing
1581 // and so iteration order isn't significant.
1582 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1583 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1584 I != E; ++I)
1585 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001586 ++SpeculationCost;
1587 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001588 return false;
1589 }
1590
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001591 // Check that the PHI nodes can be converted to selects.
1592 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001593 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001594 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001595 Value *OrigV = PN->getIncomingValueForBlock(BB);
1596 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001597
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001598 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001599 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001600 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001601 continue;
1602
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001603 // Don't convert to selects if we could remove undefined behavior instead.
1604 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1605 passingValueIsAlwaysUndefined(ThenV, PN))
1606 return false;
1607
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001608 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001609 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1610 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1611 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001612 continue; // Known safe and cheap.
1613
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001614 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1615 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001616 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001617 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1618 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001619 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1620 TargetTransformInfo::TCC_Basic;
1621 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001622 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001623
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001624 // Account for the cost of an unfolded ConstantExpr which could end up
1625 // getting expanded into Instructions.
1626 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001627 // constant expression.
1628 ++SpeculationCost;
1629 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001630 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001631 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001632
1633 // If there are no PHIs to process, bail early. This helps ensure idempotence
1634 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001635 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001636 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001637
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001638 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001639 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001640
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001641 // Insert a select of the value of the speculated store.
1642 if (SpeculatedStoreValue) {
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001643 IRBuilder<NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001644 Value *TrueV = SpeculatedStore->getValueOperand();
1645 Value *FalseV = SpeculatedStoreValue;
1646 if (Invert)
1647 std::swap(TrueV, FalseV);
Sanjay Patel796db352016-03-26 23:30:50 +00001648 Value *S = Builder.CreateSelect(
1649 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001650 SpeculatedStore->setOperand(0, S);
1651 }
1652
Igor Laevsky7310c682015-11-18 14:50:18 +00001653 // Metadata can be dependent on the condition we are hoisting above.
1654 // Conservatively strip all metadata on the instruction.
1655 for (auto &I: *ThenBB)
1656 I.dropUnknownNonDebugMetadata();
1657
Chandler Carruth7481ca82013-01-24 11:52:58 +00001658 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001659 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1660 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001661
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001662 // Insert selects and rewrite the PHI operands.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001663 IRBuilder<NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001664 for (BasicBlock::iterator I = EndBB->begin();
1665 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1666 unsigned OrigI = PN->getBasicBlockIndex(BB);
1667 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1668 Value *OrigV = PN->getIncomingValue(OrigI);
1669 Value *ThenV = PN->getIncomingValue(ThenI);
1670
1671 // Skip PHIs which are trivial.
1672 if (OrigV == ThenV)
1673 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001674
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001675 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001676 // false value is the preexisting value. Swap them if the branch
1677 // destinations were inverted.
1678 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001679 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001680 std::swap(TrueV, FalseV);
Sanjay Patelf11ab052016-04-15 15:32:12 +00001681 Value *V = Builder.CreateSelect(
1682 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001683 PN->setIncomingValue(OrigI, V);
1684 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001685 }
1686
Evan Cheng89553cc2008-06-12 21:15:59 +00001687 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001688 return true;
1689}
1690
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001691/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001692static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1693 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001694 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001695
Devang Patel84fceff2009-03-10 18:00:05 +00001696 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001697 if (isa<DbgInfoIntrinsic>(BBI))
1698 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001699 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001700 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001701
Dale Johannesened6f5a82009-03-12 23:18:09 +00001702 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001703 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001704 for (User *U : BBI->users()) {
1705 Instruction *UI = cast<Instruction>(U);
1706 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001707 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001708
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001709 // Looks ok, continue checking.
1710 }
Chris Lattner6c701062005-09-20 01:48:40 +00001711
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001712 return true;
1713}
1714
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001715/// If we have a conditional branch on a PHI node value that is defined in the
1716/// same block as the branch and if any PHI entries are constants, thread edges
1717/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001718static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001719 BasicBlock *BB = BI->getParent();
1720 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001721 // NOTE: we currently cannot transform this case if the PHI node is used
1722 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001723 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1724 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001725
Chris Lattner748f9032005-09-19 23:49:37 +00001726 // Degenerate case of a single entry PHI.
1727 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001728 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001729 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001730 }
1731
1732 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001733 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001734
Justin Lebardb639492016-02-12 21:01:36 +00001735 // Can't fold blocks that contain noduplicate or convergent calls.
1736 if (llvm::any_of(*BB, [](const Instruction &I) {
1737 const CallInst *CI = dyn_cast<CallInst>(&I);
1738 return CI && (CI->cannotDuplicate() || CI->isConvergent());
1739 }))
1740 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00001741
Chris Lattner748f9032005-09-19 23:49:37 +00001742 // Okay, this is a simple enough basic block. See if any phi values are
1743 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001745 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001746 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001747
Chris Lattner4088e2b2010-12-13 01:47:07 +00001748 // Okay, we now know that all edges from PredBB should be revectored to
1749 // branch to RealDest.
1750 BasicBlock *PredBB = PN->getIncomingBlock(i);
1751 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001752
Chris Lattner4088e2b2010-12-13 01:47:07 +00001753 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001754 // Skip if the predecessor's terminator is an indirect branch.
1755 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001756
Chris Lattner4088e2b2010-12-13 01:47:07 +00001757 // The dest block might have PHI nodes, other predecessors and other
1758 // difficult cases. Instead of being smart about this, just insert a new
1759 // block that jumps to the destination block, effectively splitting
1760 // the edge we are about to create.
1761 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1762 RealDest->getName()+".critedge",
1763 RealDest->getParent(), RealDest);
1764 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001765
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001766 // Update PHI nodes.
1767 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001768
1769 // BB may have instructions that are being threaded over. Clone these
1770 // instructions into EdgeBB. We know that there will be no uses of the
1771 // cloned instructions outside of EdgeBB.
1772 BasicBlock::iterator InsertPt = EdgeBB->begin();
1773 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1774 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1775 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1776 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1777 continue;
1778 }
1779 // Clone the instruction.
1780 Instruction *N = BBI->clone();
1781 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001782
Chris Lattner4088e2b2010-12-13 01:47:07 +00001783 // Update operands due to translation.
1784 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1785 i != e; ++i) {
1786 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1787 if (PI != TranslateMap.end())
1788 *i = PI->second;
1789 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001790
Chris Lattner4088e2b2010-12-13 01:47:07 +00001791 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001792 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001793 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001794 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001795 } else {
1796 // Insert the new instruction into its new home.
1797 EdgeBB->getInstList().insert(InsertPt, N);
1798 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001799 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001800 }
1801 }
1802
1803 // Loop over all of the edges from PredBB to BB, changing them to branch
1804 // to EdgeBB instead.
1805 TerminatorInst *PredBBTI = PredBB->getTerminator();
1806 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1807 if (PredBBTI->getSuccessor(i) == BB) {
1808 BB->removePredecessor(PredBB);
1809 PredBBTI->setSuccessor(i, EdgeBB);
1810 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001811
Chris Lattner4088e2b2010-12-13 01:47:07 +00001812 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001813 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001814 }
Chris Lattner748f9032005-09-19 23:49:37 +00001815
1816 return false;
1817}
1818
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001819/// Given a BB that starts with the specified two-entry PHI node,
1820/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001821static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1822 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001823 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1824 // statement", which has a very simple dominance structure. Basically, we
1825 // are trying to find the condition that is being branched on, which
1826 // subsequently causes this merge to happen. We really want control
1827 // dependence information for this check, but simplifycfg can't keep it up
1828 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001829 BasicBlock *BB = PN->getParent();
1830 BasicBlock *IfTrue, *IfFalse;
1831 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001832 if (!IfCond ||
1833 // Don't bother if the branch will be constant folded trivially.
1834 isa<ConstantInt>(IfCond))
1835 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001836
Chris Lattner95adf8f12006-11-18 19:19:36 +00001837 // Okay, we found that we can merge this two-entry phi node into a select.
1838 // Doing so would require us to fold *all* two entry phi nodes in this block.
1839 // At some point this becomes non-profitable (particularly if the target
1840 // doesn't support cmov's). Only do this transformation if there are two or
1841 // fewer PHI nodes in this block.
1842 unsigned NumPhis = 0;
1843 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1844 if (NumPhis > 2)
1845 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001846
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001847 // Loop over the PHI's seeing if we can promote them all to select
1848 // instructions. While we are at it, keep track of the instructions
1849 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001850 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001851 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1852 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001853 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1854 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001855
Chris Lattner7499b452010-12-14 08:46:09 +00001856 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1857 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001858 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001859 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001860 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001861 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001862 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001863
Peter Collingbournee3511e12011-04-29 18:47:31 +00001864 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001865 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001866 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001867 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001868 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001869 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001870
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001871 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001872 // we ran out of PHIs then we simplified them all.
1873 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001874 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001875
Chris Lattner7499b452010-12-14 08:46:09 +00001876 // Don't fold i1 branches on PHIs which contain binary operators. These can
1877 // often be turned into switches and other things.
1878 if (PN->getType()->isIntegerTy(1) &&
1879 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1880 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1881 isa<BinaryOperator>(IfCond)))
1882 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001883
Sanjay Patel2e002772016-03-12 18:05:53 +00001884 // If all PHI nodes are promotable, check to make sure that all instructions
1885 // in the predecessor blocks can be promoted as well. If not, we won't be able
1886 // to get rid of the control flow, so it's not worth promoting to select
1887 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001888 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001889 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1890 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1891 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001892 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001893 } else {
1894 DomBlock = *pred_begin(IfBlock1);
1895 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001896 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001897 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00001898 // Because of this, we won't be able to get rid of the control flow, so
1899 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001900 return false;
1901 }
1902 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001903
Chris Lattner9ac168d2010-12-14 07:41:39 +00001904 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001905 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001906 } else {
1907 DomBlock = *pred_begin(IfBlock2);
1908 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001909 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001910 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00001911 // Because of this, we won't be able to get rid of the control flow, so
1912 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001913 return false;
1914 }
1915 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001916
Chris Lattner9fd838d2010-12-14 07:23:10 +00001917 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001918 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001919
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001920 // If we can still promote the PHI nodes after this gauntlet of tests,
1921 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001922 Instruction *InsertPt = DomBlock->getTerminator();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001923 IRBuilder<NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001924
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001925 // Move all 'aggressive' instructions, which are defined in the
1926 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001927 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001928 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001929 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001930 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001931 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001932 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001933 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001934 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001935
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001936 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1937 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001938 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1939 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001940
Sanjay Patel9e23fed2016-03-17 15:30:52 +00001941 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
1942 PN->replaceAllUsesWith(Sel);
1943 Sel->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001944 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001945 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001946
Chris Lattner335f0e42010-12-14 08:01:53 +00001947 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1948 // has been flattened. Change DomBlock to jump directly to our new block to
1949 // avoid other simplifycfg's kicking in on the diamond.
1950 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001951 Builder.SetInsertPoint(OldTI);
1952 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001953 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001954 return true;
1955}
Chris Lattner748f9032005-09-19 23:49:37 +00001956
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001957/// If we found a conditional branch that goes to two returning blocks,
1958/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001959/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001960static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001961 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001962 assert(BI->isConditional() && "Must be a conditional branch");
1963 BasicBlock *TrueSucc = BI->getSuccessor(0);
1964 BasicBlock *FalseSucc = BI->getSuccessor(1);
1965 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1966 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001967
Chris Lattner86bbf332008-04-24 00:01:19 +00001968 // Check to ensure both blocks are empty (just a return) or optionally empty
1969 // with PHI nodes. If there are other instructions, merging would cause extra
1970 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001971 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001972 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001973 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001974 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001975
Devang Pateldd14e0f2011-05-18 21:33:11 +00001976 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001977 // Okay, we found a branch that is going to two return nodes. If
1978 // there is no return value for this function, just change the
1979 // branch into a return.
1980 if (FalseRet->getNumOperands() == 0) {
1981 TrueSucc->removePredecessor(BI->getParent());
1982 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001983 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001984 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001985 return true;
1986 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001987
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001988 // Otherwise, figure out what the true and false return values are
1989 // so we can insert a new select instruction.
1990 Value *TrueValue = TrueRet->getReturnValue();
1991 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001992
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001993 // Unwrap any PHI nodes in the return blocks.
1994 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1995 if (TVPN->getParent() == TrueSucc)
1996 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1997 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1998 if (FVPN->getParent() == FalseSucc)
1999 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002000
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002001 // In order for this transformation to be safe, we must be able to
2002 // unconditionally execute both operands to the return. This is
2003 // normally the case, but we could have a potentially-trapping
2004 // constant expression that prevents this transformation from being
2005 // safe.
2006 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2007 if (TCV->canTrap())
2008 return false;
2009 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2010 if (FCV->canTrap())
2011 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002012
Chris Lattner86bbf332008-04-24 00:01:19 +00002013 // Okay, we collected all the mapped values and checked them for sanity, and
2014 // defined to really do this transformation. First, update the CFG.
2015 TrueSucc->removePredecessor(BI->getParent());
2016 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002017
Chris Lattner86bbf332008-04-24 00:01:19 +00002018 // Insert select instructions where needed.
2019 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002020 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002021 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002022 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2023 } else if (isa<UndefValue>(TrueValue)) {
2024 TrueValue = FalseValue;
2025 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00002026 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2027 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002028 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002029 }
2030
Andrew Trickf3cf1932012-08-29 21:46:36 +00002031 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002032 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2033
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002034 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002035
David Greene725c7c32010-01-05 01:26:52 +00002036 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002037 << "\n " << *BI << "NewRet = " << *RI
2038 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002039
Eli Friedmancb61afb2008-12-16 20:54:32 +00002040 EraseTerminatorInstAndDCECond(BI);
2041
Chris Lattner86bbf332008-04-24 00:01:19 +00002042 return true;
2043}
2044
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002045/// Given a conditional BranchInstruction, retrieve the probabilities of the
2046/// branch taking each edge. Fills in the two APInt parameters and returns true,
2047/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002048static bool ExtractBranchMetadata(BranchInst *BI,
2049 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2050 assert(BI->isConditional() &&
2051 "Looking for probabilities on unconditional branch?");
2052 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2053 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002054 ConstantInt *CITrue =
2055 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2056 ConstantInt *CIFalse =
2057 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002058 if (!CITrue || !CIFalse) return false;
2059 ProbTrue = CITrue->getValue().getZExtValue();
2060 ProbFalse = CIFalse->getValue().getZExtValue();
2061 return true;
2062}
2063
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002064/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002065/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002066static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002067 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2068 return false;
2069 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2070 Instruction *PBI = &*I;
2071 // Check whether Inst and PBI generate the same value.
2072 if (Inst->isIdenticalTo(PBI)) {
2073 Inst->replaceAllUsesWith(PBI);
2074 Inst->eraseFromParent();
2075 return true;
2076 }
2077 }
2078 return false;
2079}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002080
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002081/// If this basic block is simple enough, and if a predecessor branches to us
2082/// and one of our successors, fold the block into the predecessor and use
2083/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002084bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002085 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002086
Craig Topperf40110f2014-04-25 05:29:35 +00002087 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002088 if (BI->isConditional())
2089 Cond = dyn_cast<Instruction>(BI->getCondition());
2090 else {
2091 // For unconditional branch, check for a simple CFG pattern, where
2092 // BB has a single predecessor and BB's successor is also its predecessor's
2093 // successor. If such pattern exisits, check for CSE between BB and its
2094 // predecessor.
2095 if (BasicBlock *PB = BB->getSinglePredecessor())
2096 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2097 if (PBI->isConditional() &&
2098 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2099 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2100 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2101 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002102 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002103 if (isa<CmpInst>(Curr)) {
2104 Cond = Curr;
2105 break;
2106 }
2107 // Quit if we can't remove this instruction.
2108 if (!checkCSEInPredecessor(Curr, PB))
2109 return false;
2110 }
2111 }
2112
Craig Topperf40110f2014-04-25 05:29:35 +00002113 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002114 return false;
2115 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002116
Craig Topperf40110f2014-04-25 05:29:35 +00002117 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2118 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002119 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002120
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002121 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002122 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002123
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002124 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002125 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002126
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002127 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002128 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002129
Jingyue Wufc029672014-09-30 22:23:38 +00002130 // Only allow this transformation if computing the condition doesn't involve
2131 // too many instructions and these involved instructions can be executed
2132 // unconditionally. We denote all involved instructions except the condition
2133 // as "bonus instructions", and only allow this transformation when the
2134 // number of the bonus instructions does not exceed a certain threshold.
2135 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002136 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002137 // Ignore dbg intrinsics.
2138 if (isa<DbgInfoIntrinsic>(I))
2139 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002140 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002141 return false;
2142 // I has only one use and can be executed unconditionally.
2143 Instruction *User = dyn_cast<Instruction>(I->user_back());
2144 if (User == nullptr || User->getParent() != BB)
2145 return false;
2146 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2147 // to use any other instruction, User must be an instruction between next(I)
2148 // and Cond.
2149 ++NumBonusInsts;
2150 // Early exits once we reach the limit.
2151 if (NumBonusInsts > BonusInstThreshold)
2152 return false;
2153 }
2154
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002155 // Cond is known to be a compare or binary operator. Check to make sure that
2156 // neither operand is a potentially-trapping constant expression.
2157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2158 if (CE->canTrap())
2159 return false;
2160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2161 if (CE->canTrap())
2162 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002163
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002164 // Finally, don't infinitely unroll conditional loops.
2165 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002166 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002167 if (TrueDest == BB || FalseDest == BB)
2168 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002169
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002170 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2171 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002172 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002173
Chris Lattner80b03a12008-07-13 22:23:11 +00002174 // Check that we have two conditional branches. If there is a PHI node in
2175 // the common successor, verify that the same value flows in from both
2176 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002177 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002178 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002179 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002180 !SafeToMergeTerminators(BI, PBI)) ||
2181 (!BI->isConditional() &&
2182 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002183 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002184
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002185 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002186 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002187 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002188
Manman Rend33f4ef2012-06-13 05:43:29 +00002189 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002190 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002191 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002192 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002193 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002194 } else if (PBI->getSuccessor(0) == FalseDest) {
2195 Opc = Instruction::And;
2196 InvertPredCond = true;
2197 } else if (PBI->getSuccessor(1) == TrueDest) {
2198 Opc = Instruction::Or;
2199 InvertPredCond = true;
2200 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002201 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002202 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002203 } else {
2204 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2205 continue;
2206 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002207
David Greene725c7c32010-01-05 01:26:52 +00002208 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002209 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002210
Chris Lattner55eaae12008-07-13 21:20:19 +00002211 // If we need to invert the condition in the pred block to match, do so now.
2212 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002213 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002214
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002215 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2216 CmpInst *CI = cast<CmpInst>(NewCond);
2217 CI->setPredicate(CI->getInversePredicate());
2218 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002219 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002220 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002221 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002222
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002223 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002224 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002225 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002226
Jingyue Wufc029672014-09-30 22:23:38 +00002227 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002228 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002229 // bonus instructions to a predecessor block.
2230 ValueToValueMapTy VMap; // maps original values to cloned values
2231 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002232 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002233 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002234 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002235 if (isa<DbgInfoIntrinsic>(BonusInst))
2236 continue;
2237 Instruction *NewBonusInst = BonusInst->clone();
2238 RemapInstruction(NewBonusInst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002239 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002240 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002241
2242 // If we moved a load, we cannot any longer claim any knowledge about
2243 // its potential value. The previous information might have been valid
2244 // only given the branch precondition.
2245 // For an analogous reason, we must also drop all the metadata whose
2246 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002247 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002248
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002249 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2250 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002251 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002252 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002253
Chris Lattner55eaae12008-07-13 21:20:19 +00002254 // Clone Cond into the predecessor basic block, and or/and the
2255 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002256 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002257 RemapInstruction(New, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002258 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002259 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002260 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002261 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002262
Manman Rend33f4ef2012-06-13 05:43:29 +00002263 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002264 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002265 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002266 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002267 PBI->setCondition(NewCond);
2268
Manman Renbfb9d432012-09-15 00:39:57 +00002269 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002270 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2271 PredFalseWeight);
2272 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2273 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002274 SmallVector<uint64_t, 8> NewWeights;
2275
Manman Rend33f4ef2012-06-13 05:43:29 +00002276 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002277 if (PredHasWeights && SuccHasWeights) {
2278 // PBI: br i1 %x, BB, FalseDest
2279 // BI: br i1 %y, TrueDest, FalseDest
2280 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2281 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2282 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2283 // TrueWeight for PBI * FalseWeight for BI.
2284 // We assume that total weights of a BranchInst can fit into 32 bits.
2285 // Therefore, we will not have overflow using 64-bit arithmetic.
2286 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2287 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2288 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002289 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2290 PBI->setSuccessor(0, TrueDest);
2291 }
2292 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002293 if (PredHasWeights && SuccHasWeights) {
2294 // PBI: br i1 %x, TrueDest, BB
2295 // BI: br i1 %y, TrueDest, FalseDest
2296 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2297 // FalseWeight for PBI * TrueWeight for BI.
2298 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2299 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2300 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2301 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2302 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002303 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2304 PBI->setSuccessor(1, FalseDest);
2305 }
Manman Renbfb9d432012-09-15 00:39:57 +00002306 if (NewWeights.size() == 2) {
2307 // Halve the weights if any of them cannot fit in an uint32_t
2308 FitWeights(NewWeights);
2309
2310 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2311 PBI->setMetadata(LLVMContext::MD_prof,
2312 MDBuilder(BI->getContext()).
2313 createBranchWeights(MDWeights));
2314 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002315 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002316 } else {
2317 // Update PHI nodes in the common successors.
2318 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002319 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002320 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2321 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002322 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002323 if (PBI->getSuccessor(0) == TrueDest) {
2324 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2325 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2326 // is false: !PBI_Cond and BI_Value
2327 Instruction *NotCond =
2328 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2329 "not.cond"));
2330 MergedCond =
2331 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2332 NotCond, New,
2333 "and.cond"));
2334 if (PBI_C->isOne())
2335 MergedCond =
2336 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2337 PBI->getCondition(), MergedCond,
2338 "or.cond"));
2339 } else {
2340 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2341 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2342 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002343 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002344 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2345 PBI->getCondition(), New,
2346 "and.cond"));
2347 if (PBI_C->isOne()) {
2348 Instruction *NotCond =
2349 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2350 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002351 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002352 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2353 NotCond, MergedCond,
2354 "or.cond"));
2355 }
2356 }
2357 // Update PHI Node.
2358 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2359 MergedCond);
2360 }
2361 // Change PBI from Conditional to Unconditional.
2362 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2363 EraseTerminatorInstAndDCECond(PBI);
2364 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002365 }
Devang Pateld715ec82011-04-06 22:37:20 +00002366
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002367 // TODO: If BB is reachable from all paths through PredBlock, then we
2368 // could replace PBI's branch probabilities with BI's.
2369
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002370 // Copy any debug value intrinsics into the end of PredBlock.
2371 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2372 if (isa<DbgInfoIntrinsic>(*I))
2373 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002374
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002375 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002376 }
2377 return false;
2378}
2379
James Molloy4de84dd2015-11-04 15:28:04 +00002380// If there is only one store in BB1 and BB2, return it, otherwise return
2381// nullptr.
2382static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2383 StoreInst *S = nullptr;
2384 for (auto *BB : {BB1, BB2}) {
2385 if (!BB)
2386 continue;
2387 for (auto &I : *BB)
2388 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2389 if (S)
2390 // Multiple stores seen.
2391 return nullptr;
2392 else
2393 S = SI;
2394 }
2395 }
2396 return S;
2397}
2398
2399static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2400 Value *AlternativeV = nullptr) {
2401 // PHI is going to be a PHI node that allows the value V that is defined in
2402 // BB to be referenced in BB's only successor.
2403 //
2404 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2405 // doesn't matter to us what the other operand is (it'll never get used). We
2406 // could just create a new PHI with an undef incoming value, but that could
2407 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2408 // other PHI. So here we directly look for some PHI in BB's successor with V
2409 // as an incoming operand. If we find one, we use it, else we create a new
2410 // one.
2411 //
2412 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2413 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2414 // where OtherBB is the single other predecessor of BB's only successor.
2415 PHINode *PHI = nullptr;
2416 BasicBlock *Succ = BB->getSingleSuccessor();
2417
2418 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2419 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2420 PHI = cast<PHINode>(I);
2421 if (!AlternativeV)
2422 break;
2423
2424 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2425 auto PredI = pred_begin(Succ);
2426 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2427 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2428 break;
2429 PHI = nullptr;
2430 }
2431 if (PHI)
2432 return PHI;
2433
James Molloy3d21dcf2015-12-16 14:12:44 +00002434 // If V is not an instruction defined in BB, just return it.
2435 if (!AlternativeV &&
2436 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2437 return V;
2438
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002439 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002440 PHI->addIncoming(V, BB);
2441 for (BasicBlock *PredBB : predecessors(Succ))
2442 if (PredBB != BB)
2443 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2444 PredBB);
2445 return PHI;
2446}
2447
2448static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2449 BasicBlock *QTB, BasicBlock *QFB,
2450 BasicBlock *PostBB, Value *Address,
2451 bool InvertPCond, bool InvertQCond) {
2452 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2453 return Operator::getOpcode(&I) == Instruction::BitCast &&
2454 I.getType()->isPointerTy();
2455 };
2456
2457 // If we're not in aggressive mode, we only optimize if we have some
2458 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2459 auto IsWorthwhile = [&](BasicBlock *BB) {
2460 if (!BB)
2461 return true;
2462 // Heuristic: if the block can be if-converted/phi-folded and the
2463 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2464 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002465 unsigned N = 0;
2466 for (auto &I : *BB) {
2467 // Cheap instructions viable for folding.
2468 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2469 isa<StoreInst>(I))
2470 ++N;
2471 // Free instructions.
2472 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2473 IsaBitcastOfPointerType(I))
2474 continue;
2475 else
James Molloy4de84dd2015-11-04 15:28:04 +00002476 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002477 }
2478 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002479 };
2480
2481 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2482 !IsWorthwhile(PFB) ||
2483 !IsWorthwhile(QTB) ||
2484 !IsWorthwhile(QFB)))
2485 return false;
2486
2487 // For every pointer, there must be exactly two stores, one coming from
2488 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2489 // store (to any address) in PTB,PFB or QTB,QFB.
2490 // FIXME: We could relax this restriction with a bit more work and performance
2491 // testing.
2492 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2493 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2494 if (!PStore || !QStore)
2495 return false;
2496
2497 // Now check the stores are compatible.
2498 if (!QStore->isUnordered() || !PStore->isUnordered())
2499 return false;
2500
2501 // Check that sinking the store won't cause program behavior changes. Sinking
2502 // the store out of the Q blocks won't change any behavior as we're sinking
2503 // from a block to its unconditional successor. But we're moving a store from
2504 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2505 // So we need to check that there are no aliasing loads or stores in
2506 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2507 // operations between PStore and the end of its parent block.
2508 //
2509 // The ideal way to do this is to query AliasAnalysis, but we don't
2510 // preserve AA currently so that is dangerous. Be super safe and just
2511 // check there are no other memory operations at all.
2512 for (auto &I : *QFB->getSinglePredecessor())
2513 if (I.mayReadOrWriteMemory())
2514 return false;
2515 for (auto &I : *QFB)
2516 if (&I != QStore && I.mayReadOrWriteMemory())
2517 return false;
2518 if (QTB)
2519 for (auto &I : *QTB)
2520 if (&I != QStore && I.mayReadOrWriteMemory())
2521 return false;
2522 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2523 I != E; ++I)
2524 if (&*I != PStore && I->mayReadOrWriteMemory())
2525 return false;
2526
2527 // OK, we're going to sink the stores to PostBB. The store has to be
2528 // conditional though, so first create the predicate.
2529 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2530 ->getCondition();
2531 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2532 ->getCondition();
2533
2534 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2535 PStore->getParent());
2536 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2537 QStore->getParent(), PPHI);
2538
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002539 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2540
James Molloy4de84dd2015-11-04 15:28:04 +00002541 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2542 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2543
2544 if (InvertPCond)
2545 PPred = QB.CreateNot(PPred);
2546 if (InvertQCond)
2547 QPred = QB.CreateNot(QPred);
2548 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2549
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002550 auto *T =
2551 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002552 QB.SetInsertPoint(T);
2553 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2554 AAMDNodes AAMD;
2555 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2556 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2557 SI->setAAMetadata(AAMD);
2558
2559 QStore->eraseFromParent();
2560 PStore->eraseFromParent();
2561
2562 return true;
2563}
2564
2565static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2566 // The intention here is to find diamonds or triangles (see below) where each
2567 // conditional block contains a store to the same address. Both of these
2568 // stores are conditional, so they can't be unconditionally sunk. But it may
2569 // be profitable to speculatively sink the stores into one merged store at the
2570 // end, and predicate the merged store on the union of the two conditions of
2571 // PBI and QBI.
2572 //
2573 // This can reduce the number of stores executed if both of the conditions are
2574 // true, and can allow the blocks to become small enough to be if-converted.
2575 // This optimization will also chain, so that ladders of test-and-set
2576 // sequences can be if-converted away.
2577 //
2578 // We only deal with simple diamonds or triangles:
2579 //
2580 // PBI or PBI or a combination of the two
2581 // / \ | \
2582 // PTB PFB | PFB
2583 // \ / | /
2584 // QBI QBI
2585 // / \ | \
2586 // QTB QFB | QFB
2587 // \ / | /
2588 // PostBB PostBB
2589 //
2590 // We model triangles as a type of diamond with a nullptr "true" block.
2591 // Triangles are canonicalized so that the fallthrough edge is represented by
2592 // a true condition, as in the diagram above.
2593 //
2594 BasicBlock *PTB = PBI->getSuccessor(0);
2595 BasicBlock *PFB = PBI->getSuccessor(1);
2596 BasicBlock *QTB = QBI->getSuccessor(0);
2597 BasicBlock *QFB = QBI->getSuccessor(1);
2598 BasicBlock *PostBB = QFB->getSingleSuccessor();
2599
2600 bool InvertPCond = false, InvertQCond = false;
2601 // Canonicalize fallthroughs to the true branches.
2602 if (PFB == QBI->getParent()) {
2603 std::swap(PFB, PTB);
2604 InvertPCond = true;
2605 }
2606 if (QFB == PostBB) {
2607 std::swap(QFB, QTB);
2608 InvertQCond = true;
2609 }
2610
2611 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2612 // and QFB may not. Model fallthroughs as a nullptr block.
2613 if (PTB == QBI->getParent())
2614 PTB = nullptr;
2615 if (QTB == PostBB)
2616 QTB = nullptr;
2617
2618 // Legality bailouts. We must have at least the non-fallthrough blocks and
2619 // the post-dominating block, and the non-fallthroughs must only have one
2620 // predecessor.
2621 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2622 return BB->getSinglePredecessor() == P &&
2623 BB->getSingleSuccessor() == S;
2624 };
2625 if (!PostBB ||
2626 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2627 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2628 return false;
2629 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2630 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2631 return false;
2632 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2633 return false;
2634
2635 // OK, this is a sequence of two diamonds or triangles.
2636 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2637 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2638 for (auto *BB : {PTB, PFB}) {
2639 if (!BB)
2640 continue;
2641 for (auto &I : *BB)
2642 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2643 PStoreAddresses.insert(SI->getPointerOperand());
2644 }
2645 for (auto *BB : {QTB, QFB}) {
2646 if (!BB)
2647 continue;
2648 for (auto &I : *BB)
2649 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2650 QStoreAddresses.insert(SI->getPointerOperand());
2651 }
2652
2653 set_intersect(PStoreAddresses, QStoreAddresses);
2654 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2655 // clear what it contains.
2656 auto &CommonAddresses = PStoreAddresses;
2657
2658 bool Changed = false;
2659 for (auto *Address : CommonAddresses)
2660 Changed |= mergeConditionalStoreToAddress(
2661 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2662 return Changed;
2663}
2664
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002665/// If we have a conditional branch as a predecessor of another block,
2666/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002667/// that PBI and BI are both conditional branches, and BI is in one of the
2668/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002669static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2670 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002671 assert(PBI->isConditional() && BI->isConditional());
2672 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002673
Chris Lattner9aada1d2008-07-13 21:53:26 +00002674 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002675 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002676 // this conditional branch redundant.
2677 if (PBI->getCondition() == BI->getCondition() &&
2678 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2679 // Okay, the outcome of this conditional branch is statically
2680 // knowable. If this block had a single pred, handle specially.
2681 if (BB->getSinglePredecessor()) {
2682 // Turn this into a branch on constant.
2683 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002684 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002685 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002686 return true; // Nuke the branch on constant.
2687 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002688
Chris Lattner9aada1d2008-07-13 21:53:26 +00002689 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2690 // in the constant and simplify the block result. Subsequent passes of
2691 // simplifycfg will thread the block.
2692 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002693 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002694 PHINode *NewPN = PHINode::Create(
2695 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2696 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002697 // Okay, we're going to insert the PHI node. Since PBI is not the only
2698 // predecessor, compute the PHI'd conditional value for all of the preds.
2699 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002700 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002701 BasicBlock *P = *PI;
2702 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002703 PBI != BI && PBI->isConditional() &&
2704 PBI->getCondition() == BI->getCondition() &&
2705 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2706 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002707 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002708 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002709 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002710 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002711 }
Gabor Greif8629f122010-07-12 10:59:23 +00002712 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002713
Chris Lattner9aada1d2008-07-13 21:53:26 +00002714 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002715 return true;
2716 }
2717 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002718
Philip Reamesb42db212015-10-14 22:46:19 +00002719 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2720 if (CE->canTrap())
2721 return false;
2722
Philip Reames846e3e42015-10-29 03:11:49 +00002723 // If BI is reached from the true path of PBI and PBI's condition implies
2724 // BI's condition, we know the direction of the BI branch.
2725 if (PBI->getSuccessor(0) == BI->getParent() &&
Sanjoy Das55ea67c2015-11-06 19:01:08 +00002726 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
Philip Reames846e3e42015-10-29 03:11:49 +00002727 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2728 BB->getSinglePredecessor()) {
2729 // Turn this into a branch on constant.
2730 auto *OldCond = BI->getCondition();
2731 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2732 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2733 return true; // Nuke the branch on constant.
2734 }
2735
James Molloy4de84dd2015-11-04 15:28:04 +00002736 // If both branches are conditional and both contain stores to the same
2737 // address, remove the stores from the conditionals and create a conditional
2738 // merged store at the end.
2739 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2740 return true;
2741
Chris Lattner9aada1d2008-07-13 21:53:26 +00002742 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002743 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002744 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002745 BasicBlock::iterator BBI = BB->begin();
2746 // Ignore dbg intrinsics.
2747 while (isa<DbgInfoIntrinsic>(BBI))
2748 ++BBI;
2749 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002750 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002751
Chris Lattner834ab4e2008-07-13 22:04:41 +00002752 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00002753 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
2754 PBIOp = 0;
2755 BIOp = 0;
2756 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
2757 PBIOp = 0;
2758 BIOp = 1;
2759 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
2760 PBIOp = 1;
2761 BIOp = 0;
2762 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
2763 PBIOp = 1;
2764 BIOp = 1;
2765 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002766 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00002767 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002768
Chris Lattner834ab4e2008-07-13 22:04:41 +00002769 // Check to make sure that the other destination of this branch
2770 // isn't BB itself. If so, this is an infinite loop that will
2771 // keep getting unwound.
2772 if (PBI->getSuccessor(PBIOp) == BB)
2773 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002774
2775 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002776 // insertion of a large number of select instructions. For targets
2777 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002778
Sanjay Patela932da82014-07-07 21:19:00 +00002779 // Also do not perform this transformation if any phi node in the common
2780 // destination block can trap when reached by BB or PBB (PR17073). In that
2781 // case, it would be unsafe to hoist the operation into a select instruction.
2782
2783 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002784 unsigned NumPhis = 0;
2785 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002786 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002787 if (NumPhis > 2) // Disable this xform.
2788 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002789
Sanjay Patela932da82014-07-07 21:19:00 +00002790 PHINode *PN = cast<PHINode>(II);
2791 Value *BIV = PN->getIncomingValueForBlock(BB);
2792 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2793 if (CE->canTrap())
2794 return false;
2795
2796 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2797 Value *PBIV = PN->getIncomingValue(PBBIdx);
2798 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2799 if (CE->canTrap())
2800 return false;
2801 }
2802
Chris Lattner834ab4e2008-07-13 22:04:41 +00002803 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002804 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002805
David Greene725c7c32010-01-05 01:26:52 +00002806 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002807 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002808
2809
Chris Lattner80b03a12008-07-13 22:23:11 +00002810 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2811 // branch in it, where one edge (OtherDest) goes back to itself but the other
2812 // exits. We don't *know* that the program avoids the infinite loop
2813 // (even though that seems likely). If we do this xform naively, we'll end up
2814 // recursively unpeeling the loop. Since we know that (after the xform is
2815 // done) that the block *is* infinite if reached, we just make it an obviously
2816 // infinite loop with no cond branch.
2817 if (OtherDest == BB) {
2818 // Insert it at the end of the function, because it's either code,
2819 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002820 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2821 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002822 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2823 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002824 }
2825
David Greene725c7c32010-01-05 01:26:52 +00002826 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002827
Chris Lattner834ab4e2008-07-13 22:04:41 +00002828 // BI may have other predecessors. Because of this, we leave
2829 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002830
Chris Lattner834ab4e2008-07-13 22:04:41 +00002831 // Make sure we get to CommonDest on True&True directions.
2832 Value *PBICond = PBI->getCondition();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002833 IRBuilder<NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002834 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002835 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2836
Chris Lattner834ab4e2008-07-13 22:04:41 +00002837 Value *BICond = BI->getCondition();
2838 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002839 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2840
Chris Lattner834ab4e2008-07-13 22:04:41 +00002841 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002842 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002843
Chris Lattner834ab4e2008-07-13 22:04:41 +00002844 // Modify PBI to branch on the new condition to the new dests.
2845 PBI->setCondition(Cond);
2846 PBI->setSuccessor(0, CommonDest);
2847 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002848
Manman Ren2d4c10f2012-09-17 21:30:40 +00002849 // Update branch weight for PBI.
2850 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002851 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2852 PredFalseWeight);
2853 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2854 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002855 if (PredHasWeights && SuccHasWeights) {
2856 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2857 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2858 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2859 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2860 // The weight to CommonDest should be PredCommon * SuccTotal +
2861 // PredOther * SuccCommon.
2862 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002863 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2864 PredOther * SuccCommon,
2865 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002866 // Halve the weights if any of them cannot fit in an uint32_t
2867 FitWeights(NewWeights);
2868
Manman Ren2d4c10f2012-09-17 21:30:40 +00002869 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002870 MDBuilder(BI->getContext())
2871 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002872 }
2873
Chris Lattner834ab4e2008-07-13 22:04:41 +00002874 // OtherDest may have phi nodes. If so, add an entry from PBI's
2875 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002876 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002877
Chris Lattner834ab4e2008-07-13 22:04:41 +00002878 // We know that the CommonDest already had an edge from PBI to
2879 // it. If it has PHIs though, the PHIs may have different
2880 // entries for BB and PBI's BB. If so, insert a select to make
2881 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002882 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002883 for (BasicBlock::iterator II = CommonDest->begin();
2884 (PN = dyn_cast<PHINode>(II)); ++II) {
2885 Value *BIV = PN->getIncomingValueForBlock(BB);
2886 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2887 Value *PBIV = PN->getIncomingValue(PBBIdx);
2888 if (BIV != PBIV) {
2889 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002890 Value *NV = cast<SelectInst>
Sanjay Patel2e002772016-03-12 18:05:53 +00002891 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002892 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002893 }
2894 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002895
David Greene725c7c32010-01-05 01:26:52 +00002896 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2897 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002898
Chris Lattner834ab4e2008-07-13 22:04:41 +00002899 // This basic block is probably dead. We know it has at least
2900 // one fewer predecessor.
2901 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002902}
2903
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002904// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2905// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002906// Takes care of updating the successors and removing the old terminator.
2907// Also makes sure not to introduce new successors by assuming that edges to
2908// non-successor TrueBBs and FalseBBs aren't reachable.
2909static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002910 BasicBlock *TrueBB, BasicBlock *FalseBB,
2911 uint32_t TrueWeight,
2912 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002913 // Remove any superfluous successor edges from the CFG.
2914 // First, figure out which successors to preserve.
2915 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2916 // successor.
2917 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002918 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002919
2920 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002921 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002922 // Make sure only to keep exactly one copy of each edge.
2923 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002924 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002925 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002926 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002927 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002928 Succ->removePredecessor(OldTerm->getParent(),
2929 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002930 }
2931
Devang Patel2c2ea222011-05-18 18:43:31 +00002932 IRBuilder<> Builder(OldTerm);
2933 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2934
Frits van Bommel8e158492011-01-11 12:52:11 +00002935 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002936 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002937 if (TrueBB == FalseBB)
2938 // We were only looking for one successor, and it was present.
2939 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002940 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002941 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002942 // We found both of the successors we were looking for.
2943 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002944 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2945 if (TrueWeight != FalseWeight)
2946 NewBI->setMetadata(LLVMContext::MD_prof,
2947 MDBuilder(OldTerm->getContext()).
2948 createBranchWeights(TrueWeight, FalseWeight));
2949 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002950 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2951 // Neither of the selected blocks were successors, so this
2952 // terminator must be unreachable.
2953 new UnreachableInst(OldTerm->getContext(), OldTerm);
2954 } else {
2955 // One of the selected values was a successor, but the other wasn't.
2956 // Insert an unconditional branch to the one that was found;
2957 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002958 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002959 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002960 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002961 else
2962 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002963 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002964 }
2965
2966 EraseTerminatorInstAndDCECond(OldTerm);
2967 return true;
2968}
2969
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002970// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002971// (switch (select cond, X, Y)) on constant X, Y
2972// with a branch - conditional if X and Y lead to distinct BBs,
2973// unconditional otherwise.
2974static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2975 // Check for constant integer values in the select.
2976 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2977 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2978 if (!TrueVal || !FalseVal)
2979 return false;
2980
2981 // Find the relevant condition and destinations.
2982 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002983 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2984 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002985
Manman Ren774246a2012-09-17 22:28:55 +00002986 // Get weight for TrueBB and FalseBB.
2987 uint32_t TrueWeight = 0, FalseWeight = 0;
2988 SmallVector<uint64_t, 8> Weights;
2989 bool HasWeights = HasBranchWeights(SI);
2990 if (HasWeights) {
2991 GetBranchWeights(SI, Weights);
2992 if (Weights.size() == 1 + SI->getNumCases()) {
2993 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2994 getSuccessorIndex()];
2995 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2996 getSuccessorIndex()];
2997 }
2998 }
2999
Frits van Bommel8ae07992011-02-28 09:44:07 +00003000 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003001 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
3002 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003003}
3004
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003005// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003006// (indirectbr (select cond, blockaddress(@fn, BlockA),
3007// blockaddress(@fn, BlockB)))
3008// with
3009// (br cond, BlockA, BlockB).
3010static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3011 // Check that both operands of the select are block addresses.
3012 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3013 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3014 if (!TBA || !FBA)
3015 return false;
3016
3017 // Extract the actual blocks.
3018 BasicBlock *TrueBB = TBA->getBasicBlock();
3019 BasicBlock *FalseBB = FBA->getBasicBlock();
3020
Frits van Bommel8e158492011-01-11 12:52:11 +00003021 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003022 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3023 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003024}
3025
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003026/// This is called when we find an icmp instruction
3027/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003028/// block that ends with an uncond branch. We are looking for a very specific
3029/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3030/// this case, we merge the first two "or's of icmp" into a switch, but then the
3031/// default value goes to an uncond block with a seteq in it, we get something
3032/// like:
3033///
3034/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3035/// DEFAULT:
3036/// %tmp = icmp eq i8 %A, 92
3037/// br label %end
3038/// end:
3039/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003040///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003041/// We prefer to split the edge to 'end' so that there is a true/false entry to
3042/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003043static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003044 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3045 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3046 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003047 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003048
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003049 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3050 // complex.
3051 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3052
3053 Value *V = ICI->getOperand(0);
3054 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003055
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003056 // The pattern we're looking for is where our only predecessor is a switch on
3057 // 'V' and this block is the default case for the switch. In this case we can
3058 // fold the compared value into the switch to simplify things.
3059 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00003060 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003061
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003062 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3063 if (SI->getCondition() != V)
3064 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003065
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003066 // If BB is reachable on a non-default case, then we simply know the value of
3067 // V in this block. Substitute it and constant fold the icmp instruction
3068 // away.
3069 if (SI->getDefaultDest() != BB) {
3070 ConstantInt *VVal = SI->findCaseDest(BB);
3071 assert(VVal && "Should have a unique destination value");
3072 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003073
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003074 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003075 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003076 ICI->eraseFromParent();
3077 }
3078 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003079 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003080 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003081
Chris Lattner62cc76e2010-12-13 03:43:57 +00003082 // Ok, the block is reachable from the default dest. If the constant we're
3083 // comparing exists in one of the other edges, then we can constant fold ICI
3084 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003085 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003086 Value *V;
3087 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3088 V = ConstantInt::getFalse(BB->getContext());
3089 else
3090 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003091
Chris Lattner62cc76e2010-12-13 03:43:57 +00003092 ICI->replaceAllUsesWith(V);
3093 ICI->eraseFromParent();
3094 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003095 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003096 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003097
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003098 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3099 // the block.
3100 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003101 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003102 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003103 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3104 return false;
3105
3106 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3107 // true in the PHI.
3108 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3109 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3110
3111 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3112 std::swap(DefaultCst, NewCst);
3113
3114 // Replace ICI (which is used by the PHI for the default value) with true or
3115 // false depending on if it is EQ or NE.
3116 ICI->replaceAllUsesWith(DefaultCst);
3117 ICI->eraseFromParent();
3118
3119 // Okay, the switch goes to this block on a default value. Add an edge from
3120 // the switch to the merge point on the compared value.
3121 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3122 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003123 SmallVector<uint64_t, 8> Weights;
3124 bool HasWeights = HasBranchWeights(SI);
3125 if (HasWeights) {
3126 GetBranchWeights(SI, Weights);
3127 if (Weights.size() == 1 + SI->getNumCases()) {
3128 // Split weight for default case to case for "Cst".
3129 Weights[0] = (Weights[0]+1) >> 1;
3130 Weights.push_back(Weights[0]);
3131
3132 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3133 SI->setMetadata(LLVMContext::MD_prof,
3134 MDBuilder(SI->getContext()).
3135 createBranchWeights(MDWeights));
3136 }
3137 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003138 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003139
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003140 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003141 Builder.SetInsertPoint(NewBB);
3142 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3143 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003144 PHIUse->addIncoming(NewCst, NewBB);
3145 return true;
3146}
3147
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003148/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003149/// Check to see if it is branching on an or/and chain of icmp instructions, and
3150/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003151static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3152 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003153 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00003154 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003155
Chris Lattnera69c4432010-12-13 05:03:41 +00003156 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3157 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3158 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003159
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003160 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003161 ConstantComparesGatherer ConstantCompare(Cond, DL);
3162 // Unpack the result
3163 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3164 Value *CompVal = ConstantCompare.CompValue;
3165 unsigned UsedICmps = ConstantCompare.UsedICmps;
3166 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003167
Chris Lattnera69c4432010-12-13 05:03:41 +00003168 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00003169 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003170
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003171 // Avoid turning single icmps into a switch.
3172 if (UsedICmps <= 1)
3173 return false;
3174
Mehdi Aminiffd01002014-11-20 22:40:25 +00003175 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3176
Chris Lattnera69c4432010-12-13 05:03:41 +00003177 // There might be duplicate constants in the list, which the switch
3178 // instruction can't handle, remove them now.
3179 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3180 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003181
Chris Lattnera69c4432010-12-13 05:03:41 +00003182 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003183 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003184 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003185
Andrew Trick3051aa12012-08-29 21:46:38 +00003186 // TODO: Preserve branch weight metadata, similarly to how
3187 // FoldValueComparisonIntoPredecessors preserves it.
3188
Chris Lattnera69c4432010-12-13 05:03:41 +00003189 // Figure out which block is which destination.
3190 BasicBlock *DefaultBB = BI->getSuccessor(1);
3191 BasicBlock *EdgeBB = BI->getSuccessor(0);
3192 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003193
Chris Lattnera69c4432010-12-13 05:03:41 +00003194 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003195
Chris Lattnerd7beca32010-12-14 06:17:25 +00003196 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003197 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003198
Chris Lattnera69c4432010-12-13 05:03:41 +00003199 // If there are any extra values that couldn't be folded into the switch
3200 // then we evaluate them with an explicit branch first. Split the block
3201 // right before the condbr to handle it.
3202 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003203 BasicBlock *NewBB =
3204 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003205 // Remove the uncond branch added to the old block.
3206 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003207 Builder.SetInsertPoint(OldTI);
3208
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003209 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003210 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003211 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003212 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003213
Chris Lattnera69c4432010-12-13 05:03:41 +00003214 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003215
Chris Lattnercb570f82010-12-13 05:34:18 +00003216 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3217 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003218 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003219
Chris Lattnerd7beca32010-12-14 06:17:25 +00003220 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3221 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003222 BB = NewBB;
3223 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003224
3225 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003226 // Convert pointer to int before we switch.
3227 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003228 CompVal = Builder.CreatePtrToInt(
3229 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003230 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003231
Chris Lattnera69c4432010-12-13 05:03:41 +00003232 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003233 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003234
Chris Lattnera69c4432010-12-13 05:03:41 +00003235 // Add all of the 'cases' to the switch instruction.
3236 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3237 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003238
Chris Lattnera69c4432010-12-13 05:03:41 +00003239 // We added edges from PI to the EdgeBB. As such, if there were any
3240 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3241 // the number of edges added.
3242 for (BasicBlock::iterator BBI = EdgeBB->begin();
3243 isa<PHINode>(BBI); ++BBI) {
3244 PHINode *PN = cast<PHINode>(BBI);
3245 Value *InVal = PN->getIncomingValueForBlock(BB);
3246 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3247 PN->addIncoming(InVal, BB);
3248 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003249
Chris Lattnera69c4432010-12-13 05:03:41 +00003250 // Erase the old branch instruction.
3251 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003252
Chris Lattnerd7beca32010-12-14 06:17:25 +00003253 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003254 return true;
3255}
3256
Duncan Sands29192d02011-09-05 12:57:57 +00003257bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003258 if (isa<PHINode>(RI->getValue()))
3259 return SimplifyCommonResume(RI);
3260 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3261 RI->getValue() == RI->getParent()->getFirstNonPHI())
3262 // The resume must unwind the exception that caused control to branch here.
3263 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003264
3265 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003266}
3267
3268// Simplify resume that is shared by several landing pads (phi of landing pad).
3269bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3270 BasicBlock *BB = RI->getParent();
3271
3272 // Check that there are no other instructions except for debug intrinsics
3273 // between the phi of landing pads (RI->getValue()) and resume instruction.
3274 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3275 E = RI->getIterator();
3276 while (++I != E)
3277 if (!isa<DbgInfoIntrinsic>(I))
3278 return false;
3279
3280 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3281 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3282
3283 // Check incoming blocks to see if any of them are trivial.
3284 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues();
3285 Idx != End; Idx++) {
3286 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3287 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3288
3289 // If the block has other successors, we can not delete it because
3290 // it has other dependents.
3291 if (IncomingBB->getUniqueSuccessor() != BB)
3292 continue;
3293
3294 auto *LandingPad =
3295 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3296 // Not the landing pad that caused the control to branch here.
3297 if (IncomingValue != LandingPad)
3298 continue;
3299
3300 bool isTrivial = true;
3301
3302 I = IncomingBB->getFirstNonPHI()->getIterator();
3303 E = IncomingBB->getTerminator()->getIterator();
3304 while (++I != E)
3305 if (!isa<DbgInfoIntrinsic>(I)) {
3306 isTrivial = false;
3307 break;
3308 }
3309
3310 if (isTrivial)
3311 TrivialUnwindBlocks.insert(IncomingBB);
3312 }
3313
3314 // If no trivial unwind blocks, don't do any simplifications.
3315 if (TrivialUnwindBlocks.empty()) return false;
3316
3317 // Turn all invokes that unwind here into calls.
3318 for (auto *TrivialBB : TrivialUnwindBlocks) {
3319 // Blocks that will be simplified should be removed from the phi node.
3320 // Note there could be multiple edges to the resume block, and we need
3321 // to remove them all.
3322 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3323 BB->removePredecessor(TrivialBB, true);
3324
3325 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3326 PI != PE;) {
3327 BasicBlock *Pred = *PI++;
3328 removeUnwindEdge(Pred);
3329 }
3330
3331 // In each SimplifyCFG run, only the current processed block can be erased.
3332 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3333 // of erasing TrivialBB, we only remove the branch to the common resume
3334 // block so that we can later erase the resume block since it has no
3335 // predecessors.
3336 TrivialBB->getTerminator()->eraseFromParent();
3337 new UnreachableInst(RI->getContext(), TrivialBB);
3338 }
3339
3340 // Delete the resume block if all its predecessors have been removed.
3341 if (pred_empty(BB))
3342 BB->eraseFromParent();
3343
3344 return !TrivialUnwindBlocks.empty();
3345}
3346
3347// Simplify resume that is only used by a single (non-phi) landing pad.
3348bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003349 BasicBlock *BB = RI->getParent();
3350 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003351 assert (RI->getValue() == LPInst &&
3352 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003353
Chen Li7009cd32015-10-23 21:13:01 +00003354 // Check that there are no other instructions except for debug intrinsics.
3355 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003356 while (++I != E)
3357 if (!isa<DbgInfoIntrinsic>(I))
3358 return false;
3359
Chen Lic6e28782015-10-22 20:48:38 +00003360 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003361 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3362 BasicBlock *Pred = *PI++;
3363 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003364 }
3365
Chen Li7009cd32015-10-23 21:13:01 +00003366 // The landingpad is now unreachable. Zap it.
3367 BB->eraseFromParent();
Hyojin Sung4673f102016-03-29 04:08:57 +00003368 if (LoopHeaders) LoopHeaders->erase(BB);
Chen Li7009cd32015-10-23 21:13:01 +00003369 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003370}
3371
David Majnemer1efa23d2016-02-20 01:07:45 +00003372static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003373 // If this is a trivial cleanup pad that executes no instructions, it can be
3374 // eliminated. If the cleanup pad continues to the caller, any predecessor
3375 // that is an EH pad will be updated to continue to the caller and any
3376 // predecessor that terminates with an invoke instruction will have its invoke
3377 // instruction converted to a call instruction. If the cleanup pad being
3378 // simplified does not continue to the caller, each predecessor will be
3379 // updated to continue to the unwind destination of the cleanup pad being
3380 // simplified.
3381 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003382 CleanupPadInst *CPInst = RI->getCleanupPad();
3383 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003384 // This isn't an empty cleanup.
3385 return false;
3386
3387 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003388 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003389 while (++I != E)
3390 if (!isa<DbgInfoIntrinsic>(I))
3391 return false;
3392
David Majnemer8a1c45d2015-12-12 05:38:55 +00003393 // If the cleanup return we are simplifying unwinds to the caller, this will
3394 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003395 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003396 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003397
3398 // We're about to remove BB from the control flow. Before we do, sink any
3399 // PHINodes into the unwind destination. Doing this before changing the
3400 // control flow avoids some potentially slow checks, since we can currently
3401 // be certain that UnwindDest and BB have no common predecessors (since they
3402 // are both EH pads).
3403 if (UnwindDest) {
3404 // First, go through the PHI nodes in UnwindDest and update any nodes that
3405 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003406 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003407 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003408 I != IE; ++I) {
3409 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003410
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003411 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003412 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003413 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003414 // This PHI node has an incoming value that corresponds to a control
3415 // path through the cleanup pad we are removing. If the incoming
3416 // value is in the cleanup pad, it must be a PHINode (because we
3417 // verified above that the block is otherwise empty). Otherwise, the
3418 // value is either a constant or a value that dominates the cleanup
3419 // pad being removed.
3420 //
3421 // Because BB and UnwindDest are both EH pads, all of their
3422 // predecessors must unwind to these blocks, and since no instruction
3423 // can have multiple unwind destinations, there will be no overlap in
3424 // incoming blocks between SrcPN and DestPN.
3425 Value *SrcVal = DestPN->getIncomingValue(Idx);
3426 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3427
3428 // Remove the entry for the block we are deleting.
3429 DestPN->removeIncomingValue(Idx, false);
3430
3431 if (SrcPN && SrcPN->getParent() == BB) {
3432 // If the incoming value was a PHI node in the cleanup pad we are
3433 // removing, we need to merge that PHI node's incoming values into
3434 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003435 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003436 SrcIdx != SrcE; ++SrcIdx) {
3437 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3438 SrcPN->getIncomingBlock(SrcIdx));
3439 }
3440 } else {
3441 // Otherwise, the incoming value came from above BB and
3442 // so we can just reuse it. We must associate all of BB's
3443 // predecessors with this value.
3444 for (auto *pred : predecessors(BB)) {
3445 DestPN->addIncoming(SrcVal, pred);
3446 }
3447 }
3448 }
3449
3450 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003451 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003452 for (BasicBlock::iterator I = BB->begin(),
3453 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003454 I != IE;) {
3455 // The iterator must be incremented here because the instructions are
3456 // being moved to another block.
3457 PHINode *PN = cast<PHINode>(I++);
3458 if (PN->use_empty())
3459 // If the PHI node has no uses, just leave it. It will be erased
3460 // when we erase BB below.
3461 continue;
3462
3463 // Otherwise, sink this PHI node into UnwindDest.
3464 // Any predecessors to UnwindDest which are not already represented
3465 // must be back edges which inherit the value from the path through
3466 // BB. In this case, the PHI value must reference itself.
3467 for (auto *pred : predecessors(UnwindDest))
3468 if (pred != BB)
3469 PN->addIncoming(PN, pred);
3470 PN->moveBefore(InsertPt);
3471 }
3472 }
3473
3474 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3475 // The iterator must be updated here because we are removing this pred.
3476 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003477 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003478 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003479 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003480 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003481 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003482 }
3483 }
3484
3485 // The cleanup pad is now unreachable. Zap it.
3486 BB->eraseFromParent();
3487 return true;
3488}
3489
David Majnemer1efa23d2016-02-20 01:07:45 +00003490// Try to merge two cleanuppads together.
3491static bool mergeCleanupPad(CleanupReturnInst *RI) {
3492 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3493 // with.
3494 BasicBlock *UnwindDest = RI->getUnwindDest();
3495 if (!UnwindDest)
3496 return false;
3497
3498 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3499 // be safe to merge without code duplication.
3500 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3501 return false;
3502
3503 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3504 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3505 if (!SuccessorCleanupPad)
3506 return false;
3507
3508 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3509 // Replace any uses of the successor cleanupad with the predecessor pad
3510 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3511 // funclet bundle operands.
3512 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3513 // Remove the old cleanuppad.
3514 SuccessorCleanupPad->eraseFromParent();
3515 // Now, we simply replace the cleanupret with a branch to the unwind
3516 // destination.
3517 BranchInst::Create(UnwindDest, RI->getParent());
3518 RI->eraseFromParent();
3519
3520 return true;
3521}
3522
3523bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003524 // It is possible to transiantly have an undef cleanuppad operand because we
3525 // have deleted some, but not all, dead blocks.
3526 // Eventually, this block will be deleted.
3527 if (isa<UndefValue>(RI->getOperand(0)))
3528 return false;
3529
David Majnemer1efa23d2016-02-20 01:07:45 +00003530 if (removeEmptyCleanup(RI))
3531 return true;
3532
3533 if (mergeCleanupPad(RI))
3534 return true;
3535
3536 return false;
3537}
3538
Devang Pateldd14e0f2011-05-18 21:33:11 +00003539bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003540 BasicBlock *BB = RI->getParent();
3541 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003542
Chris Lattner25c3af32010-12-13 06:25:44 +00003543 // Find predecessors that end with branches.
3544 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3545 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003546 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3547 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003548 TerminatorInst *PTI = P->getTerminator();
3549 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3550 if (BI->isUnconditional())
3551 UncondBranchPreds.push_back(P);
3552 else
3553 CondBranchPreds.push_back(BI);
3554 }
3555 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003556
Chris Lattner25c3af32010-12-13 06:25:44 +00003557 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003558 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003559 while (!UncondBranchPreds.empty()) {
3560 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3561 DEBUG(dbgs() << "FOLDING: " << *BB
3562 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003563 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003564 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003565
Chris Lattner25c3af32010-12-13 06:25:44 +00003566 // If we eliminated all predecessors of the block, delete the block now.
Hyojin Sung4673f102016-03-29 04:08:57 +00003567 if (pred_empty(BB)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003568 // We know there are no successors, so just nuke the block.
3569 BB->eraseFromParent();
Hyojin Sung4673f102016-03-29 04:08:57 +00003570 if (LoopHeaders) LoopHeaders->erase(BB);
3571 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003572
Chris Lattner25c3af32010-12-13 06:25:44 +00003573 return true;
3574 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003575
Chris Lattner25c3af32010-12-13 06:25:44 +00003576 // Check out all of the conditional branches going to this return
3577 // instruction. If any of them just select between returns, change the
3578 // branch itself into a select/return pair.
3579 while (!CondBranchPreds.empty()) {
3580 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003581
Chris Lattner25c3af32010-12-13 06:25:44 +00003582 // Check to see if the non-BB successor is also a return block.
3583 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3584 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003585 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003586 return true;
3587 }
3588 return false;
3589}
3590
Chris Lattner25c3af32010-12-13 06:25:44 +00003591bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3592 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003593
Chris Lattner25c3af32010-12-13 06:25:44 +00003594 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003595
Chris Lattner25c3af32010-12-13 06:25:44 +00003596 // If there are any instructions immediately before the unreachable that can
3597 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003598 while (UI->getIterator() != BB->begin()) {
3599 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003600 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003601 // Do not delete instructions that can have side effects which might cause
3602 // the unreachable to not be reachable; specifically, calls and volatile
3603 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003604 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003605
3606 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003607 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003608 if (SI->isVolatile())
3609 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003610 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003611 if (LI->isVolatile())
3612 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003613 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003614 if (RMWI->isVolatile())
3615 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003616 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003617 if (CXI->isVolatile())
3618 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003619 } else if (isa<CatchPadInst>(BBI)) {
3620 // A catchpad may invoke exception object constructors and such, which
3621 // in some languages can be arbitrary code, so be conservative by
3622 // default.
3623 // For CoreCLR, it just involves a type test, so can be removed.
3624 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3625 EHPersonality::CoreCLR)
3626 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003627 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3628 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003629 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003630 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003631 // Note that deleting LandingPad's here is in fact okay, although it
3632 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3633 // all the predecessors of this block will be the unwind edges of Invokes,
3634 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003635 }
3636
Eli Friedmanaac35b32011-03-09 00:48:33 +00003637 // Delete this instruction (any uses are guaranteed to be dead)
3638 if (!BBI->use_empty())
3639 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003640 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003641 Changed = true;
3642 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003643
Chris Lattner25c3af32010-12-13 06:25:44 +00003644 // If the unreachable instruction is the first in the block, take a gander
3645 // at all of the predecessors of this instruction, and simplify them.
3646 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003647
Chris Lattner25c3af32010-12-13 06:25:44 +00003648 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3649 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3650 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003651 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003652 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003653 if (BI->isUnconditional()) {
3654 if (BI->getSuccessor(0) == BB) {
3655 new UnreachableInst(TI->getContext(), TI);
3656 TI->eraseFromParent();
3657 Changed = true;
3658 }
3659 } else {
3660 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003661 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003662 EraseTerminatorInstAndDCECond(BI);
3663 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003664 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003665 EraseTerminatorInstAndDCECond(BI);
3666 Changed = true;
3667 }
3668 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003669 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003670 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003671 i != e; ++i)
3672 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003673 BB->removePredecessor(SI->getParent());
3674 SI->removeCase(i);
3675 --i; --e;
3676 Changed = true;
3677 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003678 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3679 if (II->getUnwindDest() == BB) {
3680 removeUnwindEdge(TI->getParent());
3681 Changed = true;
3682 }
3683 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3684 if (CSI->getUnwindDest() == BB) {
3685 removeUnwindEdge(TI->getParent());
3686 Changed = true;
3687 continue;
3688 }
3689
3690 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3691 E = CSI->handler_end();
3692 I != E; ++I) {
3693 if (*I == BB) {
3694 CSI->removeHandler(I);
3695 --I;
3696 --E;
3697 Changed = true;
3698 }
3699 }
3700 if (CSI->getNumHandlers() == 0) {
3701 BasicBlock *CatchSwitchBB = CSI->getParent();
3702 if (CSI->hasUnwindDest()) {
3703 // Redirect preds to the unwind dest
3704 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3705 } else {
3706 // Rewrite all preds to unwind to caller (or from invoke to call).
3707 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3708 for (BasicBlock *EHPred : EHPreds)
3709 removeUnwindEdge(EHPred);
3710 }
3711 // The catchswitch is no longer reachable.
3712 new UnreachableInst(CSI->getContext(), CSI);
3713 CSI->eraseFromParent();
3714 Changed = true;
3715 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003716 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003717 new UnreachableInst(TI->getContext(), TI);
3718 TI->eraseFromParent();
3719 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003720 }
3721 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003722
Chris Lattner25c3af32010-12-13 06:25:44 +00003723 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003724 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003725 BB != &BB->getParent()->getEntryBlock()) {
3726 // We know there are no successors, so just nuke the block.
3727 BB->eraseFromParent();
Hyojin Sung4673f102016-03-29 04:08:57 +00003728 if (LoopHeaders) LoopHeaders->erase(BB);
Chris Lattner25c3af32010-12-13 06:25:44 +00003729 return true;
3730 }
3731
3732 return Changed;
3733}
3734
Hans Wennborg68000082015-01-26 19:52:32 +00003735static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3736 assert(Cases.size() >= 1);
3737
3738 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3739 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3740 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3741 return false;
3742 }
3743 return true;
3744}
3745
3746/// Turn a switch with two reachable destinations into an integer range
3747/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003748static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003749 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003750
Hans Wennborg68000082015-01-26 19:52:32 +00003751 bool HasDefault =
3752 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003753
Hans Wennborg68000082015-01-26 19:52:32 +00003754 // Partition the cases into two sets with different destinations.
3755 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3756 BasicBlock *DestB = nullptr;
3757 SmallVector <ConstantInt *, 16> CasesA;
3758 SmallVector <ConstantInt *, 16> CasesB;
3759
3760 for (SwitchInst::CaseIt I : SI->cases()) {
3761 BasicBlock *Dest = I.getCaseSuccessor();
3762 if (!DestA) DestA = Dest;
3763 if (Dest == DestA) {
3764 CasesA.push_back(I.getCaseValue());
3765 continue;
3766 }
3767 if (!DestB) DestB = Dest;
3768 if (Dest == DestB) {
3769 CasesB.push_back(I.getCaseValue());
3770 continue;
3771 }
3772 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003773 }
3774
Hans Wennborg68000082015-01-26 19:52:32 +00003775 assert(DestA && DestB && "Single-destination switch should have been folded.");
3776 assert(DestA != DestB);
3777 assert(DestB != SI->getDefaultDest());
3778 assert(!CasesB.empty() && "There must be non-default cases.");
3779 assert(!CasesA.empty() || HasDefault);
3780
3781 // Figure out if one of the sets of cases form a contiguous range.
3782 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3783 BasicBlock *ContiguousDest = nullptr;
3784 BasicBlock *OtherDest = nullptr;
3785 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3786 ContiguousCases = &CasesA;
3787 ContiguousDest = DestA;
3788 OtherDest = DestB;
3789 } else if (CasesAreContiguous(CasesB)) {
3790 ContiguousCases = &CasesB;
3791 ContiguousDest = DestB;
3792 OtherDest = DestA;
3793 } else
3794 return false;
3795
3796 // Start building the compare and branch.
3797
3798 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3799 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003800
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003801 Value *Sub = SI->getCondition();
3802 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003803 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3804
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003805 Value *Cmp;
3806 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003807 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003808 Cmp = ConstantInt::getTrue(SI->getContext());
3809 else
3810 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003811 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003812
Manman Ren56575552012-09-18 00:47:33 +00003813 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003814 if (HasBranchWeights(SI)) {
3815 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003816 GetBranchWeights(SI, Weights);
3817 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003818 uint64_t TrueWeight = 0;
3819 uint64_t FalseWeight = 0;
3820 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3821 if (SI->getSuccessor(I) == ContiguousDest)
3822 TrueWeight += Weights[I];
3823 else
3824 FalseWeight += Weights[I];
3825 }
3826 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3827 TrueWeight /= 2;
3828 FalseWeight /= 2;
3829 }
Manman Ren56575552012-09-18 00:47:33 +00003830 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003831 MDBuilder(SI->getContext()).createBranchWeights(
3832 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003833 }
3834 }
3835
Hans Wennborg68000082015-01-26 19:52:32 +00003836 // Prune obsolete incoming values off the successors' PHI nodes.
3837 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3838 unsigned PreviousEdges = ContiguousCases->size();
3839 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3840 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003841 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3842 }
Hans Wennborg68000082015-01-26 19:52:32 +00003843 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3844 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3845 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3846 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3847 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3848 }
3849
3850 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003851 SI->eraseFromParent();
3852
3853 return true;
3854}
Chris Lattner25c3af32010-12-13 06:25:44 +00003855
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003856/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003857/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003858static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3859 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003860 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003861 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003862 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003863 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003864
3865 // Gather dead cases.
3866 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003867 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003868 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3869 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3870 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003871 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003872 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003873 }
3874 }
3875
Philip Reames98a2dab2015-08-26 23:56:46 +00003876 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003877 // default destination becomes dead and we can remove it. If we know some
3878 // of the bits in the value, we can use that to more precisely compute the
3879 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003880 bool HasDefault =
3881 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003882 const unsigned NumUnknownBits = Bits -
3883 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003884 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003885 if (HasDefault && DeadCases.empty() &&
3886 NumUnknownBits < 64 /* avoid overflow */ &&
3887 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003888 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3889 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3890 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003891 SI->setDefaultDest(&*NewDefault);
3892 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003893 auto *OldTI = NewDefault->getTerminator();
3894 new UnreachableInst(SI->getContext(), OldTI);
3895 EraseTerminatorInstAndDCECond(OldTI);
3896 return true;
3897 }
3898
Manman Ren56575552012-09-18 00:47:33 +00003899 SmallVector<uint64_t, 8> Weights;
3900 bool HasWeight = HasBranchWeights(SI);
3901 if (HasWeight) {
3902 GetBranchWeights(SI, Weights);
3903 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3904 }
3905
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003906 // Remove dead cases from the switch.
3907 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003908 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003909 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003910 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003911 if (HasWeight) {
3912 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3913 Weights.pop_back();
3914 }
3915
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003916 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003917 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003918 SI->removeCase(Case);
3919 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003920 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003921 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3922 SI->setMetadata(LLVMContext::MD_prof,
3923 MDBuilder(SI->getParent()->getContext()).
3924 createBranchWeights(MDWeights));
3925 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003926
3927 return !DeadCases.empty();
3928}
3929
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003930/// If BB would be eligible for simplification by
3931/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003932/// by an unconditional branch), look at the phi node for BB in the successor
3933/// block and see if the incoming value is equal to CaseValue. If so, return
3934/// the phi node, and set PhiIndex to BB's index in the phi node.
3935static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3936 BasicBlock *BB,
3937 int *PhiIndex) {
3938 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003939 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003940 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003941 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003942
3943 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3944 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003945 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003946
3947 BasicBlock *Succ = Branch->getSuccessor(0);
3948
3949 BasicBlock::iterator I = Succ->begin();
3950 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3951 int Idx = PHI->getBasicBlockIndex(BB);
3952 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3953
3954 Value *InValue = PHI->getIncomingValue(Idx);
3955 if (InValue != CaseValue) continue;
3956
3957 *PhiIndex = Idx;
3958 return PHI;
3959 }
3960
Craig Topperf40110f2014-04-25 05:29:35 +00003961 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003962}
3963
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003964/// Try to forward the condition of a switch instruction to a phi node
3965/// dominated by the switch, if that would mean that some of the destination
3966/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003967/// Returns true if a change is made.
3968static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3969 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3970 ForwardingNodesMap ForwardingNodes;
3971
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003972 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003973 ConstantInt *CaseValue = I.getCaseValue();
3974 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003975
3976 int PhiIndex;
3977 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3978 &PhiIndex);
3979 if (!PHI) continue;
3980
3981 ForwardingNodes[PHI].push_back(PhiIndex);
3982 }
3983
3984 bool Changed = false;
3985
3986 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3987 E = ForwardingNodes.end(); I != E; ++I) {
3988 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003989 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003990
3991 if (Indexes.size() < 2) continue;
3992
3993 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3994 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3995 Changed = true;
3996 }
3997
3998 return Changed;
3999}
4000
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004001/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004002/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00004003static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00004004 if (C->isThreadDependent())
4005 return false;
4006 if (C->isDLLImportDependent())
4007 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004008
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004009 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
4010 return CE->isGEPWithNoNotionalOverIndexing();
4011
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004012 return isa<ConstantFP>(C) ||
4013 isa<ConstantInt>(C) ||
4014 isa<ConstantPointerNull>(C) ||
4015 isa<GlobalValue>(C) ||
4016 isa<UndefValue>(C);
4017}
4018
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004019/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004020/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00004021static Constant *LookupConstant(Value *V,
4022 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
4023 if (Constant *C = dyn_cast<Constant>(V))
4024 return C;
4025 return ConstantPool.lookup(V);
4026}
4027
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004028/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004029/// simple instructions such as binary operations where both operands are
4030/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004031/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004032static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004033ConstantFold(Instruction *I, const DataLayout &DL,
4034 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004035 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004036 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4037 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004038 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004039 if (A->isAllOnesValue())
4040 return LookupConstant(Select->getTrueValue(), ConstantPool);
4041 if (A->isNullValue())
4042 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004043 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004044 }
4045
Benjamin Kramer7c302602013-11-12 12:24:36 +00004046 SmallVector<Constant *, 4> COps;
4047 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4048 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4049 COps.push_back(A);
4050 else
Craig Topperf40110f2014-04-25 05:29:35 +00004051 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004052 }
4053
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004054 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004055 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4056 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004057 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004058
Manuel Jacobe9024592016-01-21 06:33:22 +00004059 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004060}
4061
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004062/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004063/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004064/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004065/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004066static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004067GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004068 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004069 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4070 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004071 // The block from which we enter the common destination.
4072 BasicBlock *Pred = SI->getParent();
4073
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004074 // If CaseDest is empty except for some side-effect free instructions through
4075 // which we can constant-propagate the CaseVal, continue to its successor.
4076 SmallDenseMap<Value*, Constant*> ConstantPool;
4077 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4078 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4079 ++I) {
4080 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4081 // If the terminator is a simple branch, continue to the next block.
4082 if (T->getNumSuccessors() != 1)
4083 return false;
4084 Pred = CaseDest;
4085 CaseDest = T->getSuccessor(0);
4086 } else if (isa<DbgInfoIntrinsic>(I)) {
4087 // Skip debug intrinsic.
4088 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004089 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004090 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004091
4092 // If the instruction has uses outside this block or a phi node slot for
4093 // the block, it is not safe to bypass the instruction since it would then
4094 // no longer dominate all its uses.
4095 for (auto &Use : I->uses()) {
4096 User *User = Use.getUser();
4097 if (Instruction *I = dyn_cast<Instruction>(User))
4098 if (I->getParent() == CaseDest)
4099 continue;
4100 if (PHINode *Phi = dyn_cast<PHINode>(User))
4101 if (Phi->getIncomingBlock(Use) == CaseDest)
4102 continue;
4103 return false;
4104 }
4105
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004106 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004107 } else {
4108 break;
4109 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004110 }
4111
4112 // If we did not have a CommonDest before, use the current one.
4113 if (!*CommonDest)
4114 *CommonDest = CaseDest;
4115 // If the destination isn't the common one, abort.
4116 if (CaseDest != *CommonDest)
4117 return false;
4118
4119 // Get the values for this case from phi nodes in the destination block.
4120 BasicBlock::iterator I = (*CommonDest)->begin();
4121 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4122 int Idx = PHI->getBasicBlockIndex(Pred);
4123 if (Idx == -1)
4124 continue;
4125
Hans Wennborg09acdb92012-10-31 15:14:39 +00004126 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
4127 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004128 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004129 return false;
4130
4131 // Be conservative about which kinds of constants we support.
4132 if (!ValidLookupTableConstant(ConstVal))
4133 return false;
4134
4135 Res.push_back(std::make_pair(PHI, ConstVal));
4136 }
4137
Hans Wennborgac114a32014-01-12 00:44:41 +00004138 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004139}
4140
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004141// Helper function used to add CaseVal to the list of cases that generate
4142// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004143static void MapCaseToResult(ConstantInt *CaseVal,
4144 SwitchCaseResultVectorTy &UniqueResults,
4145 Constant *Result) {
4146 for (auto &I : UniqueResults) {
4147 if (I.first == Result) {
4148 I.second.push_back(CaseVal);
4149 return;
4150 }
4151 }
4152 UniqueResults.push_back(std::make_pair(Result,
4153 SmallVector<ConstantInt*, 4>(1, CaseVal)));
4154}
4155
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004156// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004157// results for the PHI node of the common destination block for a switch
4158// instruction. Returns false if multiple PHI nodes have been found or if
4159// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004160static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4161 BasicBlock *&CommonDest,
4162 SwitchCaseResultVectorTy &UniqueResults,
4163 Constant *&DefaultResult,
4164 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004165 for (auto &I : SI->cases()) {
4166 ConstantInt *CaseVal = I.getCaseValue();
4167
4168 // Resulting value at phi nodes for this case value.
4169 SwitchCaseResultsTy Results;
4170 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4171 DL))
4172 return false;
4173
4174 // Only one value per case is permitted
4175 if (Results.size() > 1)
4176 return false;
4177 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4178
4179 // Check the PHI consistency.
4180 if (!PHI)
4181 PHI = Results[0].first;
4182 else if (PHI != Results[0].first)
4183 return false;
4184 }
4185 // Find the default result value.
4186 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4187 BasicBlock *DefaultDest = SI->getDefaultDest();
4188 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4189 DL);
4190 // If the default value is not found abort unless the default destination
4191 // is unreachable.
4192 DefaultResult =
4193 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4194 if ((!DefaultResult &&
4195 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4196 return false;
4197
4198 return true;
4199}
4200
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004201// Helper function that checks if it is possible to transform a switch with only
4202// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004203// Example:
4204// switch (a) {
4205// case 10: %0 = icmp eq i32 %a, 10
4206// return 10; %1 = select i1 %0, i32 10, i32 4
4207// case 20: ----> %2 = icmp eq i32 %a, 20
4208// return 2; %3 = select i1 %2, i32 2, i32 %1
4209// default:
4210// return 4;
4211// }
4212static Value *
4213ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4214 Constant *DefaultResult, Value *Condition,
4215 IRBuilder<> &Builder) {
4216 assert(ResultVector.size() == 2 &&
4217 "We should have exactly two unique results at this point");
4218 // If we are selecting between only two cases transform into a simple
4219 // select or a two-way select if default is possible.
4220 if (ResultVector[0].second.size() == 1 &&
4221 ResultVector[1].second.size() == 1) {
4222 ConstantInt *const FirstCase = ResultVector[0].second[0];
4223 ConstantInt *const SecondCase = ResultVector[1].second[0];
4224
4225 bool DefaultCanTrigger = DefaultResult;
4226 Value *SelectValue = ResultVector[1].first;
4227 if (DefaultCanTrigger) {
4228 Value *const ValueCompare =
4229 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4230 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4231 DefaultResult, "switch.select");
4232 }
4233 Value *const ValueCompare =
4234 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4235 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4236 "switch.select");
4237 }
4238
4239 return nullptr;
4240}
4241
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004242// Helper function to cleanup a switch instruction that has been converted into
4243// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004244static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4245 Value *SelectValue,
4246 IRBuilder<> &Builder) {
4247 BasicBlock *SelectBB = SI->getParent();
4248 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4249 PHI->removeIncomingValue(SelectBB);
4250 PHI->addIncoming(SelectValue, SelectBB);
4251
4252 Builder.CreateBr(PHI->getParent());
4253
4254 // Remove the switch.
4255 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4256 BasicBlock *Succ = SI->getSuccessor(i);
4257
4258 if (Succ == PHI->getParent())
4259 continue;
4260 Succ->removePredecessor(SelectBB);
4261 }
4262 SI->eraseFromParent();
4263}
4264
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004265/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004266/// phi nodes in a common successor block with only two different
4267/// constant values, replace the switch with select.
4268static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004269 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004270 Value *const Cond = SI->getCondition();
4271 PHINode *PHI = nullptr;
4272 BasicBlock *CommonDest = nullptr;
4273 Constant *DefaultResult;
4274 SwitchCaseResultVectorTy UniqueResults;
4275 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004276 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4277 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004278 return false;
4279 // Selects choose between maximum two values.
4280 if (UniqueResults.size() != 2)
4281 return false;
4282 assert(PHI != nullptr && "PHI for value select not found");
4283
4284 Builder.SetInsertPoint(SI);
4285 Value *SelectValue = ConvertTwoCaseSwitch(
4286 UniqueResults,
4287 DefaultResult, Cond, Builder);
4288 if (SelectValue) {
4289 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4290 return true;
4291 }
4292 // The switch couldn't be converted into a select.
4293 return false;
4294}
4295
Hans Wennborg776d7122012-09-26 09:34:53 +00004296namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004297 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00004298 class SwitchLookupTable {
4299 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004300 /// Create a lookup table to use as a switch replacement with the contents
4301 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004302 SwitchLookupTable(
4303 Module &M, uint64_t TableSize, ConstantInt *Offset,
4304 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4305 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004306
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004307 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00004308 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00004309 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004310
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004311 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00004312 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004313 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004314 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004315
Hans Wennborg776d7122012-09-26 09:34:53 +00004316 private:
4317 // Depending on the contents of the table, it can be represented in
4318 // different ways.
4319 enum {
4320 // For tables where each element contains the same value, we just have to
4321 // store that single value and return it for each lookup.
4322 SingleValueKind,
4323
Erik Eckstein105374f2014-11-17 09:13:57 +00004324 // For tables where there is a linear relationship between table index
4325 // and values. We calculate the result with a simple multiplication
4326 // and addition instead of a table lookup.
4327 LinearMapKind,
4328
Hans Wennborg39583b82012-09-26 09:44:49 +00004329 // For small tables with integer elements, we can pack them into a bitmap
4330 // that fits into a target-legal register. Values are retrieved by
4331 // shift and mask operations.
4332 BitMapKind,
4333
Hans Wennborg776d7122012-09-26 09:34:53 +00004334 // The table is stored as an array of values. Values are retrieved by load
4335 // instructions from the table.
4336 ArrayKind
4337 } Kind;
4338
4339 // For SingleValueKind, this is the single value.
4340 Constant *SingleValue;
4341
Hans Wennborg39583b82012-09-26 09:44:49 +00004342 // For BitMapKind, this is the bitmap.
4343 ConstantInt *BitMap;
4344 IntegerType *BitMapElementTy;
4345
Erik Eckstein105374f2014-11-17 09:13:57 +00004346 // For LinearMapKind, these are the constants used to derive the value.
4347 ConstantInt *LinearOffset;
4348 ConstantInt *LinearMultiplier;
4349
Hans Wennborg776d7122012-09-26 09:34:53 +00004350 // For ArrayKind, this is the array.
4351 GlobalVariable *Array;
4352 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004353}
Hans Wennborg776d7122012-09-26 09:34:53 +00004354
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004355SwitchLookupTable::SwitchLookupTable(
4356 Module &M, uint64_t TableSize, ConstantInt *Offset,
4357 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4358 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004359 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004360 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004361 assert(Values.size() && "Can't build lookup table without values!");
4362 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004363
4364 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004365 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004366
Hans Wennborgac114a32014-01-12 00:44:41 +00004367 Type *ValueType = Values.begin()->second->getType();
4368
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004369 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00004370 SmallVector<Constant*, 64> TableContents(TableSize);
4371 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4372 ConstantInt *CaseVal = Values[I].first;
4373 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004374 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004375
Hans Wennborg776d7122012-09-26 09:34:53 +00004376 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4377 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004378 TableContents[Idx] = CaseRes;
4379
Hans Wennborg776d7122012-09-26 09:34:53 +00004380 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004381 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004382 }
4383
4384 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004385 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004386 assert(DefaultValue &&
4387 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004388 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004389 for (uint64_t I = 0; I < TableSize; ++I) {
4390 if (!TableContents[I])
4391 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004392 }
4393
Hans Wennborg776d7122012-09-26 09:34:53 +00004394 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004395 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004396 }
4397
Hans Wennborg776d7122012-09-26 09:34:53 +00004398 // If each element in the table contains the same value, we only need to store
4399 // that single value.
4400 if (SingleValue) {
4401 Kind = SingleValueKind;
4402 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004403 }
4404
Erik Eckstein105374f2014-11-17 09:13:57 +00004405 // Check if we can derive the value with a linear transformation from the
4406 // table index.
4407 if (isa<IntegerType>(ValueType)) {
4408 bool LinearMappingPossible = true;
4409 APInt PrevVal;
4410 APInt DistToPrev;
4411 assert(TableSize >= 2 && "Should be a SingleValue table.");
4412 // Check if there is the same distance between two consecutive values.
4413 for (uint64_t I = 0; I < TableSize; ++I) {
4414 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4415 if (!ConstVal) {
4416 // This is an undef. We could deal with it, but undefs in lookup tables
4417 // are very seldom. It's probably not worth the additional complexity.
4418 LinearMappingPossible = false;
4419 break;
4420 }
4421 APInt Val = ConstVal->getValue();
4422 if (I != 0) {
4423 APInt Dist = Val - PrevVal;
4424 if (I == 1) {
4425 DistToPrev = Dist;
4426 } else if (Dist != DistToPrev) {
4427 LinearMappingPossible = false;
4428 break;
4429 }
4430 }
4431 PrevVal = Val;
4432 }
4433 if (LinearMappingPossible) {
4434 LinearOffset = cast<ConstantInt>(TableContents[0]);
4435 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4436 Kind = LinearMapKind;
4437 ++NumLinearMaps;
4438 return;
4439 }
4440 }
4441
Hans Wennborg39583b82012-09-26 09:44:49 +00004442 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004443 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004444 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004445 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4446 for (uint64_t I = TableSize; I > 0; --I) {
4447 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004448 // Insert values into the bitmap. Undef values are set to zero.
4449 if (!isa<UndefValue>(TableContents[I - 1])) {
4450 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4451 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4452 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004453 }
4454 BitMap = ConstantInt::get(M.getContext(), TableInt);
4455 BitMapElementTy = IT;
4456 Kind = BitMapKind;
4457 ++NumBitMaps;
4458 return;
4459 }
4460
Hans Wennborg776d7122012-09-26 09:34:53 +00004461 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004462 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004463 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4464
Hans Wennborg776d7122012-09-26 09:34:53 +00004465 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4466 GlobalVariable::PrivateLinkage,
4467 Initializer,
4468 "switch.table");
4469 Array->setUnnamedAddr(true);
4470 Kind = ArrayKind;
4471}
4472
Manman Ren4d189fb2014-07-24 21:13:20 +00004473Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004474 switch (Kind) {
4475 case SingleValueKind:
4476 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004477 case LinearMapKind: {
4478 // Derive the result value from the input value.
4479 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4480 false, "switch.idx.cast");
4481 if (!LinearMultiplier->isOne())
4482 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4483 if (!LinearOffset->isZero())
4484 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4485 return Result;
4486 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004487 case BitMapKind: {
4488 // Type of the bitmap (e.g. i59).
4489 IntegerType *MapTy = BitMap->getType();
4490
4491 // Cast Index to the same type as the bitmap.
4492 // Note: The Index is <= the number of elements in the table, so
4493 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004494 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004495
4496 // Multiply the shift amount by the element width.
4497 ShiftAmt = Builder.CreateMul(ShiftAmt,
4498 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4499 "switch.shiftamt");
4500
4501 // Shift down.
4502 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4503 "switch.downshift");
4504 // Mask off.
4505 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4506 "switch.masked");
4507 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004508 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004509 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004510 IntegerType *IT = cast<IntegerType>(Index->getType());
4511 uint64_t TableSize = Array->getInitializer()->getType()
4512 ->getArrayNumElements();
4513 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4514 Index = Builder.CreateZExt(Index,
4515 IntegerType::get(IT->getContext(),
4516 IT->getBitWidth() + 1),
4517 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004518
Hans Wennborg776d7122012-09-26 09:34:53 +00004519 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004520 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4521 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004522 return Builder.CreateLoad(GEP, "switch.load");
4523 }
4524 }
4525 llvm_unreachable("Unknown lookup table kind!");
4526}
4527
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004528bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004529 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004530 Type *ElementType) {
4531 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004532 if (!IT)
4533 return false;
4534 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4535 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004536
4537 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4538 if (TableSize >= UINT_MAX/IT->getBitWidth())
4539 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004540 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004541}
4542
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004543/// Determine whether a lookup table should be built for this switch, based on
4544/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004545static bool
4546ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4547 const TargetTransformInfo &TTI, const DataLayout &DL,
4548 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004549 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4550 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004551
Chandler Carruth77d433d2012-11-30 09:26:25 +00004552 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004553 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004554 for (const auto &I : ResultTypes) {
4555 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004556
4557 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004558 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004559
4560 // Saturate this flag to false.
4561 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004562 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004563
4564 // If both flags saturate, we're done. NOTE: This *only* works with
4565 // saturating flags, and all flags have to saturate first due to the
4566 // non-deterministic behavior of iterating over a dense map.
4567 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004568 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004569 }
Evan Cheng65df8082012-11-30 02:02:42 +00004570
Chandler Carruth77d433d2012-11-30 09:26:25 +00004571 // If each table would fit in a register, we should build it anyway.
4572 if (AllTablesFitInRegister)
4573 return true;
4574
4575 // Don't build a table that doesn't fit in-register if it has illegal types.
4576 if (HasIllegalType)
4577 return false;
4578
4579 // The table density should be at least 40%. This is the same criterion as for
4580 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4581 // FIXME: Find the best cut-off.
4582 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004583}
4584
Erik Eckstein0d86c762014-11-27 15:13:14 +00004585/// Try to reuse the switch table index compare. Following pattern:
4586/// \code
4587/// if (idx < tablesize)
4588/// r = table[idx]; // table does not contain default_value
4589/// else
4590/// r = default_value;
4591/// if (r != default_value)
4592/// ...
4593/// \endcode
4594/// Is optimized to:
4595/// \code
4596/// cond = idx < tablesize;
4597/// if (cond)
4598/// r = table[idx];
4599/// else
4600/// r = default_value;
4601/// if (cond)
4602/// ...
4603/// \endcode
4604/// Jump threading will then eliminate the second if(cond).
4605static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4606 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4607 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4608
4609 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4610 if (!CmpInst)
4611 return;
4612
4613 // We require that the compare is in the same block as the phi so that jump
4614 // threading can do its work afterwards.
4615 if (CmpInst->getParent() != PhiBlock)
4616 return;
4617
4618 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4619 if (!CmpOp1)
4620 return;
4621
4622 Value *RangeCmp = RangeCheckBranch->getCondition();
4623 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4624 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4625
4626 // Check if the compare with the default value is constant true or false.
4627 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4628 DefaultValue, CmpOp1, true);
4629 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4630 return;
4631
4632 // Check if the compare with the case values is distinct from the default
4633 // compare result.
4634 for (auto ValuePair : Values) {
4635 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4636 ValuePair.second, CmpOp1, true);
4637 if (!CaseConst || CaseConst == DefaultConst)
4638 return;
4639 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4640 "Expect true or false as compare result.");
4641 }
James Molloy4de84dd2015-11-04 15:28:04 +00004642
Erik Eckstein0d86c762014-11-27 15:13:14 +00004643 // Check if the branch instruction dominates the phi node. It's a simple
4644 // dominance check, but sufficient for our needs.
4645 // Although this check is invariant in the calling loops, it's better to do it
4646 // at this late stage. Practically we do it at most once for a switch.
4647 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4648 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4649 BasicBlock *Pred = *PI;
4650 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4651 return;
4652 }
4653
4654 if (DefaultConst == FalseConst) {
4655 // The compare yields the same result. We can replace it.
4656 CmpInst->replaceAllUsesWith(RangeCmp);
4657 ++NumTableCmpReuses;
4658 } else {
4659 // The compare yields the same result, just inverted. We can replace it.
4660 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4661 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4662 RangeCheckBranch);
4663 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4664 ++NumTableCmpReuses;
4665 }
4666}
4667
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004668/// If the switch is only used to initialize one or more phi nodes in a common
4669/// successor block with different constant values, replace the switch with
4670/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004671static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4672 const DataLayout &DL,
4673 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004674 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004675
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004676 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004677 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004678 return false;
4679
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004680 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4681 // split off a dense part and build a lookup table for that.
4682
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004683 // FIXME: This creates arrays of GEPs to constant strings, which means each
4684 // GEP needs a runtime relocation in PIC code. We should just build one big
4685 // string and lookup indices into that.
4686
Hans Wennborg4744ac12014-01-15 05:00:27 +00004687 // Ignore switches with less than three cases. Lookup tables will not make them
4688 // faster, so we don't analyze them.
4689 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004690 return false;
4691
4692 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004693 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004694 assert(SI->case_begin() != SI->case_end());
4695 SwitchInst::CaseIt CI = SI->case_begin();
4696 ConstantInt *MinCaseVal = CI.getCaseValue();
4697 ConstantInt *MaxCaseVal = CI.getCaseValue();
4698
Craig Topperf40110f2014-04-25 05:29:35 +00004699 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004700 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004701 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4702 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4703 SmallDenseMap<PHINode*, Type*> ResultTypes;
4704 SmallVector<PHINode*, 4> PHIs;
4705
4706 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4707 ConstantInt *CaseVal = CI.getCaseValue();
4708 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4709 MinCaseVal = CaseVal;
4710 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4711 MaxCaseVal = CaseVal;
4712
4713 // Resulting value at phi nodes for this case value.
4714 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4715 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004716 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004717 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004718 return false;
4719
4720 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004721 for (const auto &I : Results) {
4722 PHINode *PHI = I.first;
4723 Constant *Value = I.second;
4724 if (!ResultLists.count(PHI))
4725 PHIs.push_back(PHI);
4726 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004727 }
4728 }
4729
Hans Wennborgac114a32014-01-12 00:44:41 +00004730 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004731 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004732 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4733 }
4734
4735 uint64_t NumResults = ResultLists[PHIs[0]].size();
4736 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4737 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4738 bool TableHasHoles = (NumResults < TableSize);
4739
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004740 // If the table has holes, we need a constant result for the default case
4741 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004742 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004743 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004744 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004745
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004746 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4747 if (NeedMask) {
4748 // As an extra penalty for the validity test we require more cases.
4749 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4750 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004751 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004752 return false;
4753 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004754
Hans Wennborga6a11a92014-11-18 02:37:11 +00004755 for (const auto &I : DefaultResultsList) {
4756 PHINode *PHI = I.first;
4757 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004758 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004759 }
4760
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004761 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004762 return false;
4763
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004764 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004765 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004766 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4767 "switch.lookup",
4768 CommonDest->getParent(),
4769 CommonDest);
4770
Michael Gottesmanc024f322013-10-20 07:04:37 +00004771 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004772 Builder.SetInsertPoint(SI);
4773 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4774 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004775
4776 // Compute the maximum table size representable by the integer type we are
4777 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004778 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004779 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004780 assert(MaxTableSize >= TableSize &&
4781 "It is impossible for a switch to have more entries than the max "
4782 "representable value of its input integer type's size.");
4783
Hans Wennborgb64cb272015-01-26 19:52:34 +00004784 // If the default destination is unreachable, or if the lookup table covers
4785 // all values of the conditional variable, branch directly to the lookup table
4786 // BB. Otherwise, check that the condition is within the case range.
4787 const bool DefaultIsReachable =
4788 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4789 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004790 BranchInst *RangeCheckBranch = nullptr;
4791
Hans Wennborgb64cb272015-01-26 19:52:34 +00004792 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004793 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004794 // Note: We call removeProdecessor later since we need to be able to get the
4795 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004796 } else {
4797 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004798 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004799 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004800 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004801
4802 // Populate the BB that does the lookups.
4803 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004804
4805 if (NeedMask) {
4806 // Before doing the lookup we do the hole check.
4807 // The LookupBB is therefore re-purposed to do the hole check
4808 // and we create a new LookupBB.
4809 BasicBlock *MaskBB = LookupBB;
4810 MaskBB->setName("switch.hole_check");
4811 LookupBB = BasicBlock::Create(Mod.getContext(),
4812 "switch.lookup",
4813 CommonDest->getParent(),
4814 CommonDest);
4815
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004816 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4817 // unnecessary illegal types.
4818 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4819 APInt MaskInt(TableSizePowOf2, 0);
4820 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004821 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004822 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4823 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4824 uint64_t Idx = (ResultList[I].first->getValue() -
4825 MinCaseVal->getValue()).getLimitedValue();
4826 MaskInt |= One << Idx;
4827 }
4828 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4829
4830 // Get the TableIndex'th bit of the bitmask.
4831 // If this bit is 0 (meaning hole) jump to the default destination,
4832 // else continue with table lookup.
4833 IntegerType *MapTy = TableMask->getType();
4834 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4835 "switch.maskindex");
4836 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4837 "switch.shifted");
4838 Value *LoBit = Builder.CreateTrunc(Shifted,
4839 Type::getInt1Ty(Mod.getContext()),
4840 "switch.lobit");
4841 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4842
4843 Builder.SetInsertPoint(LookupBB);
4844 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4845 }
4846
Hans Wennborg86ac6302015-04-24 20:57:56 +00004847 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4848 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4849 // do not delete PHINodes here.
4850 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4851 /*DontDeleteUselessPHIs=*/true);
4852 }
4853
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004854 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004855 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4856 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004857 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004858
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004859 // If using a bitmask, use any value to fill the lookup table holes.
4860 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004861 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004862
Manman Ren4d189fb2014-07-24 21:13:20 +00004863 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004864
Hans Wennborgf744fa92012-09-19 14:24:21 +00004865 // If the result is used to return immediately from the function, we want to
4866 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004867 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4868 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004869 Builder.CreateRet(Result);
4870 ReturnedEarly = true;
4871 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004872 }
4873
Erik Eckstein0d86c762014-11-27 15:13:14 +00004874 // Do a small peephole optimization: re-use the switch table compare if
4875 // possible.
4876 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4877 BasicBlock *PhiBlock = PHI->getParent();
4878 // Search for compare instructions which use the phi.
4879 for (auto *User : PHI->users()) {
4880 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4881 }
4882 }
4883
Hans Wennborgf744fa92012-09-19 14:24:21 +00004884 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004885 }
4886
4887 if (!ReturnedEarly)
4888 Builder.CreateBr(CommonDest);
4889
4890 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004891 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004892 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004893
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004894 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004895 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004896 Succ->removePredecessor(SI->getParent());
4897 }
4898 SI->eraseFromParent();
4899
4900 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004901 if (NeedMask)
4902 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004903 return true;
4904}
4905
Devang Patela7ec47d2011-05-18 20:35:38 +00004906bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004907 BasicBlock *BB = SI->getParent();
4908
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004909 if (isValueEqualityComparison(SI)) {
4910 // If we only have one predecessor, and if it is a branch on this value,
4911 // see if that predecessor totally determines the outcome of this switch.
4912 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4913 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004914 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004915
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004916 Value *Cond = SI->getCondition();
4917 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4918 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004919 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004920
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004921 // If the block only contains the switch, see if we can fold the block
4922 // away into any preds.
4923 BasicBlock::iterator BBI = BB->begin();
4924 // Ignore dbg intrinsics.
4925 while (isa<DbgInfoIntrinsic>(BBI))
4926 ++BBI;
4927 if (SI == &*BBI)
4928 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004929 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004930 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004931
4932 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004933 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004934 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004935
4936 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004937 if (EliminateDeadSwitchCases(SI, AC, DL))
4938 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004939
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004940 if (SwitchToSelect(SI, Builder, AC, DL))
4941 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004942
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004943 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004944 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004945
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004946 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4947 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004948
Chris Lattner25c3af32010-12-13 06:25:44 +00004949 return false;
4950}
4951
4952bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4953 BasicBlock *BB = IBI->getParent();
4954 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004955
Chris Lattner25c3af32010-12-13 06:25:44 +00004956 // Eliminate redundant destinations.
4957 SmallPtrSet<Value *, 8> Succs;
4958 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4959 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004960 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004961 Dest->removePredecessor(BB);
4962 IBI->removeDestination(i);
4963 --i; --e;
4964 Changed = true;
4965 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004966 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004967
4968 if (IBI->getNumDestinations() == 0) {
4969 // If the indirectbr has no successors, change it to unreachable.
4970 new UnreachableInst(IBI->getContext(), IBI);
4971 EraseTerminatorInstAndDCECond(IBI);
4972 return true;
4973 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004974
Chris Lattner25c3af32010-12-13 06:25:44 +00004975 if (IBI->getNumDestinations() == 1) {
4976 // If the indirectbr has one successor, change it to a direct branch.
4977 BranchInst::Create(IBI->getDestination(0), IBI);
4978 EraseTerminatorInstAndDCECond(IBI);
4979 return true;
4980 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004981
Chris Lattner25c3af32010-12-13 06:25:44 +00004982 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4983 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004984 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004985 }
4986 return Changed;
4987}
4988
Philip Reames2b969d72015-03-24 22:28:45 +00004989/// Given an block with only a single landing pad and a unconditional branch
4990/// try to find another basic block which this one can be merged with. This
4991/// handles cases where we have multiple invokes with unique landing pads, but
4992/// a shared handler.
4993///
4994/// We specifically choose to not worry about merging non-empty blocks
4995/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4996/// practice, the optimizer produces empty landing pad blocks quite frequently
4997/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4998/// sinking in this file)
4999///
5000/// This is primarily a code size optimization. We need to avoid performing
5001/// any transform which might inhibit optimization (such as our ability to
5002/// specialize a particular handler via tail commoning). We do this by not
5003/// merging any blocks which require us to introduce a phi. Since the same
5004/// values are flowing through both blocks, we don't loose any ability to
5005/// specialize. If anything, we make such specialization more likely.
5006///
5007/// TODO - This transformation could remove entries from a phi in the target
5008/// block when the inputs in the phi are the same for the two blocks being
5009/// merged. In some cases, this could result in removal of the PHI entirely.
5010static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5011 BasicBlock *BB) {
5012 auto Succ = BB->getUniqueSuccessor();
5013 assert(Succ);
5014 // If there's a phi in the successor block, we'd likely have to introduce
5015 // a phi into the merged landing pad block.
5016 if (isa<PHINode>(*Succ->begin()))
5017 return false;
5018
5019 for (BasicBlock *OtherPred : predecessors(Succ)) {
5020 if (BB == OtherPred)
5021 continue;
5022 BasicBlock::iterator I = OtherPred->begin();
5023 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5024 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5025 continue;
5026 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5027 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5028 if (!BI2 || !BI2->isIdenticalTo(BI))
5029 continue;
5030
David Majnemer1efa23d2016-02-20 01:07:45 +00005031 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005032 // path instead and make ourselves dead.
5033 SmallSet<BasicBlock *, 16> Preds;
5034 Preds.insert(pred_begin(BB), pred_end(BB));
5035 for (BasicBlock *Pred : Preds) {
5036 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
5037 assert(II->getNormalDest() != BB &&
5038 II->getUnwindDest() == BB && "unexpected successor");
5039 II->setUnwindDest(OtherPred);
5040 }
5041
5042 // The debug info in OtherPred doesn't cover the merged control flow that
5043 // used to go through BB. We need to delete it or update it.
5044 for (auto I = OtherPred->begin(), E = OtherPred->end();
5045 I != E;) {
5046 Instruction &Inst = *I; I++;
5047 if (isa<DbgInfoIntrinsic>(Inst))
5048 Inst.eraseFromParent();
5049 }
5050
5051 SmallSet<BasicBlock *, 16> Succs;
5052 Succs.insert(succ_begin(BB), succ_end(BB));
5053 for (BasicBlock *Succ : Succs) {
5054 Succ->removePredecessor(BB);
5055 }
5056
5057 IRBuilder<> Builder(BI);
5058 Builder.CreateUnreachable();
5059 BI->eraseFromParent();
5060 return true;
5061 }
5062 return false;
5063}
5064
Devang Patel767f6932011-05-18 18:28:48 +00005065bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00005066 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005067
Manman Ren93ab6492012-09-20 22:37:36 +00005068 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5069 return true;
5070
Chris Lattner25c3af32010-12-13 06:25:44 +00005071 // If the Terminator is the only non-phi instruction, simplify the block.
Hyojin Sung4673f102016-03-29 04:08:57 +00005072 // if LoopHeader is provided, check if the block is a loop header
5073 // (This is for early invocations before loop simplify and vectorization
5074 // to keep canonical loop forms for nested loops.
5075 // These blocks can be eliminated when the pass is invoked later
5076 // in the back-end.)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00005077 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005078 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
Hans Wennborge9134892016-04-11 20:35:01 +00005079 (!LoopHeaders || !LoopHeaders->count(BB)) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00005080 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5081 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005082
Chris Lattner25c3af32010-12-13 06:25:44 +00005083 // If the only instruction in the block is a seteq/setne comparison
5084 // against a constant, try to simplify the block.
5085 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5086 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5087 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5088 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005089 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005090 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5091 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005092 return true;
5093 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005094
Philip Reames2b969d72015-03-24 22:28:45 +00005095 // See if we can merge an empty landing pad block with another which is
5096 // equivalent.
5097 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5098 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5099 if (I->isTerminator() &&
5100 TryToMergeLandingPad(LPad, BI, BB))
5101 return true;
5102 }
5103
Manman Rend33f4ef2012-06-13 05:43:29 +00005104 // If this basic block is ONLY a compare and a branch, and if a predecessor
5105 // branches to us and our successor, fold the comparison into the
5106 // predecessor and use logical operations to update the incoming value
5107 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005108 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5109 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005110 return false;
5111}
5112
James Molloy4de84dd2015-11-04 15:28:04 +00005113static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5114 BasicBlock *PredPred = nullptr;
5115 for (auto *P : predecessors(BB)) {
5116 BasicBlock *PPred = P->getSinglePredecessor();
5117 if (!PPred || (PredPred && PredPred != PPred))
5118 return nullptr;
5119 PredPred = PPred;
5120 }
5121 return PredPred;
5122}
Chris Lattner25c3af32010-12-13 06:25:44 +00005123
Devang Patela7ec47d2011-05-18 20:35:38 +00005124bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005125 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005126
Chris Lattner25c3af32010-12-13 06:25:44 +00005127 // Conditional branch
5128 if (isValueEqualityComparison(BI)) {
5129 // If we only have one predecessor, and if it is a branch on this value,
5130 // see if that predecessor totally determines the outcome of this
5131 // switch.
5132 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005133 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005134 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005135
Chris Lattner25c3af32010-12-13 06:25:44 +00005136 // This block must be empty, except for the setcond inst, if it exists.
5137 // Ignore dbg intrinsics.
5138 BasicBlock::iterator I = BB->begin();
5139 // Ignore dbg intrinsics.
5140 while (isa<DbgInfoIntrinsic>(I))
5141 ++I;
5142 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005143 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005144 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005145 } else if (&*I == cast<Instruction>(BI->getCondition())){
5146 ++I;
5147 // Ignore dbg intrinsics.
5148 while (isa<DbgInfoIntrinsic>(I))
5149 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005150 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005151 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005152 }
5153 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005154
Chris Lattner25c3af32010-12-13 06:25:44 +00005155 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005156 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005157 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005158
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005159 // If this basic block is ONLY a compare and a branch, and if a predecessor
5160 // branches to us and one of our successors, fold the comparison into the
5161 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005162 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5163 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005164
Chris Lattner25c3af32010-12-13 06:25:44 +00005165 // We have a conditional branch to two blocks that are only reachable
5166 // from BI. We know that the condbr dominates the two blocks, so see if
5167 // there is any identical code in the "then" and "else" blocks. If so, we
5168 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005169 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5170 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005171 if (HoistThenElseCodeToIf(BI, TTI))
5172 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005173 } else {
5174 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005175 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005176 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5177 if (Succ0TI->getNumSuccessors() == 1 &&
5178 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005179 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5180 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005181 }
Craig Topperf40110f2014-04-25 05:29:35 +00005182 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005183 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005184 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005185 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5186 if (Succ1TI->getNumSuccessors() == 1 &&
5187 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005188 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5189 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005190 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005191
Chris Lattner25c3af32010-12-13 06:25:44 +00005192 // If this is a branch on a phi node in the current block, thread control
5193 // through this block if any PHI node entries are constants.
5194 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5195 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005196 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005197 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005198
Chris Lattner25c3af32010-12-13 06:25:44 +00005199 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005200 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5201 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005202 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005203 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005204 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005205
James Molloy4de84dd2015-11-04 15:28:04 +00005206 // Look for diamond patterns.
5207 if (MergeCondStores)
5208 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5209 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5210 if (PBI != BI && PBI->isConditional())
5211 if (mergeConditionalStores(PBI, BI))
5212 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5213
Chris Lattner25c3af32010-12-13 06:25:44 +00005214 return false;
5215}
5216
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005217/// Check if passing a value to an instruction will cause undefined behavior.
5218static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5219 Constant *C = dyn_cast<Constant>(V);
5220 if (!C)
5221 return false;
5222
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005223 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005224 return false;
5225
5226 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005227 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005228 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005229
5230 // Now make sure that there are no instructions in between that can alter
5231 // control flow (eg. calls)
5232 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005233 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005234 return false;
5235
5236 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5237 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5238 if (GEP->getPointerOperand() == I)
5239 return passingValueIsAlwaysUndefined(V, GEP);
5240
5241 // Look through bitcasts.
5242 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5243 return passingValueIsAlwaysUndefined(V, BC);
5244
Benjamin Kramer0655b782011-08-26 02:25:55 +00005245 // Load from null is undefined.
5246 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005247 if (!LI->isVolatile())
5248 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005249
Benjamin Kramer0655b782011-08-26 02:25:55 +00005250 // Store to null is undefined.
5251 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005252 if (!SI->isVolatile())
5253 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005254 }
5255 return false;
5256}
5257
5258/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005259/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005260static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5261 for (BasicBlock::iterator i = BB->begin();
5262 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5263 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5264 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5265 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5266 IRBuilder<> Builder(T);
5267 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5268 BB->removePredecessor(PHI->getIncomingBlock(i));
5269 // Turn uncoditional branches into unreachables and remove the dead
5270 // destination from conditional branches.
5271 if (BI->isUnconditional())
5272 Builder.CreateUnreachable();
5273 else
5274 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5275 BI->getSuccessor(0));
5276 BI->eraseFromParent();
5277 return true;
5278 }
5279 // TODO: SwitchInst.
5280 }
5281
5282 return false;
5283}
5284
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005285bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005286 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005287
Chris Lattnerd7beca32010-12-14 06:17:25 +00005288 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005289 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005290
Dan Gohman4a63fad2010-08-14 00:29:42 +00005291 // Remove basic blocks that have no predecessors (except the entry block)...
5292 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00005293 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00005294 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005295 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005296 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5297 DeleteDeadBlock(BB);
5298 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005299 }
5300
Chris Lattner031340a2003-08-17 19:41:53 +00005301 // Check to see if we can constant propagate this terminator instruction
5302 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005303 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005304
Dan Gohman1a951062009-10-30 22:39:04 +00005305 // Check for and eliminate duplicate PHI nodes in this block.
5306 Changed |= EliminateDuplicatePHINodes(BB);
5307
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005308 // Check for and remove branches that will always cause undefined behavior.
5309 Changed |= removeUndefIntroducingPredecessor(BB);
5310
Chris Lattner2e3832d2010-12-13 05:10:48 +00005311 // Merge basic blocks into their predecessor if there is only one distinct
5312 // pred, and if there is only one distinct successor of the predecessor, and
5313 // if there are no PHI nodes.
5314 //
5315 if (MergeBlockIntoPredecessor(BB))
5316 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005317
Devang Patel15ad6762011-05-18 18:01:27 +00005318 IRBuilder<> Builder(BB);
5319
Dan Gohman20af5a02008-03-11 21:53:06 +00005320 // If there is a trivial two-entry PHI node in this basic block, and we can
5321 // eliminate it, do so now.
5322 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5323 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005324 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005325
Devang Patela7ec47d2011-05-18 20:35:38 +00005326 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005327 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005328 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00005329 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005330 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00005331 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005332 }
5333 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00005334 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005335 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5336 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005337 } else if (CleanupReturnInst *RI =
5338 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5339 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005340 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00005341 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005342 } else if (UnreachableInst *UI =
5343 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5344 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005345 } else if (IndirectBrInst *IBI =
5346 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5347 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005348 }
5349
Chris Lattner031340a2003-08-17 19:41:53 +00005350 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005351}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005352
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005353/// This function is used to do simplification of a CFG.
5354/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005355/// eliminates unreachable basic blocks, and does other "peephole" optimization
5356/// of the CFG. It returns true if a modification was made.
5357///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005358bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Hyojin Sung4673f102016-03-29 04:08:57 +00005359 unsigned BonusInstThreshold, AssumptionCache *AC,
5360 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005361 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
Hyojin Sung4673f102016-03-29 04:08:57 +00005362 BonusInstThreshold, AC, LoopHeaders).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005363}