blob: 1b442a9a264d4c05ffa5c9b9f75ac82233367838 [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
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000014#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000017#include "llvm/ADT/Optional.h"
James Molloy4de84dd2015-11-04 15:28:04 +000018#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000021#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000024#include "llvm/ADT/STLExtras.h"
Peter Collingbourne0609acc2017-02-15 03:01:11 +000025#include "llvm/Analysis/AssumptionCache.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000026#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000027#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000029#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000031#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/CallSite.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000033#include "llvm/IR/CFG.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000034#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000035#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
Andrea Di Biagiof20c57e2016-12-15 20:01:26 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000040#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/GlobalVariable.h"
42#include "llvm/IR/IRBuilder.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000043#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000047#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/MDBuilder.h"
50#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000052#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000054#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Type.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000056#include "llvm/IR/User.h"
57#include "llvm/IR/Value.h"
Robert Loughercf176742016-12-15 16:17:53 +000058#include "llvm/IR/DebugInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000059#include "llvm/Support/Casting.h"
Evan Chengd983eba2011-01-29 04:46:23 +000060#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000061#include "llvm/Support/Debug.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000062#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000063#include "llvm/Support/KnownBits.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000064#include "llvm/Support/MathExtras.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000065#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dehao Chenf6c00832016-05-18 19:44:21 +000067#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000068#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000069#include <algorithm>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000070#include <cassert>
71#include <climits>
72#include <cstddef>
73#include <cstdint>
74#include <iterator>
Chris Lattner5edb2f32004-10-18 04:07:22 +000075#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000076#include <set>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000077#include <utility>
78#include <vector>
79
Chris Lattnerdf3c3422004-01-09 06:12:26 +000080using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000081using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000082
Chandler Carruth964daaa2014-04-22 02:55:47 +000083#define DEBUG_TYPE "simplifycfg"
84
James Molloy1b6207e2015-02-13 10:48:30 +000085// Chosen as 2 so as to be cheap, but still to have enough power to fold
86// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
87// To catch this, we need to fold a compare and a select, hence '2' being the
88// minimum reasonable default.
Dehao Chenf6c00832016-05-18 19:44:21 +000089static cl::opt<unsigned> PHINodeFoldingThreshold(
90 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
91 cl::desc(
92 "Control the amount of phi node folding to perform (default = 2)"));
93
94static cl::opt<bool> DupRet(
95 "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
96 cl::desc("Duplicate return instructions into unconditional branches"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000097
Evan Chengd983eba2011-01-29 04:46:23 +000098static cl::opt<bool>
Dehao Chenf6c00832016-05-18 19:44:21 +000099 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
100 cl::desc("Sink common instructions down to the end block"));
Manman Ren93ab6492012-09-20 22:37:36 +0000101
Alp Tokercb402912014-01-24 17:20:08 +0000102static cl::opt<bool> HoistCondStores(
103 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
104 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +0000105
James Molloy4de84dd2015-11-04 15:28:04 +0000106static cl::opt<bool> MergeCondStores(
107 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
108 cl::desc("Hoist conditional stores even if an unconditional store does not "
109 "precede - hoist multiple conditional stores into a single "
110 "predicated store"));
111
112static cl::opt<bool> MergeCondStoresAggressively(
113 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
114 cl::desc("When merging conditional stores, do so even if the resultant "
115 "basic blocks are unlikely to be if-converted as a result"));
116
David Majnemerfccf5c62016-01-27 02:59:41 +0000117static cl::opt<bool> SpeculateOneExpensiveInst(
118 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
119 cl::desc("Allow exactly one expensive instruction to be speculatively "
120 "executed"));
121
Sanjay Patel5264cc72016-01-27 19:22:45 +0000122static cl::opt<unsigned> MaxSpeculationDepth(
123 "max-speculation-depth", cl::Hidden, cl::init(10),
124 cl::desc("Limit maximum recursion depth when calculating costs of "
125 "speculatively executed instructions"));
126
Hans Wennborg39583b82012-09-26 09:44:49 +0000127STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Dehao Chenf6c00832016-05-18 19:44:21 +0000128STATISTIC(NumLinearMaps,
129 "Number of switch instructions turned into linear mapping");
130STATISTIC(NumLookupTables,
131 "Number of switch instructions turned into lookup tables");
132STATISTIC(
133 NumLookupTablesHoles,
134 "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000135STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Dehao Chenf6c00832016-05-18 19:44:21 +0000136STATISTIC(NumSinkCommons,
137 "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000138STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000139
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000140namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000141
Dehao Chenf6c00832016-05-18 19:44:21 +0000142// The first field contains the value that the switch produces when a certain
143// case group is selected, and the second field is a vector containing the
144// cases composing the case group.
145typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000146 SwitchCaseResultVectorTy;
Dehao Chenf6c00832016-05-18 19:44:21 +0000147// The first field contains the phi node that generates a result of the switch
148// and the second field contains the value generated for a certain case in the
149// switch for that PHI.
150typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000151
Dehao Chenf6c00832016-05-18 19:44:21 +0000152/// ValueEqualityComparisonCase - Represents a case of a switch.
153struct ValueEqualityComparisonCase {
154 ConstantInt *Value;
155 BasicBlock *Dest;
Eric Christopherb65acc62012-07-02 23:22:21 +0000156
Dehao Chenf6c00832016-05-18 19:44:21 +0000157 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
Eric Christopherb65acc62012-07-02 23:22:21 +0000158 : Value(Value), Dest(Dest) {}
159
Dehao Chenf6c00832016-05-18 19:44:21 +0000160 bool operator<(ValueEqualityComparisonCase RHS) const {
161 // Comparing pointers is ok as we only rely on the order for uniquing.
162 return Value < RHS.Value;
163 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000164
Dehao Chenf6c00832016-05-18 19:44:21 +0000165 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
166};
Eric Christopherb65acc62012-07-02 23:22:21 +0000167
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000168class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000169 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000170 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000171 unsigned BonusInstThreshold;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000172 AssumptionCache *AC;
Hyojin Sung4673f102016-03-29 04:08:57 +0000173 SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +0000174 // See comments in SimplifyCFGOpt::SimplifySwitch.
175 bool LateSimplifyCFG;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000176 Value *isValueEqualityComparison(TerminatorInst *TI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000177 BasicBlock *GetValueEqualityComparisonCases(
178 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000179 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000180 BasicBlock *Pred,
181 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000182 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
183 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000184
Devang Pateldd14e0f2011-05-18 21:33:11 +0000185 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000186 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000187 bool SimplifySingleResume(ResumeInst *RI);
188 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000189 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000190 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000191 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000192 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000193 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
194 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000195
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000196public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000197 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000198 unsigned BonusInstThreshold, AssumptionCache *AC,
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +0000199 SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
200 bool LateSimplifyCFG)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000201 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC),
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +0000202 LoopHeaders(LoopHeaders), LateSimplifyCFG(LateSimplifyCFG) {}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000203
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000204 bool run(BasicBlock *BB);
205};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000206
207} // end anonymous namespace
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000208
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000209/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000210/// terminator instructions together.
James Molloye6566422016-09-01 07:45:25 +0000211static bool
212SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2,
James Molloy21744682016-09-01 09:01:34 +0000213 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000214 if (SI1 == SI2)
215 return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000216
Chris Lattner76dc2042005-08-03 00:19:45 +0000217 // It is not safe to merge these two switch instructions if they have a common
218 // successor, and if that successor has a PHI node, and if *that* PHI node has
219 // conflicting incoming values from the two switch blocks.
220 BasicBlock *SI1BB = SI1->getParent();
221 BasicBlock *SI2BB = SI2->getParent();
James Molloy3c1137c2016-08-31 13:32:28 +0000222
James Molloye6566422016-09-01 07:45:25 +0000223 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
224 bool Fail = false;
Sanjay Patel5781d842016-03-12 16:52:17 +0000225 for (BasicBlock *Succ : successors(SI2BB))
226 if (SI1Succs.count(Succ))
227 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000228 PHINode *PN = cast<PHINode>(BBI);
229 if (PN->getIncomingValueForBlock(SI1BB) !=
James Molloye6566422016-09-01 07:45:25 +0000230 PN->getIncomingValueForBlock(SI2BB)) {
231 if (FailBlocks)
232 FailBlocks->insert(Succ);
233 Fail = true;
234 }
Chris Lattner76dc2042005-08-03 00:19:45 +0000235 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000236
James Molloye6566422016-09-01 07:45:25 +0000237 return !Fail;
Chris Lattner76dc2042005-08-03 00:19:45 +0000238}
239
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000240/// Return true if it is safe and profitable to merge these two terminator
241/// instructions together, where SI1 is an unconditional branch. PhiNodes will
242/// store all PHI nodes in common successors.
Dehao Chenf6c00832016-05-18 19:44:21 +0000243static bool
244isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
245 Instruction *Cond,
246 SmallVectorImpl<PHINode *> &PhiNodes) {
247 if (SI1 == SI2)
248 return false; // Can't merge with self!
Manman Rend33f4ef2012-06-13 05:43:29 +0000249 assert(SI1->isUnconditional() && SI2->isConditional());
250
251 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000252 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000253 // 1> We have a constant incoming value for the conditional branch;
254 // 2> We have "Cond" as the incoming value for the unconditional branch;
255 // 3> SI2->getCondition() and Cond have same operands.
256 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +0000257 if (!Ci2)
258 return false;
Manman Rend33f4ef2012-06-13 05:43:29 +0000259 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
260 Cond->getOperand(1) == Ci2->getOperand(1)) &&
261 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
262 Cond->getOperand(1) == Ci2->getOperand(0)))
263 return false;
264
265 BasicBlock *SI1BB = SI1->getParent();
266 BasicBlock *SI2BB = SI2->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000267 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Sanjay Patel5781d842016-03-12 16:52:17 +0000268 for (BasicBlock *Succ : successors(SI2BB))
269 if (SI1Succs.count(Succ))
270 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Manman Rend33f4ef2012-06-13 05:43:29 +0000271 PHINode *PN = cast<PHINode>(BBI);
272 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000273 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000274 return false;
275 PhiNodes.push_back(PN);
276 }
277 return true;
278}
279
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000280/// Update PHI nodes in Succ to indicate that there will now be entries in it
281/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
282/// will be the same as those coming in from ExistPred, an existing predecessor
283/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000284static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
285 BasicBlock *ExistPred) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000286 if (!isa<PHINode>(Succ->begin()))
287 return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000288
Chris Lattner80b03a12008-07-13 22:23:11 +0000289 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +0000290 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
Chris Lattner80b03a12008-07-13 22:23:11 +0000291 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000292}
293
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000294/// Compute an abstract "cost" of speculating the given instruction,
295/// which is assumed to be safe to speculate. TCC_Free means cheap,
296/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000297/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000298static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000299 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000300 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000301 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000302 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000303}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000304
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000305/// If we have a merge point of an "if condition" as accepted above,
306/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000307/// don't handle the true generality of domination here, just a special case
308/// which works well enough for us.
309///
310/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000311/// see if V (which must be an instruction) and its recursive operands
312/// that do not dominate BB have a combined cost lower than CostRemaining and
313/// are non-trapping. If both are true, the instruction is inserted into the
314/// set and true is returned.
315///
316/// The cost for most non-trapping instructions is defined as 1 except for
317/// Select whose cost is 2.
318///
319/// After this function returns, CostRemaining is decreased by the cost of
320/// V plus its non-dominating operands. If that cost is greater than
321/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000322static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Dehao Chenf6c00832016-05-18 19:44:21 +0000323 SmallPtrSetImpl<Instruction *> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000324 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000325 const TargetTransformInfo &TTI,
326 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000327 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
328 // so limit the recursion depth.
329 // TODO: While this recursion limit does prevent pathological behavior, it
330 // would be better to track visited instructions to avoid cycles.
331 if (Depth == MaxSpeculationDepth)
332 return false;
333
Chris Lattner0aa56562004-04-09 22:50:22 +0000334 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000335 if (!I) {
336 // Non-instructions all dominate instructions, but not all constantexprs
337 // can be executed unconditionally.
338 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
339 if (C->canTrap())
340 return false;
341 return true;
342 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000343 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000344
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000345 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000346 // the bottom of this block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000347 if (PBB == BB)
348 return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000349
Chris Lattner0aa56562004-04-09 22:50:22 +0000350 // If this instruction is defined in a block that contains an unconditional
351 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000352 // statement". If not, it definitely dominates the region.
353 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000354 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000355 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000356
Chris Lattner9ac168d2010-12-14 07:41:39 +0000357 // If we aren't allowing aggressive promotion anymore, then don't consider
358 // instructions in the 'if region'.
Dehao Chenf6c00832016-05-18 19:44:21 +0000359 if (!AggressiveInsts)
360 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000361
Peter Collingbournee3511e12011-04-29 18:47:31 +0000362 // If we have seen this instruction before, don't count it again.
Dehao Chenf6c00832016-05-18 19:44:21 +0000363 if (AggressiveInsts->count(I))
364 return true;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000365
Chris Lattner9ac168d2010-12-14 07:41:39 +0000366 // Okay, it looks like the instruction IS in the "condition". Check to
367 // see if it's a cheap instruction to unconditionally compute, and if it
368 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000369 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000370 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000371
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000372 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000373
David Majnemerfccf5c62016-01-27 02:59:41 +0000374 // Allow exactly one instruction to be speculated regardless of its cost
375 // (as long as it is safe to do so).
376 // This is intended to flatten the CFG even if the instruction is a division
377 // or other expensive operation. The speculation of an expensive instruction
378 // is expected to be undone in CodeGenPrepare if the speculation has not
379 // enabled further IR optimizations.
380 if (Cost > CostRemaining &&
381 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000382 return false;
383
David Majnemerfccf5c62016-01-27 02:59:41 +0000384 // Avoid unsigned wrap.
385 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000386
387 // Okay, we can only really hoist these out if their operands do
388 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000389 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000390 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
391 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000392 return false;
393 // Okay, it's safe to do this! Remember this instruction.
394 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000395 return true;
396}
Chris Lattner466a0492002-05-21 20:50:24 +0000397
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000398/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000399/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000401 // Normal constant int.
402 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000403 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000404 return CI;
405
406 // This is some kind of pointer constant. Turn it into a pointer-sized
407 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000409
410 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
411 if (isa<ConstantPointerNull>(V))
412 return ConstantInt::get(PtrTy, 0);
413
414 // IntToPtr const int.
415 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
416 if (CE->getOpcode() == Instruction::IntToPtr)
417 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
418 // The constant is very likely to have the right type already.
419 if (CI->getType() == PtrTy)
420 return CI;
421 else
Dehao Chenf6c00832016-05-18 19:44:21 +0000422 return cast<ConstantInt>(
423 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000424 }
Craig Topperf40110f2014-04-25 05:29:35 +0000425 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000426}
427
Mehdi Aminiffd01002014-11-20 22:40:25 +0000428namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000429
Mehdi Aminiffd01002014-11-20 22:40:25 +0000430/// Given a chain of or (||) or and (&&) comparison of a value against a
431/// constant, this will try to recover the information required for a switch
432/// structure.
433/// It will depth-first traverse the chain of comparison, seeking for patterns
434/// like %a == 12 or %a < 4 and combine them to produce a set of integer
435/// representing the different cases for the switch.
436/// Note that if the chain is composed of '||' it will build the set of elements
437/// that matches the comparisons (i.e. any of this value validate the chain)
438/// while for a chain of '&&' it will build the set elements that make the test
439/// fail.
440struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000442 Value *CompValue; /// Value found for the switch comparison
443 Value *Extra; /// Extra clause to be checked before the switch
444 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
445 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000446
Mehdi Aminiffd01002014-11-20 22:40:25 +0000447 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000448 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
449 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
450 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000451 }
452
Mehdi Aminiffd01002014-11-20 22:40:25 +0000453 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000454 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000455 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000456 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000457
Mehdi Aminiffd01002014-11-20 22:40:25 +0000458private:
Mehdi Aminiffd01002014-11-20 22:40:25 +0000459 /// Try to set the current value used for the comparison, it succeeds only if
460 /// it wasn't set before or if the new value is the same as the old one
461 bool setValueOnce(Value *NewVal) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000462 if (CompValue && CompValue != NewVal)
463 return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000464 CompValue = NewVal;
465 return (CompValue != nullptr);
466 }
467
468 /// Try to match Instruction "I" as a comparison against a constant and
469 /// populates the array Vals with the set of values that match (or do not
470 /// match depending on isEQ).
471 /// Return false on failure. On success, the Value the comparison matched
472 /// against is placed in CompValue.
473 /// If CompValue is already set, the function is expected to fail if a match
474 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000475 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000476 // If this is an icmp against a constant, handle this as one of the cases.
477 ICmpInst *ICI;
478 ConstantInt *C;
479 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
Dehao Chenf6c00832016-05-18 19:44:21 +0000480 (C = GetConstantInt(I->getOperand(1), DL)))) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000481 return false;
482 }
483
484 Value *RHSVal;
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000485 const APInt *RHSC;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000486
487 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000488 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000489 // This undoes a transformation done by instcombine to fuse 2 compares.
Dehao Chenf6c00832016-05-18 19:44:21 +0000490 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000491
492 // It's a little bit hard to see why the following transformations are
493 // correct. Here is a CVC3 program to verify them for 64-bit values:
494
495 /*
496 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
497 x : BITVECTOR(64);
498 y : BITVECTOR(64);
499 z : BITVECTOR(64);
500 mask : BITVECTOR(64) = BVSHL(ONE, z);
501 QUERY( (y & ~mask = y) =>
502 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
503 );
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000504 QUERY( (y | mask = y) =>
505 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
506 );
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000507 */
508
509 // Please note that each pattern must be a dual implication (<--> or
510 // iff). One directional implication can create spurious matches. If the
511 // implication is only one-way, an unsatisfiable condition on the left
512 // side can imply a satisfiable condition on the right side. Dual
513 // implication ensures that satisfiable conditions are transformed to
514 // other satisfiable conditions and unsatisfiable conditions are
515 // transformed to other unsatisfiable conditions.
516
517 // Here is a concrete example of a unsatisfiable condition on the left
518 // implying a satisfiable condition on the right:
519 //
520 // mask = (1 << z)
521 // (x & ~mask) == y --> (x == y || x == (y | mask))
522 //
523 // Substituting y = 3, z = 0 yields:
524 // (x & -2) == 3 --> (x == 3 || x == 2)
525
526 // Pattern match a special case:
527 /*
528 QUERY( (y & ~mask = y) =>
529 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
530 );
531 */
Mehdi Aminiffd01002014-11-20 22:40:25 +0000532 if (match(ICI->getOperand(0),
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000533 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
534 APInt Mask = ~*RHSC;
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000535 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000536 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000537 if (!setValueOnce(RHSVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000538 return false;
539
540 Vals.push_back(C);
Dehao Chenf6c00832016-05-18 19:44:21 +0000541 Vals.push_back(
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000542 ConstantInt::get(C->getContext(),
543 C->getValue() | Mask));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000544 UsedICmps++;
545 return true;
546 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000547 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000548
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000549 // Pattern match a special case:
550 /*
551 QUERY( (y | mask = y) =>
552 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
553 );
554 */
555 if (match(ICI->getOperand(0),
556 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
557 APInt Mask = *RHSC;
558 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
559 // If we already have a value for the switch, it has to match!
560 if (!setValueOnce(RHSVal))
561 return false;
562
563 Vals.push_back(C);
564 Vals.push_back(ConstantInt::get(C->getContext(),
565 C->getValue() & ~Mask));
566 UsedICmps++;
567 return true;
568 }
569 }
570
Mehdi Aminiffd01002014-11-20 22:40:25 +0000571 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000572 if (!setValueOnce(ICI->getOperand(0)))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000573 return false;
574
575 UsedICmps++;
576 Vals.push_back(C);
577 return ICI->getOperand(0);
578 }
579
580 // 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 +0000581 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
582 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000583
584 // Shift the range if the compare is fed by an add. This is the range
585 // compare idiom as emitted by instcombine.
586 Value *CandidateVal = I->getOperand(0);
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000587 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
588 Span = Span.subtract(*RHSC);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000589 CandidateVal = RHSVal;
590 }
591
592 // If this is an and/!= check, then we are looking to build the set of
593 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
594 // x != 0 && x != 1.
595 if (!isEQ)
596 Span = Span.inverse();
597
598 // If there are a ton of values, we don't want to make a ginormous switch.
Craig Topper7e3e7af2017-05-07 22:22:11 +0000599 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000600 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000601 }
602
603 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000604 if (!setValueOnce(CandidateVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000605 return false;
606
607 // Add all values from the range to the set
608 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
609 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000610
611 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000612 return true;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000613 }
614
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000615 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000616 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
617 /// the value being compared, and stick the list constants into the Vals
618 /// vector.
619 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000620 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000621 Instruction *I = dyn_cast<Instruction>(V);
622 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000623
Mehdi Aminiffd01002014-11-20 22:40:25 +0000624 // Keep a stack (SmallVector for efficiency) for depth-first traversal
625 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000626 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000627
Mehdi Aminiffd01002014-11-20 22:40:25 +0000628 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000629 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000630 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000631
Dehao Chenf6c00832016-05-18 19:44:21 +0000632 while (!DFT.empty()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000633 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000634
Mehdi Aminiffd01002014-11-20 22:40:25 +0000635 if (Instruction *I = dyn_cast<Instruction>(V)) {
636 // If it is a || (or && depending on isEQ), process the operands.
637 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000638 if (Visited.insert(I->getOperand(1)).second)
639 DFT.push_back(I->getOperand(1));
640 if (Visited.insert(I->getOperand(0)).second)
641 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000642 continue;
643 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000644
Mehdi Aminiffd01002014-11-20 22:40:25 +0000645 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000646 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000647 // Match succeed, continue the loop
648 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000649 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000650
Mehdi Aminiffd01002014-11-20 22:40:25 +0000651 // One element of the sequence of || (or &&) could not be match as a
652 // comparison against the same value as the others.
653 // We allow only one "Extra" case to be checked before the switch
654 if (!Extra) {
655 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000656 continue;
657 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000658 // Failed to parse a proper sequence, abort now
659 CompValue = nullptr;
660 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000661 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000662 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000663};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000664
665} // end anonymous namespace
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000666
Eli Friedmancb61afb2008-12-16 20:54:32 +0000667static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000668 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000669 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
670 Cond = dyn_cast<Instruction>(SI->getCondition());
671 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
672 if (BI->isConditional())
673 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000674 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
675 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000676 }
677
678 TI->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000679 if (Cond)
680 RecursivelyDeleteTriviallyDeadInstructions(Cond);
Eli Friedmancb61afb2008-12-16 20:54:32 +0000681}
682
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000683/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000684/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000685Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000686 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000687 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
688 // Do not permit merging of large switch instructions into their
689 // predecessors unless there is only one predecessor.
Dehao Chenf6c00832016-05-18 19:44:21 +0000690 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
691 pred_end(SI->getParent())) <=
692 128)
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000693 CV = SI->getCondition();
694 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000695 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000696 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000697 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000698 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000700
701 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000702 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000703 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
704 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000705 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000706 CV = Ptr;
707 }
708 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000709 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000710}
711
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000712/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000713/// decode all of the 'cases' that it represents and return the 'default' block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000714BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
715 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000716 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000717 Cases.reserve(SI->getNumCases());
Chandler Carruth927d8e62017-04-12 07:27:28 +0000718 for (auto Case : SI->cases())
719 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
720 Case.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000721 return SI->getDefaultDest();
722 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000723
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000724 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000725 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000726 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
Dehao Chenf6c00832016-05-18 19:44:21 +0000727 Cases.push_back(ValueEqualityComparisonCase(
728 GetConstantInt(ICI->getOperand(1), DL), Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000729 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000730}
731
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000732/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000733/// in the list that match the specified block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000734static void
735EliminateBlockCases(BasicBlock *BB,
736 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000737 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000738}
739
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000740/// Return true if there are any keys in C1 that exist in C2 as well.
Dehao Chenf6c00832016-05-18 19:44:21 +0000741static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
742 std::vector<ValueEqualityComparisonCase> &C2) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000743 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
744
745 // Make V1 be smaller than V2.
746 if (V1->size() > V2->size())
747 std::swap(V1, V2);
748
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000749 if (V1->empty())
Dehao Chenf6c00832016-05-18 19:44:21 +0000750 return false;
Eric Christopherb65acc62012-07-02 23:22:21 +0000751 if (V1->size() == 1) {
752 // Just scan V2.
753 ConstantInt *TheVal = (*V1)[0].Value;
754 for (unsigned i = 0, e = V2->size(); i != e; ++i)
755 if (TheVal == (*V2)[i].Value)
756 return true;
757 }
758
759 // Otherwise, just sort both lists and compare element by element.
760 array_pod_sort(V1->begin(), V1->end());
761 array_pod_sort(V2->begin(), V2->end());
762 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
763 while (i1 != e1 && i2 != e2) {
764 if ((*V1)[i1].Value == (*V2)[i2].Value)
765 return true;
766 if ((*V1)[i1].Value < (*V2)[i2].Value)
767 ++i1;
768 else
769 ++i2;
770 }
771 return false;
772}
773
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000774/// If TI is known to be a terminator instruction and its block is known to
775/// only have a single predecessor block, check to see if that predecessor is
776/// also a value comparison with the same value, and if that comparison
777/// determines the outcome of this comparison. If so, simplify TI. This does a
778/// very limited form of jump threading.
Dehao Chenf6c00832016-05-18 19:44:21 +0000779bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
780 TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000781 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +0000782 if (!PredVal)
783 return false; // Not a value comparison in predecessor.
Chris Lattner1cca9592005-02-24 06:17:52 +0000784
785 Value *ThisVal = isValueEqualityComparison(TI);
786 assert(ThisVal && "This isn't a value comparison!!");
Dehao Chenf6c00832016-05-18 19:44:21 +0000787 if (ThisVal != PredVal)
788 return false; // Different predicates.
Chris Lattner1cca9592005-02-24 06:17:52 +0000789
Andrew Trick3051aa12012-08-29 21:46:38 +0000790 // TODO: Preserve branch weight metadata, similarly to how
791 // FoldValueComparisonIntoPredecessors preserves it.
792
Chris Lattner1cca9592005-02-24 06:17:52 +0000793 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000794 std::vector<ValueEqualityComparisonCase> PredCases;
Dehao Chenf6c00832016-05-18 19:44:21 +0000795 BasicBlock *PredDef =
796 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
797 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000798
Chris Lattner1cca9592005-02-24 06:17:52 +0000799 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000800 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000801 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Dehao Chenf6c00832016-05-18 19:44:21 +0000802 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000803
804 // If TI's block is the default block from Pred's comparison, potentially
805 // simplify TI based on this knowledge.
806 if (PredDef == TI->getParent()) {
807 // If we are here, we know that the value is none of those cases listed in
808 // PredCases. If there are any cases in ThisCases that are in PredCases, we
809 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000810 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000811 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000812
Chris Lattner4088e2b2010-12-13 01:47:07 +0000813 if (isa<BranchInst>(TI)) {
814 // Okay, one of the successors of this condbr is dead. Convert it to a
815 // uncond br.
816 assert(ThisCases.size() == 1 && "Branch can only have one case!");
817 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000818 Instruction *NI = Builder.CreateBr(ThisDef);
Dehao Chenf6c00832016-05-18 19:44:21 +0000819 (void)NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000820
Chris Lattner4088e2b2010-12-13 01:47:07 +0000821 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000822 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000823
Chris Lattner4088e2b2010-12-13 01:47:07 +0000824 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000825 << "Through successor TI: " << *TI << "Leaving: " << *NI
826 << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000827
Chris Lattner4088e2b2010-12-13 01:47:07 +0000828 EraseTerminatorInstAndDCECond(TI);
829 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000830 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000831
Chris Lattner4088e2b2010-12-13 01:47:07 +0000832 SwitchInst *SI = cast<SwitchInst>(TI);
833 // Okay, TI has cases that are statically dead, prune them away.
Dehao Chenf6c00832016-05-18 19:44:21 +0000834 SmallPtrSet<Constant *, 16> DeadCases;
Eric Christopherb65acc62012-07-02 23:22:21 +0000835 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
836 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000837
David Greene725c7c32010-01-05 01:26:52 +0000838 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000839 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000840
Manman Ren8691e522012-09-14 21:53:06 +0000841 // Collect branch weights into a vector.
842 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000843 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000844 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
845 if (HasWeight)
846 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
847 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000848 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000849 Weights.push_back(CI->getValue().getZExtValue());
850 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000851 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
852 --i;
Chandler Carruth927d8e62017-04-12 07:27:28 +0000853 if (DeadCases.count(i->getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000854 if (HasWeight) {
Chandler Carruth927d8e62017-04-12 07:27:28 +0000855 std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
Manman Ren8691e522012-09-14 21:53:06 +0000856 Weights.pop_back();
857 }
Chandler Carruth927d8e62017-04-12 07:27:28 +0000858 i->getCaseSuccessor()->removePredecessor(TI->getParent());
Eric Christopherb65acc62012-07-02 23:22:21 +0000859 SI->removeCase(i);
860 }
861 }
Manman Ren97c18762012-10-11 22:28:34 +0000862 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000863 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +0000864 MDBuilder(SI->getParent()->getContext())
865 .createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000866
867 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000868 return true;
869 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000870
Chris Lattner4088e2b2010-12-13 01:47:07 +0000871 // Otherwise, TI's block must correspond to some matched value. Find out
872 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000873 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000874 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000875 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
876 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000877 if (TIV)
Dehao Chenf6c00832016-05-18 19:44:21 +0000878 return false; // Cannot handle multiple values coming to this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000879 TIV = PredCases[i].Value;
880 }
881 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000882
883 // Okay, we found the one constant that our value can be if we get into TI's
884 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000885 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000886 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
887 if (ThisCases[i].Value == TIV) {
888 TheRealDest = ThisCases[i].Dest;
889 break;
890 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000891
892 // If not handled by any explicit cases, it is handled by the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +0000893 if (!TheRealDest)
894 TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000895
896 // Remove PHI node entries for dead edges.
897 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000898 for (BasicBlock *Succ : successors(TIBB))
899 if (Succ != CheckEdge)
900 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000901 else
Craig Topperf40110f2014-04-25 05:29:35 +0000902 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000903
904 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000905 Instruction *NI = Builder.CreateBr(TheRealDest);
Dehao Chenf6c00832016-05-18 19:44:21 +0000906 (void)NI;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000907
908 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000909 << "Through successor TI: " << *TI << "Leaving: " << *NI
910 << "\n");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000911
912 EraseTerminatorInstAndDCECond(TI);
913 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000914}
915
Dale Johannesen7f99d222009-03-12 21:01:11 +0000916namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000917
Dehao Chenf6c00832016-05-18 19:44:21 +0000918/// This class implements a stable ordering of constant
919/// integers that does not depend on their address. This is important for
920/// applications that sort ConstantInt's to ensure uniqueness.
921struct ConstantIntOrdering {
922 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
923 return LHS->getValue().ult(RHS->getValue());
924 }
925};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000926
927} // end anonymous namespace
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000928
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000929static int ConstantIntSortPredicate(ConstantInt *const *P1,
930 ConstantInt *const *P2) {
931 const ConstantInt *LHS = *P1;
932 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000933 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000934 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000935 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000936}
937
Dehao Chenf6c00832016-05-18 19:44:21 +0000938static inline bool HasBranchWeights(const Instruction *I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000939 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000940 if (ProfMD && ProfMD->getOperand(0))
Dehao Chenf6c00832016-05-18 19:44:21 +0000941 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
Andrew Trick3051aa12012-08-29 21:46:38 +0000942 return MDS->getString().equals("branch_weights");
943
944 return false;
945}
946
Manman Ren571d9e42012-09-11 17:43:35 +0000947/// Get Weights of a given TerminatorInst, the default weight is at the front
948/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
949/// metadata.
950static void GetBranchWeights(TerminatorInst *TI,
951 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000952 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000953 assert(MD);
954 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000955 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000956 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000957 }
958
Manman Ren571d9e42012-09-11 17:43:35 +0000959 // If TI is a conditional eq, the default case is the false case,
960 // and the corresponding branch-weight data is at index 2. We swap the
961 // default weight to be the first entry.
Dehao Chenf6c00832016-05-18 19:44:21 +0000962 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Manman Ren571d9e42012-09-11 17:43:35 +0000963 assert(Weights.size() == 2);
964 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
965 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
966 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000967 }
968}
969
Sanjay Patel84a0bf62016-05-06 17:51:37 +0000970/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000971static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000972 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
973 if (Max > UINT_MAX) {
974 unsigned Offset = 32 - countLeadingZeros(Max);
975 for (uint64_t &I : Weights)
976 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000977 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000978}
979
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000980/// The specified terminator is a value equality comparison instruction
981/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000982/// See if any of the predecessors of the terminator block are value comparisons
983/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000984bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
985 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000986 BasicBlock *BB = TI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000987 Value *CV = isValueEqualityComparison(TI); // CondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000988 assert(CV && "Not a comparison?");
989 bool Changed = false;
990
Dehao Chenf6c00832016-05-18 19:44:21 +0000991 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000992 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000993 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000994
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000995 // See if the predecessor is a comparison with the same value.
996 TerminatorInst *PTI = Pred->getTerminator();
Dehao Chenf6c00832016-05-18 19:44:21 +0000997 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000998
James Molloye6566422016-09-01 07:45:25 +0000999 if (PCV == CV && TI != PTI) {
James Molloy21744682016-09-01 09:01:34 +00001000 SmallSetVector<BasicBlock*, 4> FailBlocks;
James Molloye6566422016-09-01 07:45:25 +00001001 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1002 for (auto *Succ : FailBlocks) {
Benjamin Kramer46f5e2c2017-03-24 14:15:35 +00001003 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
James Molloye6566422016-09-01 07:45:25 +00001004 return false;
1005 }
1006 }
1007
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001008 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +00001009 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001010 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1011
Eric Christopherb65acc62012-07-02 23:22:21 +00001012 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001013 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1014
1015 // Based on whether the default edge from PTI goes to BB or not, fill in
1016 // PredCases and PredDefault with the new switch cases we would like to
1017 // build.
Dehao Chenf6c00832016-05-18 19:44:21 +00001018 SmallVector<BasicBlock *, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001019
Andrew Trick3051aa12012-08-29 21:46:38 +00001020 // Update the branch weight metadata along the way
1021 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +00001022 bool PredHasWeights = HasBranchWeights(PTI);
1023 bool SuccHasWeights = HasBranchWeights(TI);
1024
Manman Ren5e5049d2012-09-14 19:05:19 +00001025 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001026 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001027 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001028 if (Weights.size() != 1 + PredCases.size())
1029 PredHasWeights = SuccHasWeights = false;
1030 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +00001031 // If there are no predecessor weights but there are successor weights,
1032 // populate Weights with 1, which will later be scaled to the sum of
1033 // successor's weights
1034 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001035
Manman Ren571d9e42012-09-11 17:43:35 +00001036 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +00001037 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001038 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001039 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001040 if (SuccWeights.size() != 1 + BBCases.size())
1041 PredHasWeights = SuccHasWeights = false;
1042 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +00001043 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001044
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001045 if (PredDefault == BB) {
1046 // If this is the default destination from PTI, only the edges in TI
1047 // that don't occur in PTI, or that branch to BB will be activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001048 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001049 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1050 if (PredCases[i].Dest != BB)
1051 PTIHandled.insert(PredCases[i].Value);
1052 else {
1053 // The default destination is BB, we don't need explicit targets.
1054 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001055
Manman Ren571d9e42012-09-11 17:43:35 +00001056 if (PredHasWeights || SuccHasWeights) {
1057 // Increase weight for the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +00001058 Weights[0] += Weights[i + 1];
1059 std::swap(Weights[i + 1], Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001060 Weights.pop_back();
1061 }
1062
Eric Christopherb65acc62012-07-02 23:22:21 +00001063 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001064 --i;
1065 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001066 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001067
Eric Christopherb65acc62012-07-02 23:22:21 +00001068 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001069 if (PredDefault != BBDefault) {
1070 PredDefault->removePredecessor(Pred);
1071 PredDefault = BBDefault;
1072 NewSuccessors.push_back(BBDefault);
1073 }
Andrew Trick3051aa12012-08-29 21:46:38 +00001074
Manman Ren571d9e42012-09-11 17:43:35 +00001075 unsigned CasesFromPred = Weights.size();
1076 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +00001077 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1078 if (!PTIHandled.count(BBCases[i].Value) &&
1079 BBCases[i].Dest != BBDefault) {
1080 PredCases.push_back(BBCases[i]);
1081 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +00001082 if (SuccHasWeights || PredHasWeights) {
1083 // The default weight is at index 0, so weight for the ith case
1084 // should be at index i+1. Scale the cases from successor by
1085 // PredDefaultWeight (Weights[0]).
Dehao Chenf6c00832016-05-18 19:44:21 +00001086 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1087 ValidTotalSuccWeight += SuccWeights[i + 1];
Andrew Trick3051aa12012-08-29 21:46:38 +00001088 }
Eric Christopherb65acc62012-07-02 23:22:21 +00001089 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001090
Manman Ren571d9e42012-09-11 17:43:35 +00001091 if (SuccHasWeights || PredHasWeights) {
1092 ValidTotalSuccWeight += SuccWeights[0];
1093 // Scale the cases from predecessor by ValidTotalSuccWeight.
1094 for (unsigned i = 1; i < CasesFromPred; ++i)
1095 Weights[i] *= ValidTotalSuccWeight;
1096 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1097 Weights[0] *= SuccWeights[0];
1098 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001099 } else {
1100 // If this is not the default destination from PSI, only the edges
1101 // in SI that occur in PSI with a destination of BB will be
1102 // activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001103 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1104 std::map<ConstantInt *, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001105 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1106 if (PredCases[i].Dest == BB) {
1107 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +00001108
1109 if (PredHasWeights || SuccHasWeights) {
Dehao Chenf6c00832016-05-18 19:44:21 +00001110 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1111 std::swap(Weights[i + 1], Weights.back());
Manman Rend81b8e82012-09-14 17:29:56 +00001112 Weights.pop_back();
1113 }
1114
Eric Christopherb65acc62012-07-02 23:22:21 +00001115 std::swap(PredCases[i], PredCases.back());
1116 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001117 --i;
1118 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001119 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001120
1121 // Okay, now we know which constants were sent to BB from the
1122 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +00001123 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1124 if (PTIHandled.count(BBCases[i].Value)) {
1125 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +00001126 if (PredHasWeights || SuccHasWeights)
1127 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001128 PredCases.push_back(BBCases[i]);
1129 NewSuccessors.push_back(BBCases[i].Dest);
Dehao Chenf6c00832016-05-18 19:44:21 +00001130 PTIHandled.erase(
1131 BBCases[i].Value); // This constant is taken care of
Eric Christopherb65acc62012-07-02 23:22:21 +00001132 }
1133
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001134 // If there are any constants vectored to BB that TI doesn't handle,
1135 // they must go to the default destination of TI.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001136 for (ConstantInt *I : PTIHandled) {
Andrew Trick90f50292012-11-15 18:40:29 +00001137 if (PredHasWeights || SuccHasWeights)
Benjamin Kramer135f7352016-06-26 12:28:59 +00001138 Weights.push_back(WeightsForHandled[I]);
1139 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001140 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001141 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001142 }
1143
1144 // Okay, at this point, we know which new successor Pred will get. Make
1145 // sure we update the number of entries in the PHI nodes for these
1146 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001147 for (BasicBlock *NewSuccessor : NewSuccessors)
1148 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001149
Devang Patel58380552011-05-18 20:53:17 +00001150 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001151 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001152 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001153 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001154 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001155 }
1156
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001157 // Now that the successors are updated, create the new Switch instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001158 SwitchInst *NewSI =
1159 Builder.CreateSwitch(CV, PredDefault, PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001160 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001161 for (ValueEqualityComparisonCase &V : PredCases)
1162 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001163
Andrew Trick3051aa12012-08-29 21:46:38 +00001164 if (PredHasWeights || SuccHasWeights) {
1165 // Halve the weights if any of them cannot fit in an uint32_t
1166 FitWeights(Weights);
1167
1168 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1169
Dehao Chenf6c00832016-05-18 19:44:21 +00001170 NewSI->setMetadata(
1171 LLVMContext::MD_prof,
1172 MDBuilder(BB->getContext()).createBranchWeights(MDWeights));
Andrew Trick3051aa12012-08-29 21:46:38 +00001173 }
1174
Eli Friedmancb61afb2008-12-16 20:54:32 +00001175 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001176
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001177 // Okay, last check. If BB is still a successor of PSI, then we must
1178 // have an infinite loop case. If so, add an infinitely looping block
1179 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001180 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001181 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1182 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001183 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001184 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001185 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00001186 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
1187 BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001188 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001189 }
1190 NewSI->setSuccessor(i, InfLoopBlock);
1191 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001192
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001193 Changed = true;
1194 }
1195 }
1196 return Changed;
1197}
1198
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001199// If we would need to insert a select that uses the value of this invoke
1200// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1201// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001202static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1203 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001204 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001205 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001206 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001207 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1208 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1209 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001210 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001211 return false;
1212 }
1213 }
1214 }
1215 return true;
1216}
1217
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001218static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1219
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001220/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1221/// in the two blocks up into the branch block. The caller of this function
1222/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001223static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001224 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001225 // This does very trivial matching, with limited scanning, to find identical
1226 // instructions in the two blocks. In particular, we don't want to get into
1227 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1228 // such, we currently just scan for obviously identical instructions in an
1229 // identical order.
Dehao Chenf6c00832016-05-18 19:44:21 +00001230 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1231 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
Chris Lattner389cfac2004-11-30 00:29:14 +00001232
Devang Patelf10e2872009-02-04 00:03:08 +00001233 BasicBlock::iterator BB1_Itr = BB1->begin();
1234 BasicBlock::iterator BB2_Itr = BB2->begin();
1235
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001236 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001237 // Skip debug info if it is not identical.
1238 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1239 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1240 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1241 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001242 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001243 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001244 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001245 }
Devang Patele48ddf82011-04-07 00:30:15 +00001246 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001247 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001248 return false;
1249
Chris Lattner389cfac2004-11-30 00:29:14 +00001250 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001251
David Majnemerc82f27a2013-06-03 20:43:12 +00001252 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001253 do {
1254 // If we are hoisting the terminator instruction, don't move one (making a
1255 // broken BB), instead clone it, and remove BI.
1256 if (isa<TerminatorInst>(I1))
1257 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001258
Chad Rosier54390052015-02-23 19:15:16 +00001259 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1260 return Changed;
1261
Chris Lattner389cfac2004-11-30 00:29:14 +00001262 // For a normal instruction, we just move one to right before the branch,
1263 // then replace all uses of the other with the first. Finally, we remove
1264 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001265 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001266 if (!I2->use_empty())
1267 I2->replaceAllUsesWith(I1);
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +00001268 I1->andIRFlags(I2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001269 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1270 LLVMContext::MD_range,
1271 LLVMContext::MD_fpmath,
1272 LLVMContext::MD_invariant_load,
1273 LLVMContext::MD_nonnull,
1274 LLVMContext::MD_invariant_group,
1275 LLVMContext::MD_align,
1276 LLVMContext::MD_dereferenceable,
1277 LLVMContext::MD_dereferenceable_or_null,
1278 LLVMContext::MD_mem_parallel_loop_access};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001279 combineMetadata(I1, I2, KnownIDs);
Dehao Chen87823f82016-09-08 21:53:33 +00001280
Robert Lougherb0124c12017-01-12 21:11:09 +00001281 // I1 and I2 are being combined into a single instruction. Its debug
1282 // location is the merged locations of the original instructions.
1283 if (!isa<CallInst>(I1))
Andrea Di Biagiof20c57e2016-12-15 20:01:26 +00001284 I1->setDebugLoc(
1285 DILocation::getMergedLocation(I1->getDebugLoc(), I2->getDebugLoc()));
Taewook Oh505a25a2017-01-28 07:05:43 +00001286
Chris Lattnerd7beca32010-12-14 06:17:25 +00001287 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001288 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001289
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001290 I1 = &*BB1_Itr++;
1291 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001292 // Skip debug info if it is not identical.
1293 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1294 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1295 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1296 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001297 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001298 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001299 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001300 }
Devang Patele48ddf82011-04-07 00:30:15 +00001301 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001302
1303 return true;
1304
1305HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001306 // It may not be possible to hoist an invoke.
1307 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001308 return Changed;
1309
Sanjay Patel5781d842016-03-12 16:52:17 +00001310 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001311 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001312 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001313 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1314 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1315 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1316 if (BB1V == BB2V)
1317 continue;
1318
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001319 // Check for passingValueIsAlwaysUndefined here because we would rather
1320 // eliminate undefined control flow then converting it to a select.
1321 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1322 passingValueIsAlwaysUndefined(BB2V, PN))
Dehao Chenf6c00832016-05-18 19:44:21 +00001323 return Changed;
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001324
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001325 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001326 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001327 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001328 return Changed;
1329 }
1330 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001331
Chris Lattner389cfac2004-11-30 00:29:14 +00001332 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001333 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001334 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001335 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001336 I1->replaceAllUsesWith(NT);
1337 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001338 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001339 }
1340
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001341 IRBuilder<NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001342 // Hoisting one of the terminators from our successor is a great thing.
1343 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1344 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1345 // nodes, so we insert select instruction to compute the final result.
Dehao Chenf6c00832016-05-18 19:44:21 +00001346 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001347 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001348 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001349 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001350 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001351 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1352 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001353 if (BB1V == BB2V)
1354 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001355
Chris Lattner4088e2b2010-12-13 01:47:07 +00001356 // These values do not agree. Insert a select instruction before NT
1357 // that determines the right value.
1358 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001359 if (!SI)
Dehao Chenf6c00832016-05-18 19:44:21 +00001360 SI = cast<SelectInst>(
1361 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1362 BB1V->getName() + "." + BB2V->getName(), BI));
Devang Patel1407fb42011-05-19 20:52:46 +00001363
Chris Lattner4088e2b2010-12-13 01:47:07 +00001364 // Make the PHI node use the select for all incoming values for BB1/BB2
1365 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1366 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1367 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001368 }
1369 }
1370
1371 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001372 for (BasicBlock *Succ : successors(BB1))
1373 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001374
Eli Friedmancb61afb2008-12-16 20:54:32 +00001375 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001376 return true;
1377}
1378
James Molloyeec6df32016-09-01 10:44:35 +00001379// All instructions in Insts belong to different blocks that all unconditionally
1380// branch to a common successor. Analyze each instruction and return true if it
1381// would be possible to sink them into their successor, creating one common
1382// instruction instead. For every value that would be required to be provided by
1383// PHI node (because an operand varies in each input block), add to PHIOperands.
1384static bool canSinkInstructions(
1385 ArrayRef<Instruction *> Insts,
1386 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
James Molloy5bf21142016-08-22 19:07:15 +00001387 // Prune out obviously bad instructions to move. Any non-store instruction
1388 // must have exactly one use, and we check later that use is by a single,
1389 // common PHI instruction in the successor.
1390 for (auto *I : Insts) {
1391 // These instructions may change or break semantics if moved.
1392 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1393 I->getType()->isTokenTy())
1394 return false;
Akira Hatanaka4ec7b202017-01-25 06:21:51 +00001395
1396 // Conservatively return false if I is an inline-asm instruction. Sinking
1397 // and merging inline-asm instructions can potentially create arguments
1398 // that cannot satisfy the inline-asm constraints.
1399 if (const auto *C = dyn_cast<CallInst>(I))
1400 if (C->isInlineAsm())
1401 return false;
1402
James Molloy5bf21142016-08-22 19:07:15 +00001403 // Everything must have only one use too, apart from stores which
1404 // have no uses.
1405 if (!isa<StoreInst>(I) && !I->hasOneUse())
1406 return false;
1407 }
1408
1409 const Instruction *I0 = Insts.front();
1410 for (auto *I : Insts)
1411 if (!I->isSameOperationAs(I0))
1412 return false;
1413
James Molloyeec6df32016-09-01 10:44:35 +00001414 // All instructions in Insts are known to be the same opcode. If they aren't
1415 // stores, check the only user of each is a PHI or in the same block as the
1416 // instruction, because if a user is in the same block as an instruction
1417 // we're contemplating sinking, it must already be determined to be sinkable.
James Molloy5bf21142016-08-22 19:07:15 +00001418 if (!isa<StoreInst>(I0)) {
1419 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
James Molloy6c009c12016-09-07 09:01:22 +00001420 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
Eric Liu8c7d28b2017-03-15 15:29:42 +00001421 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
James Molloyeec6df32016-09-01 10:44:35 +00001422 auto *U = cast<Instruction>(*I->user_begin());
Eric Liu8c7d28b2017-03-15 15:29:42 +00001423 return (PNUse &&
1424 PNUse->getParent() == Succ &&
1425 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1426 U->getParent() == I->getParent();
James Molloy5bf21142016-08-22 19:07:15 +00001427 }))
1428 return false;
1429 }
1430
Aditya Kumar24f6ad512017-03-16 14:09:18 +00001431 // Because SROA can't handle speculating stores of selects, try not
1432 // to sink loads or stores of allocas when we'd have to create a PHI for
1433 // the address operand. Also, because it is likely that loads or stores
1434 // of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
1435 // This can cause code churn which can have unintended consequences down
1436 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1437 // FIXME: This is a workaround for a deficiency in SROA - see
1438 // https://llvm.org/bugs/show_bug.cgi?id=30188
1439 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1440 return isa<AllocaInst>(I->getOperand(1));
1441 }))
1442 return false;
1443 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1444 return isa<AllocaInst>(I->getOperand(0));
1445 }))
1446 return false;
1447
James Molloy5bf21142016-08-22 19:07:15 +00001448 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1449 if (I0->getOperand(OI)->getType()->isTokenTy())
1450 // Don't touch any operand of token type.
1451 return false;
James Molloy104370a2016-09-11 09:00:03 +00001452
James Molloy5bf21142016-08-22 19:07:15 +00001453 auto SameAsI0 = [&I0, OI](const Instruction *I) {
James Molloyeec6df32016-09-01 10:44:35 +00001454 assert(I->getNumOperands() == I0->getNumOperands());
1455 return I->getOperand(OI) == I0->getOperand(OI);
James Molloy5bf21142016-08-22 19:07:15 +00001456 };
1457 if (!all_of(Insts, SameAsI0)) {
1458 if (!canReplaceOperandWithVariable(I0, OI))
1459 // We can't create a PHI from this GEP.
1460 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001461 // Don't create indirect calls! The called value is the final operand.
1462 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
James Molloy5bf21142016-08-22 19:07:15 +00001463 // FIXME: if the call was *already* indirect, we should do this.
1464 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001465 }
James Molloyeec6df32016-09-01 10:44:35 +00001466 for (auto *I : Insts)
1467 PHIOperands[I].push_back(I->getOperand(OI));
James Molloy5bf21142016-08-22 19:07:15 +00001468 }
1469 }
1470 return true;
1471}
1472
1473// Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1474// instruction of every block in Blocks to their common successor, commoning
1475// into one instruction.
James Molloyeec6df32016-09-01 10:44:35 +00001476static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
James Molloy5bf21142016-08-22 19:07:15 +00001477 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1478
1479 // canSinkLastInstruction returning true guarantees that every block has at
1480 // least one non-terminator instruction.
1481 SmallVector<Instruction*,4> Insts;
Dehao Chen018a3af2016-10-17 19:28:44 +00001482 for (auto *BB : Blocks) {
1483 Instruction *I = BB->getTerminator();
1484 do {
1485 I = I->getPrevNode();
1486 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1487 if (!isa<DbgInfoIntrinsic>(I))
1488 Insts.push_back(I);
1489 }
James Molloy5bf21142016-08-22 19:07:15 +00001490
James Molloyeec6df32016-09-01 10:44:35 +00001491 // The only checking we need to do now is that all users of all instructions
1492 // are the same PHI node. canSinkLastInstruction should have checked this but
1493 // it is slightly over-aggressive - it gets confused by commutative instructions
1494 // so double-check it here.
James Molloy5bf21142016-08-22 19:07:15 +00001495 Instruction *I0 = Insts.front();
James Molloyeec6df32016-09-01 10:44:35 +00001496 if (!isa<StoreInst>(I0)) {
1497 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1498 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1499 auto *U = cast<Instruction>(*I->user_begin());
1500 return U == PNUse;
1501 }))
1502 return false;
1503 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001504
James Molloyeec6df32016-09-01 10:44:35 +00001505 // We don't need to do any more checking here; canSinkLastInstruction should
1506 // have done it all for us.
James Molloy5bf21142016-08-22 19:07:15 +00001507 SmallVector<Value*, 4> NewOperands;
1508 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1509 // This check is different to that in canSinkLastInstruction. There, we
1510 // cared about the global view once simplifycfg (and instcombine) have
1511 // completed - it takes into account PHIs that become trivially
1512 // simplifiable. However here we need a more local view; if an operand
1513 // differs we create a PHI and rely on instcombine to clean up the very
1514 // small mess we may make.
1515 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1516 return I->getOperand(O) != I0->getOperand(O);
1517 });
1518 if (!NeedPHI) {
1519 NewOperands.push_back(I0->getOperand(O));
1520 continue;
1521 }
1522
1523 // Create a new PHI in the successor block and populate it.
1524 auto *Op = I0->getOperand(O);
1525 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1526 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1527 Op->getName() + ".sink", &BBEnd->front());
1528 for (auto *I : Insts)
1529 PN->addIncoming(I->getOperand(O), I->getParent());
1530 NewOperands.push_back(PN);
1531 }
1532
1533 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1534 // and move it to the start of the successor block.
1535 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1536 I0->getOperandUse(O).set(NewOperands[O]);
1537 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1538
Robert Lougher5bf04162017-01-04 17:40:32 +00001539 // The debug location for the "common" instruction is the merged locations of
1540 // all the commoned instructions. We start with the original location of the
1541 // "common" instruction and iteratively merge each location in the loop below.
Robert Lougher6717a6f2017-01-12 18:33:49 +00001542 const DILocation *Loc = I0->getDebugLoc();
Robert Lougher5bf04162017-01-04 17:40:32 +00001543
1544 // Update metadata and IR flags, and merge debug locations.
James Molloyd13b1232016-08-30 10:56:08 +00001545 for (auto *I : Insts)
James Molloy0efb96a2016-09-19 08:23:08 +00001546 if (I != I0) {
Robert Lougher5bf04162017-01-04 17:40:32 +00001547 Loc = DILocation::getMergedLocation(Loc, I->getDebugLoc());
James Molloyd13b1232016-08-30 10:56:08 +00001548 combineMetadataForCSE(I0, I);
James Molloy0efb96a2016-09-19 08:23:08 +00001549 I0->andIRFlags(I);
1550 }
Robert Lougher5bf04162017-01-04 17:40:32 +00001551 if (!isa<CallInst>(I0))
1552 I0->setDebugLoc(Loc);
James Molloyd13b1232016-08-30 10:56:08 +00001553
James Molloy5bf21142016-08-22 19:07:15 +00001554 if (!isa<StoreInst>(I0)) {
1555 // canSinkLastInstruction checked that all instructions were used by
1556 // one and only one PHI node. Find that now, RAUW it to our common
1557 // instruction and nuke it.
1558 assert(I0->hasOneUse());
1559 auto *PN = cast<PHINode>(*I0->user_begin());
1560 PN->replaceAllUsesWith(I0);
1561 PN->eraseFromParent();
1562 }
1563
1564 // Finally nuke all instructions apart from the common instruction.
1565 for (auto *I : Insts)
1566 if (I != I0)
1567 I->eraseFromParent();
James Molloyeec6df32016-09-01 10:44:35 +00001568
1569 return true;
1570}
1571
1572namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001573
James Molloyeec6df32016-09-01 10:44:35 +00001574 // LockstepReverseIterator - Iterates through instructions
1575 // in a set of blocks in reverse order from the first non-terminator.
1576 // For example (assume all blocks have size n):
1577 // LockstepReverseIterator I([B1, B2, B3]);
1578 // *I-- = [B1[n], B2[n], B3[n]];
1579 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1580 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1581 // ...
1582 class LockstepReverseIterator {
1583 ArrayRef<BasicBlock*> Blocks;
1584 SmallVector<Instruction*,4> Insts;
1585 bool Fail;
1586 public:
1587 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) :
1588 Blocks(Blocks) {
1589 reset();
1590 }
1591
1592 void reset() {
1593 Fail = false;
1594 Insts.clear();
1595 for (auto *BB : Blocks) {
Dehao Chen018a3af2016-10-17 19:28:44 +00001596 Instruction *Inst = BB->getTerminator();
1597 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1598 Inst = Inst->getPrevNode();
1599 if (!Inst) {
1600 // Block wasn't big enough.
1601 Fail = true;
1602 return;
James Molloyeec6df32016-09-01 10:44:35 +00001603 }
Dehao Chen018a3af2016-10-17 19:28:44 +00001604 Insts.push_back(Inst);
James Molloyeec6df32016-09-01 10:44:35 +00001605 }
1606 }
1607
1608 bool isValid() const {
1609 return !Fail;
1610 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001611
James Molloyeec6df32016-09-01 10:44:35 +00001612 void operator -- () {
1613 if (Fail)
1614 return;
1615 for (auto *&Inst : Insts) {
Dehao Chen018a3af2016-10-17 19:28:44 +00001616 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1617 Inst = Inst->getPrevNode();
Benjamin Kramerd8b07972016-10-15 13:15:05 +00001618 // Already at beginning of block.
1619 if (!Inst) {
James Molloyeec6df32016-09-01 10:44:35 +00001620 Fail = true;
1621 return;
1622 }
James Molloyeec6df32016-09-01 10:44:35 +00001623 }
1624 }
1625
1626 ArrayRef<Instruction*> operator * () const {
1627 return Insts;
1628 }
1629 };
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001630
1631} // end anonymous namespace
James Molloy5bf21142016-08-22 19:07:15 +00001632
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001633/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001634/// check whether BBEnd has only two predecessors and the other predecessor
1635/// ends with an unconditional branch. If it is true, sink any common code
1636/// in the two predecessors to BBEnd.
1637static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1638 assert(BI1->isUnconditional());
Manman Ren93ab6492012-09-20 22:37:36 +00001639 BasicBlock *BBEnd = BI1->getSuccessor(0);
1640
James Molloy88cad7e2016-09-01 12:58:13 +00001641 // We support two situations:
1642 // (1) all incoming arcs are unconditional
1643 // (2) one incoming arc is conditional
1644 //
1645 // (2) is very common in switch defaults and
1646 // else-if patterns;
1647 //
1648 // if (a) f(1);
1649 // else if (b) f(2);
1650 //
1651 // produces:
1652 //
1653 // [if]
1654 // / \
1655 // [f(1)] [if]
1656 // | | \
Amaury Sechet2fec7e42017-01-23 15:13:01 +00001657 // | | |
James Molloy88cad7e2016-09-01 12:58:13 +00001658 // | [f(2)]|
1659 // \ | /
1660 // [ end ]
1661 //
1662 // [end] has two unconditional predecessor arcs and one conditional. The
1663 // conditional refers to the implicit empty 'else' arc. This conditional
1664 // arc can also be caused by an empty default block in a switch.
1665 //
1666 // In this case, we attempt to sink code from all *unconditional* arcs.
1667 // If we can sink instructions from these arcs (determined during the scan
1668 // phase below) we insert a common successor for all unconditional arcs and
1669 // connect that to [end], to enable sinking:
1670 //
1671 // [if]
1672 // / \
1673 // [x(1)] [if]
1674 // | | \
1675 // | | \
1676 // | [x(2)] |
1677 // \ / |
1678 // [sink.split] |
1679 // \ /
1680 // [ end ]
1681 //
1682 SmallVector<BasicBlock*,4> UnconditionalPreds;
1683 Instruction *Cond = nullptr;
1684 for (auto *B : predecessors(BBEnd)) {
1685 auto *T = B->getTerminator();
1686 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1687 UnconditionalPreds.push_back(B);
1688 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1689 Cond = T;
1690 else
1691 return false;
1692 }
1693 if (UnconditionalPreds.size() < 2)
James Molloy475f4a72016-08-22 18:13:12 +00001694 return false;
Taewook Oh505a25a2017-01-28 07:05:43 +00001695
Manman Ren93ab6492012-09-20 22:37:36 +00001696 bool Changed = false;
James Molloyeec6df32016-09-01 10:44:35 +00001697 // We take a two-step approach to tail sinking. First we scan from the end of
1698 // each block upwards in lockstep. If the n'th instruction from the end of each
1699 // block can be sunk, those instructions are added to ValuesToSink and we
1700 // carry on. If we can sink an instruction but need to PHI-merge some operands
1701 // (because they're not identical in each instruction) we add these to
1702 // PHIOperands.
1703 unsigned ScanIdx = 0;
1704 SmallPtrSet<Value*,4> InstructionsToSink;
1705 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
James Molloy88cad7e2016-09-01 12:58:13 +00001706 LockstepReverseIterator LRI(UnconditionalPreds);
James Molloyeec6df32016-09-01 10:44:35 +00001707 while (LRI.isValid() &&
1708 canSinkInstructions(*LRI, PHIOperands)) {
1709 DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] << "\n");
1710 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1711 ++ScanIdx;
1712 --LRI;
1713 }
1714
James Molloy18d96e82016-09-11 08:07:30 +00001715 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
James Molloy88cad7e2016-09-01 12:58:13 +00001716 unsigned NumPHIdValues = 0;
1717 for (auto *I : *LRI)
1718 for (auto *V : PHIOperands[I])
1719 if (InstructionsToSink.count(V) == 0)
1720 ++NumPHIdValues;
1721 DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1722 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1723 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1724 NumPHIInsts++;
Taewook Oh505a25a2017-01-28 07:05:43 +00001725
James Molloy88cad7e2016-09-01 12:58:13 +00001726 return NumPHIInsts <= 1;
1727 };
1728
1729 if (ScanIdx > 0 && Cond) {
James Molloy18d96e82016-09-11 08:07:30 +00001730 // Check if we would actually sink anything first! This mutates the CFG and
1731 // adds an extra block. The goal in doing this is to allow instructions that
1732 // couldn't be sunk before to be sunk - obviously, speculatable instructions
1733 // (such as trunc, add) can be sunk and predicated already. So we check that
1734 // we're going to sink at least one non-speculatable instruction.
1735 LRI.reset();
1736 unsigned Idx = 0;
1737 bool Profitable = false;
1738 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1739 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
1740 Profitable = true;
1741 break;
1742 }
1743 --LRI;
1744 ++Idx;
1745 }
1746 if (!Profitable)
James Molloy88cad7e2016-09-01 12:58:13 +00001747 return false;
Taewook Oh505a25a2017-01-28 07:05:43 +00001748
James Molloy88cad7e2016-09-01 12:58:13 +00001749 DEBUG(dbgs() << "SINK: Splitting edge\n");
1750 // We have a conditional edge and we're going to sink some instructions.
1751 // Insert a new block postdominating all blocks we're going to sink from.
1752 if (!SplitBlockPredecessors(BI1->getSuccessor(0), UnconditionalPreds,
1753 ".sink.split"))
1754 // Edges couldn't be split.
1755 return false;
1756 Changed = true;
1757 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001758
James Molloyeec6df32016-09-01 10:44:35 +00001759 // Now that we've analyzed all potential sinking candidates, perform the
1760 // actual sink. We iteratively sink the last non-terminator of the source
1761 // blocks into their common successor unless doing so would require too
1762 // many PHI instructions to be generated (currently only one PHI is allowed
1763 // per sunk instruction).
1764 //
1765 // We can use InstructionsToSink to discount values needing PHI-merging that will
1766 // actually be sunk in a later iteration. This allows us to be more
1767 // aggressive in what we sink. This does allow a false positive where we
1768 // sink presuming a later value will also be sunk, but stop half way through
1769 // and never actually sink it which means we produce more PHIs than intended.
1770 // This is unlikely in practice though.
1771 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1772 DEBUG(dbgs() << "SINK: Sink: "
James Molloy88cad7e2016-09-01 12:58:13 +00001773 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
James Molloyeec6df32016-09-01 10:44:35 +00001774 << "\n");
1775
1776 // Because we've sunk every instruction in turn, the current instruction to
1777 // sink is always at index 0.
James Molloy18d96e82016-09-11 08:07:30 +00001778 LRI.reset();
1779 if (!ProfitableToSinkInstruction(LRI)) {
James Molloyeec6df32016-09-01 10:44:35 +00001780 // Too many PHIs would be created.
James Molloy88cad7e2016-09-01 12:58:13 +00001781 DEBUG(dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
James Molloyeec6df32016-09-01 10:44:35 +00001782 break;
James Molloy88cad7e2016-09-01 12:58:13 +00001783 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001784
James Molloy88cad7e2016-09-01 12:58:13 +00001785 if (!sinkLastInstruction(UnconditionalPreds))
James Molloyeec6df32016-09-01 10:44:35 +00001786 return Changed;
Manman Ren93ab6492012-09-20 22:37:36 +00001787 NumSinkCommons++;
1788 Changed = true;
1789 }
1790 return Changed;
1791}
1792
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001793/// \brief Determine if we can hoist sink a sole store instruction out of a
1794/// conditional block.
1795///
1796/// We are looking for code like the following:
1797/// BrBB:
1798/// store i32 %add, i32* %arrayidx2
1799/// ... // No other stores or function calls (we could be calling a memory
1800/// ... // function).
1801/// %cmp = icmp ult %x, %y
1802/// br i1 %cmp, label %EndBB, label %ThenBB
1803/// ThenBB:
1804/// store i32 %add5, i32* %arrayidx2
1805/// br label EndBB
1806/// EndBB:
1807/// ...
1808/// We are going to transform this into:
1809/// BrBB:
1810/// store i32 %add, i32* %arrayidx2
1811/// ... //
1812/// %cmp = icmp ult %x, %y
1813/// %add.add5 = select i1 %cmp, i32 %add, %add5
1814/// store i32 %add.add5, i32* %arrayidx2
1815/// ...
1816///
1817/// \return The pointer to the value of the previous store if the store can be
1818/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001819static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1820 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001821 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1822 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001823 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001824
1825 // Volatile or atomic.
1826 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001827 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001828
1829 Value *StorePtr = StoreToHoist->getPointerOperand();
1830
1831 // Look for a store to the same pointer in BrBB.
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001832 unsigned MaxNumInstToLookAt = 9;
David Majnemerd7708772016-06-24 04:05:21 +00001833 for (Instruction &CurI : reverse(*BrBB)) {
1834 if (!MaxNumInstToLookAt)
1835 break;
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001836 // Skip debug info.
1837 if (isa<DbgInfoIntrinsic>(CurI))
1838 continue;
1839 --MaxNumInstToLookAt;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001840
David L Kreitzer96674172016-08-12 21:06:53 +00001841 // Could be calling an instruction that affects memory like free().
David Majnemerd7708772016-06-24 04:05:21 +00001842 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001843 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001844
David Majnemerd7708772016-06-24 04:05:21 +00001845 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1846 // Found the previous store make sure it stores to the same location.
1847 if (SI->getPointerOperand() == StorePtr)
1848 // Found the previous store, return its value operand.
1849 return SI->getValueOperand();
Craig Topperf40110f2014-04-25 05:29:35 +00001850 return nullptr; // Unknown store.
David Majnemerd7708772016-06-24 04:05:21 +00001851 }
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001852 }
1853
Craig Topperf40110f2014-04-25 05:29:35 +00001854 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001855}
1856
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001857/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001858///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001859/// Note that this is a very risky transform currently. Speculating
1860/// instructions like this is most often not desirable. Instead, there is an MI
1861/// pass which can do it with full awareness of the resource constraints.
1862/// However, some cases are "obvious" and we should do directly. An example of
1863/// this is speculating a single, reasonably cheap instruction.
1864///
1865/// There is only one distinct advantage to flattening the CFG at the IR level:
1866/// it makes very common but simplistic optimizations such as are common in
1867/// instcombine and the DAG combiner more powerful by removing CFG edges and
1868/// modeling their effects with easier to reason about SSA value graphs.
1869///
1870///
1871/// An illustration of this transform is turning this IR:
1872/// \code
1873/// BB:
1874/// %cmp = icmp ult %x, %y
1875/// br i1 %cmp, label %EndBB, label %ThenBB
1876/// ThenBB:
1877/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001878/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001879/// EndBB:
1880/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1881/// ...
1882/// \endcode
1883///
1884/// Into this IR:
1885/// \code
1886/// BB:
1887/// %cmp = icmp ult %x, %y
1888/// %sub = sub %x, %y
1889/// %cond = select i1 %cmp, 0, %sub
1890/// ...
1891/// \endcode
1892///
1893/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001894static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001895 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001896 // Be conservative for now. FP select instruction can often be expensive.
1897 Value *BrCond = BI->getCondition();
1898 if (isa<FCmpInst>(BrCond))
1899 return false;
1900
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001901 BasicBlock *BB = BI->getParent();
1902 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1903
1904 // If ThenBB is actually on the false edge of the conditional branch, remember
1905 // to swap the select operands later.
1906 bool Invert = false;
1907 if (ThenBB != BI->getSuccessor(0)) {
1908 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1909 Invert = true;
1910 }
1911 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1912
Chandler Carruthceff2222013-01-25 05:40:09 +00001913 // Keep a count of how many times instructions are used within CondBB when
1914 // they are candidates for sinking into CondBB. Specifically:
1915 // - They are defined in BB, and
1916 // - They have no side effects, and
1917 // - All of their uses are in CondBB.
1918 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1919
Chandler Carruth7481ca82013-01-24 11:52:58 +00001920 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001921 Value *SpeculatedStoreValue = nullptr;
1922 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001923 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001924 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001925 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001926 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001927 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001928 if (isa<DbgInfoIntrinsic>(I))
1929 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001930
Mark Lacey274f48b2015-04-12 18:18:51 +00001931 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001932 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001933 ++SpeculationCost;
1934 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001935 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001936
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001937 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001938 if (!isSafeToSpeculativelyExecute(I) &&
1939 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1940 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001941 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001942 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001943 ComputeSpeculationCost(I, TTI) >
1944 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001945 return false;
1946
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001947 // Store the store speculation candidate.
1948 if (SpeculatedStoreValue)
1949 SpeculatedStore = cast<StoreInst>(I);
1950
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001951 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001952 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001953 // being sunk into the use block.
Dehao Chenf6c00832016-05-18 19:44:21 +00001954 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001955 Instruction *OpI = dyn_cast<Instruction>(*i);
Dehao Chenf6c00832016-05-18 19:44:21 +00001956 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
Chandler Carruthceff2222013-01-25 05:40:09 +00001957 continue; // Not a candidate for sinking.
1958
1959 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001960 }
1961 }
Evan Cheng89200c92008-06-07 08:52:29 +00001962
Chandler Carruthceff2222013-01-25 05:40:09 +00001963 // Consider any sink candidates which are only used in CondBB as costs for
1964 // speculation. Note, while we iterate over a DenseMap here, we are summing
1965 // and so iteration order isn't significant.
Dehao Chenf6c00832016-05-18 19:44:21 +00001966 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1967 I = SinkCandidateUseCounts.begin(),
1968 E = SinkCandidateUseCounts.end();
Chandler Carruthceff2222013-01-25 05:40:09 +00001969 I != E; ++I)
1970 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001971 ++SpeculationCost;
1972 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001973 return false;
1974 }
1975
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001976 // Check that the PHI nodes can be converted to selects.
1977 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001978 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001979 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001980 Value *OrigV = PN->getIncomingValueForBlock(BB);
1981 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001982
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001983 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001984 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001985 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001986 continue;
1987
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001988 // Don't convert to selects if we could remove undefined behavior instead.
1989 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1990 passingValueIsAlwaysUndefined(ThenV, PN))
1991 return false;
1992
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001993 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001994 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1995 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1996 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001997 continue; // Known safe and cheap.
1998
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001999 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2000 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00002001 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002002 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
2003 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00002004 unsigned MaxCost =
2005 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
James Molloy7c336572015-02-11 12:15:41 +00002006 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00002007 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002008
Chandler Carruth01bffaa2013-01-24 12:05:17 +00002009 // Account for the cost of an unfolded ConstantExpr which could end up
2010 // getting expanded into Instructions.
2011 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00002012 // constant expression.
2013 ++SpeculationCost;
2014 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002015 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00002016 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002017
2018 // If there are no PHIs to process, bail early. This helps ensure idempotence
2019 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002020 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002021 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002022
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002023 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00002024 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00002025
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002026 // Insert a select of the value of the speculated store.
2027 if (SpeculatedStoreValue) {
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002028 IRBuilder<NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002029 Value *TrueV = SpeculatedStore->getValueOperand();
2030 Value *FalseV = SpeculatedStoreValue;
2031 if (Invert)
2032 std::swap(TrueV, FalseV);
Sanjay Patel796db352016-03-26 23:30:50 +00002033 Value *S = Builder.CreateSelect(
2034 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002035 SpeculatedStore->setOperand(0, S);
Taewook Oh505a25a2017-01-28 07:05:43 +00002036 SpeculatedStore->setDebugLoc(
2037 DILocation::getMergedLocation(
2038 BI->getDebugLoc(), SpeculatedStore->getDebugLoc()));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002039 }
2040
Igor Laevsky7310c682015-11-18 14:50:18 +00002041 // Metadata can be dependent on the condition we are hoisting above.
2042 // Conservatively strip all metadata on the instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002043 for (auto &I : *ThenBB)
Igor Laevsky7310c682015-11-18 14:50:18 +00002044 I.dropUnknownNonDebugMetadata();
2045
Chandler Carruth7481ca82013-01-24 11:52:58 +00002046 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002047 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2048 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00002049
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002050 // Insert selects and rewrite the PHI operands.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002051 IRBuilder<NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002052 for (BasicBlock::iterator I = EndBB->begin();
2053 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2054 unsigned OrigI = PN->getBasicBlockIndex(BB);
2055 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
2056 Value *OrigV = PN->getIncomingValue(OrigI);
2057 Value *ThenV = PN->getIncomingValue(ThenI);
2058
2059 // Skip PHIs which are trivial.
2060 if (OrigV == ThenV)
2061 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00002062
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002063 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002064 // false value is the preexisting value. Swap them if the branch
2065 // destinations were inverted.
2066 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002067 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002068 std::swap(TrueV, FalseV);
Sanjay Patelf11ab052016-04-15 15:32:12 +00002069 Value *V = Builder.CreateSelect(
2070 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002071 PN->setIncomingValue(OrigI, V);
2072 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00002073 }
2074
Evan Cheng89553cc2008-06-12 21:15:59 +00002075 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00002076 return true;
2077}
2078
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002079/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002080static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2081 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00002082 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002083
Devang Patel84fceff2009-03-10 18:00:05 +00002084 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00002085 if (isa<DbgInfoIntrinsic>(BBI))
2086 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00002087 if (Size > 10)
2088 return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00002089 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002090
Dale Johannesened6f5a82009-03-12 23:18:09 +00002091 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00002092 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002093 for (User *U : BBI->users()) {
2094 Instruction *UI = cast<Instruction>(U);
Dehao Chenf6c00832016-05-18 19:44:21 +00002095 if (UI->getParent() != BB || isa<PHINode>(UI))
2096 return false;
Chris Lattner6c701062005-09-20 01:48:40 +00002097 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002098
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002099 // Looks ok, continue checking.
2100 }
Chris Lattner6c701062005-09-20 01:48:40 +00002101
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002102 return true;
2103}
2104
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002105/// If we have a conditional branch on a PHI node value that is defined in the
2106/// same block as the branch and if any PHI entries are constants, thread edges
2107/// corresponding to that entry to be branches to their ultimate destination.
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002108static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
2109 AssumptionCache *AC) {
Chris Lattner748f9032005-09-19 23:49:37 +00002110 BasicBlock *BB = BI->getParent();
2111 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00002112 // NOTE: we currently cannot transform this case if the PHI node is used
2113 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002114 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2115 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002116
Chris Lattner748f9032005-09-19 23:49:37 +00002117 // Degenerate case of a single entry PHI.
2118 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00002119 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002120 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00002121 }
2122
2123 // Now we know that this block has multiple preds and two succs.
Dehao Chenf6c00832016-05-18 19:44:21 +00002124 if (!BlockIsSimpleEnoughToThreadThrough(BB))
2125 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002126
Justin Lebardb639492016-02-12 21:01:36 +00002127 // Can't fold blocks that contain noduplicate or convergent calls.
David Majnemer0a16c222016-08-11 21:15:00 +00002128 if (any_of(*BB, [](const Instruction &I) {
Justin Lebardb639492016-02-12 21:01:36 +00002129 const CallInst *CI = dyn_cast<CallInst>(&I);
2130 return CI && (CI->cannotDuplicate() || CI->isConvergent());
2131 }))
2132 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00002133
Chris Lattner748f9032005-09-19 23:49:37 +00002134 // Okay, this is a simple enough basic block. See if any phi values are
2135 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002136 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002137 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Dehao Chenf6c00832016-05-18 19:44:21 +00002138 if (!CB || !CB->getType()->isIntegerTy(1))
2139 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002140
Chris Lattner4088e2b2010-12-13 01:47:07 +00002141 // Okay, we now know that all edges from PredBB should be revectored to
2142 // branch to RealDest.
2143 BasicBlock *PredBB = PN->getIncomingBlock(i);
2144 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002145
Dehao Chenf6c00832016-05-18 19:44:21 +00002146 if (RealDest == BB)
2147 continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00002148 // Skip if the predecessor's terminator is an indirect branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00002149 if (isa<IndirectBrInst>(PredBB->getTerminator()))
2150 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002151
Chris Lattner4088e2b2010-12-13 01:47:07 +00002152 // The dest block might have PHI nodes, other predecessors and other
2153 // difficult cases. Instead of being smart about this, just insert a new
2154 // block that jumps to the destination block, effectively splitting
2155 // the edge we are about to create.
Dehao Chenf6c00832016-05-18 19:44:21 +00002156 BasicBlock *EdgeBB =
2157 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2158 RealDest->getParent(), RealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002159 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002160
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002161 // Update PHI nodes.
2162 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002163
2164 // BB may have instructions that are being threaded over. Clone these
2165 // instructions into EdgeBB. We know that there will be no uses of the
2166 // cloned instructions outside of EdgeBB.
2167 BasicBlock::iterator InsertPt = EdgeBB->begin();
Dehao Chenf6c00832016-05-18 19:44:21 +00002168 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002169 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2170 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2171 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2172 continue;
2173 }
2174 // Clone the instruction.
2175 Instruction *N = BBI->clone();
Dehao Chenf6c00832016-05-18 19:44:21 +00002176 if (BBI->hasName())
2177 N->setName(BBI->getName() + ".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178
Chris Lattner4088e2b2010-12-13 01:47:07 +00002179 // Update operands due to translation.
Dehao Chenf6c00832016-05-18 19:44:21 +00002180 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2181 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002182 if (PI != TranslateMap.end())
2183 *i = PI->second;
2184 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002185
Chris Lattner4088e2b2010-12-13 01:47:07 +00002186 // Check for trivial simplification.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002187 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
David Majnemerb8da3a22016-06-25 00:04:10 +00002188 if (!BBI->use_empty())
2189 TranslateMap[&*BBI] = V;
2190 if (!N->mayHaveSideEffects()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00002191 N->deleteValue(); // Instruction folded away, don't need actual inst
David Majnemerb8da3a22016-06-25 00:04:10 +00002192 N = nullptr;
2193 }
Chris Lattner4088e2b2010-12-13 01:47:07 +00002194 } else {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002195 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002196 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002197 }
David Majnemerb8da3a22016-06-25 00:04:10 +00002198 // Insert the new instruction into its new home.
2199 if (N)
2200 EdgeBB->getInstList().insert(InsertPt, N);
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002201
2202 // Register the new instruction with the assumption cache if necessary.
2203 if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2204 if (II->getIntrinsicID() == Intrinsic::assume)
2205 AC->registerAssumption(II);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002206 }
2207
2208 // Loop over all of the edges from PredBB to BB, changing them to branch
2209 // to EdgeBB instead.
2210 TerminatorInst *PredBBTI = PredBB->getTerminator();
2211 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2212 if (PredBBTI->getSuccessor(i) == BB) {
2213 BB->removePredecessor(PredBB);
2214 PredBBTI->setSuccessor(i, EdgeBB);
2215 }
Bill Wendling4f163df2011-06-04 09:42:04 +00002216
Chris Lattner4088e2b2010-12-13 01:47:07 +00002217 // Recurse, simplifying any other constants.
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002218 return FoldCondBranchOnPHI(BI, DL, AC) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00002219 }
Chris Lattner748f9032005-09-19 23:49:37 +00002220
2221 return false;
2222}
2223
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002224/// Given a BB that starts with the specified two-entry PHI node,
2225/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002226static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2227 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002228 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2229 // statement", which has a very simple dominance structure. Basically, we
2230 // are trying to find the condition that is being branched on, which
2231 // subsequently causes this merge to happen. We really want control
2232 // dependence information for this check, but simplifycfg can't keep it up
2233 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002234 BasicBlock *BB = PN->getParent();
2235 BasicBlock *IfTrue, *IfFalse;
2236 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00002237 if (!IfCond ||
2238 // Don't bother if the branch will be constant folded trivially.
2239 isa<ConstantInt>(IfCond))
2240 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002241
Chris Lattner95adf8f12006-11-18 19:19:36 +00002242 // Okay, we found that we can merge this two-entry phi node into a select.
2243 // Doing so would require us to fold *all* two entry phi nodes in this block.
2244 // At some point this becomes non-profitable (particularly if the target
2245 // doesn't support cmov's). Only do this transformation if there are two or
2246 // fewer PHI nodes in this block.
2247 unsigned NumPhis = 0;
2248 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2249 if (NumPhis > 2)
2250 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002251
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002252 // Loop over the PHI's seeing if we can promote them all to select
2253 // instructions. While we are at it, keep track of the instructions
2254 // that need to be moved to the dominating block.
Dehao Chenf6c00832016-05-18 19:44:21 +00002255 SmallPtrSet<Instruction *, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00002256 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2257 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00002258 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2259 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002260
Chris Lattner7499b452010-12-14 08:46:09 +00002261 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2262 PHINode *PN = cast<PHINode>(II++);
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002263 if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00002264 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00002265 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00002266 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002267 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002268
Peter Collingbournee3511e12011-04-29 18:47:31 +00002269 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002270 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00002271 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002272 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00002273 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002274 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002275
Sylvestre Ledru35521e22012-07-23 08:51:15 +00002276 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00002277 // we ran out of PHIs then we simplified them all.
2278 PN = dyn_cast<PHINode>(BB->begin());
Dehao Chenf6c00832016-05-18 19:44:21 +00002279 if (!PN)
2280 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002281
Chris Lattner7499b452010-12-14 08:46:09 +00002282 // Don't fold i1 branches on PHIs which contain binary operators. These can
2283 // often be turned into switches and other things.
2284 if (PN->getType()->isIntegerTy(1) &&
2285 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2286 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2287 isa<BinaryOperator>(IfCond)))
2288 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002289
Sanjay Patel2e002772016-03-12 18:05:53 +00002290 // If all PHI nodes are promotable, check to make sure that all instructions
2291 // in the predecessor blocks can be promoted as well. If not, we won't be able
2292 // to get rid of the control flow, so it's not worth promoting to select
2293 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00002294 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002295 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2296 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2297 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002298 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002299 } else {
2300 DomBlock = *pred_begin(IfBlock1);
Dehao Chenf6c00832016-05-18 19:44:21 +00002301 for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2302 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002303 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002304 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002305 // Because of this, we won't be able to get rid of the control flow, so
2306 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002307 return false;
2308 }
2309 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002310
Chris Lattner9ac168d2010-12-14 07:41:39 +00002311 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002312 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002313 } else {
2314 DomBlock = *pred_begin(IfBlock2);
Dehao Chenf6c00832016-05-18 19:44:21 +00002315 for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2316 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002317 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002318 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002319 // Because of this, we won't be able to get rid of the control flow, so
2320 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002321 return false;
2322 }
2323 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002324
Chris Lattner9fd838d2010-12-14 07:23:10 +00002325 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00002326 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002327
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002328 // If we can still promote the PHI nodes after this gauntlet of tests,
2329 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00002330 Instruction *InsertPt = DomBlock->getTerminator();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002331 IRBuilder<NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002332
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002333 // Move all 'aggressive' instructions, which are defined in the
2334 // conditional parts of the if's up to the dominating block.
David Majnemere8fd5f92016-08-29 17:14:08 +00002335 if (IfBlock1) {
2336 for (auto &I : *IfBlock1)
2337 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002338 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002339 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002340 IfBlock1->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002341 }
2342 if (IfBlock2) {
2343 for (auto &I : *IfBlock2)
2344 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002345 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002346 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002347 IfBlock2->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002348 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002349
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002350 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2351 // Change the PHI node into a select instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002352 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002353 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002354
Sanjay Patel9e23fed2016-03-17 15:30:52 +00002355 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2356 PN->replaceAllUsesWith(Sel);
2357 Sel->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00002358 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002359 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002360
Chris Lattner335f0e42010-12-14 08:01:53 +00002361 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2362 // has been flattened. Change DomBlock to jump directly to our new block to
2363 // avoid other simplifycfg's kicking in on the diamond.
2364 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00002365 Builder.SetInsertPoint(OldTI);
2366 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00002367 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002368 return true;
2369}
Chris Lattner748f9032005-09-19 23:49:37 +00002370
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002371/// If we found a conditional branch that goes to two returning blocks,
2372/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00002373/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002374static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00002375 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002376 assert(BI->isConditional() && "Must be a conditional branch");
2377 BasicBlock *TrueSucc = BI->getSuccessor(0);
2378 BasicBlock *FalseSucc = BI->getSuccessor(1);
2379 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2380 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002381
Chris Lattner86bbf332008-04-24 00:01:19 +00002382 // Check to ensure both blocks are empty (just a return) or optionally empty
2383 // with PHI nodes. If there are other instructions, merging would cause extra
2384 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002385 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002386 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002387 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002388 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00002389
Devang Pateldd14e0f2011-05-18 21:33:11 +00002390 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002391 // Okay, we found a branch that is going to two return nodes. If
2392 // there is no return value for this function, just change the
2393 // branch into a return.
2394 if (FalseRet->getNumOperands() == 0) {
2395 TrueSucc->removePredecessor(BI->getParent());
2396 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00002397 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00002398 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002399 return true;
2400 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002401
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002402 // Otherwise, figure out what the true and false return values are
2403 // so we can insert a new select instruction.
2404 Value *TrueValue = TrueRet->getReturnValue();
2405 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002406
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002407 // Unwrap any PHI nodes in the return blocks.
2408 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2409 if (TVPN->getParent() == TrueSucc)
2410 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2411 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2412 if (FVPN->getParent() == FalseSucc)
2413 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002414
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002415 // In order for this transformation to be safe, we must be able to
2416 // unconditionally execute both operands to the return. This is
2417 // normally the case, but we could have a potentially-trapping
2418 // constant expression that prevents this transformation from being
2419 // safe.
2420 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2421 if (TCV->canTrap())
2422 return false;
2423 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2424 if (FCV->canTrap())
2425 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002426
Chris Lattner86bbf332008-04-24 00:01:19 +00002427 // Okay, we collected all the mapped values and checked them for sanity, and
2428 // defined to really do this transformation. First, update the CFG.
2429 TrueSucc->removePredecessor(BI->getParent());
2430 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002431
Chris Lattner86bbf332008-04-24 00:01:19 +00002432 // Insert select instructions where needed.
2433 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002434 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002435 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002436 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2437 } else if (isa<UndefValue>(TrueValue)) {
2438 TrueValue = FalseValue;
2439 } else {
Sanjay Patelfacf45a2016-04-27 23:14:12 +00002440 TrueValue =
2441 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002442 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002443 }
2444
Dehao Chenf6c00832016-05-18 19:44:21 +00002445 Value *RI =
2446 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
Devang Pateldd14e0f2011-05-18 21:33:11 +00002447
Dehao Chenf6c00832016-05-18 19:44:21 +00002448 (void)RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002449
David Greene725c7c32010-01-05 01:26:52 +00002450 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002451 << "\n " << *BI << "NewRet = " << *RI
Dehao Chenf6c00832016-05-18 19:44:21 +00002452 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002453
Eli Friedmancb61afb2008-12-16 20:54:32 +00002454 EraseTerminatorInstAndDCECond(BI);
2455
Chris Lattner86bbf332008-04-24 00:01:19 +00002456 return true;
2457}
2458
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002459/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002460/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002461static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002462 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2463 return false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00002464 for (Instruction &I : *PB) {
2465 Instruction *PBI = &I;
Manman Rend33f4ef2012-06-13 05:43:29 +00002466 // Check whether Inst and PBI generate the same value.
2467 if (Inst->isIdenticalTo(PBI)) {
2468 Inst->replaceAllUsesWith(PBI);
2469 Inst->eraseFromParent();
2470 return true;
2471 }
2472 }
2473 return false;
2474}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002475
Dehao Chenf16376b2016-05-18 22:41:03 +00002476/// Return true if either PBI or BI has branch weight available, and store
2477/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2478/// not have branch weight, use 1:1 as its weight.
2479static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2480 uint64_t &PredTrueWeight,
2481 uint64_t &PredFalseWeight,
2482 uint64_t &SuccTrueWeight,
2483 uint64_t &SuccFalseWeight) {
2484 bool PredHasWeights =
2485 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2486 bool SuccHasWeights =
2487 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2488 if (PredHasWeights || SuccHasWeights) {
2489 if (!PredHasWeights)
2490 PredTrueWeight = PredFalseWeight = 1;
2491 if (!SuccHasWeights)
2492 SuccTrueWeight = SuccFalseWeight = 1;
2493 return true;
2494 } else {
2495 return false;
2496 }
2497}
2498
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002499/// If this basic block is simple enough, and if a predecessor branches to us
2500/// and one of our successors, fold the block into the predecessor and use
2501/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002502bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002503 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002504
Craig Topperf40110f2014-04-25 05:29:35 +00002505 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002506 if (BI->isConditional())
2507 Cond = dyn_cast<Instruction>(BI->getCondition());
2508 else {
2509 // For unconditional branch, check for a simple CFG pattern, where
2510 // BB has a single predecessor and BB's successor is also its predecessor's
2511 // successor. If such pattern exisits, check for CSE between BB and its
2512 // predecessor.
2513 if (BasicBlock *PB = BB->getSinglePredecessor())
2514 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2515 if (PBI->isConditional() &&
2516 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2517 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002518 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002519 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002520 if (isa<CmpInst>(Curr)) {
2521 Cond = Curr;
2522 break;
2523 }
2524 // Quit if we can't remove this instruction.
2525 if (!checkCSEInPredecessor(Curr, PB))
2526 return false;
2527 }
2528 }
2529
Craig Topperf40110f2014-04-25 05:29:35 +00002530 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002531 return false;
2532 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002533
Craig Topperf40110f2014-04-25 05:29:35 +00002534 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2535 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002536 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002537
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002538 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002539 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002540
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002541 // Ignore dbg intrinsics.
Dehao Chenf6c00832016-05-18 19:44:21 +00002542 while (isa<DbgInfoIntrinsic>(CondIt))
2543 ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002544
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002545 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002546 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002547
Jingyue Wufc029672014-09-30 22:23:38 +00002548 // Only allow this transformation if computing the condition doesn't involve
2549 // too many instructions and these involved instructions can be executed
2550 // unconditionally. We denote all involved instructions except the condition
2551 // as "bonus instructions", and only allow this transformation when the
2552 // number of the bonus instructions does not exceed a certain threshold.
2553 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002554 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002555 // Ignore dbg intrinsics.
2556 if (isa<DbgInfoIntrinsic>(I))
2557 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002558 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002559 return false;
2560 // I has only one use and can be executed unconditionally.
2561 Instruction *User = dyn_cast<Instruction>(I->user_back());
2562 if (User == nullptr || User->getParent() != BB)
2563 return false;
2564 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2565 // to use any other instruction, User must be an instruction between next(I)
2566 // and Cond.
2567 ++NumBonusInsts;
2568 // Early exits once we reach the limit.
2569 if (NumBonusInsts > BonusInstThreshold)
2570 return false;
2571 }
2572
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002573 // Cond is known to be a compare or binary operator. Check to make sure that
2574 // neither operand is a potentially-trapping constant expression.
2575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2576 if (CE->canTrap())
2577 return false;
2578 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2579 if (CE->canTrap())
2580 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002581
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002582 // Finally, don't infinitely unroll conditional loops.
Dehao Chenf6c00832016-05-18 19:44:21 +00002583 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002584 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002585 if (TrueDest == BB || FalseDest == BB)
2586 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002587
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002588 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2589 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002590 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002591
Chris Lattner80b03a12008-07-13 22:23:11 +00002592 // Check that we have two conditional branches. If there is a PHI node in
2593 // the common successor, verify that the same value flows in from both
2594 // blocks.
Dehao Chenf6c00832016-05-18 19:44:21 +00002595 SmallVector<PHINode *, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002596 if (!PBI || PBI->isUnconditional() ||
Dehao Chenf6c00832016-05-18 19:44:21 +00002597 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
Manman Rend33f4ef2012-06-13 05:43:29 +00002598 (!BI->isConditional() &&
2599 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002600 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002601
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002602 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002603 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002604 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002605
Manman Rend33f4ef2012-06-13 05:43:29 +00002606 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002607 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002608 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002609 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002610 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002611 } else if (PBI->getSuccessor(0) == FalseDest) {
2612 Opc = Instruction::And;
2613 InvertPredCond = true;
2614 } else if (PBI->getSuccessor(1) == TrueDest) {
2615 Opc = Instruction::Or;
2616 InvertPredCond = true;
2617 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002618 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002619 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002620 } else {
2621 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2622 continue;
2623 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002624
David Greene725c7c32010-01-05 01:26:52 +00002625 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002626 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002627
Chris Lattner55eaae12008-07-13 21:20:19 +00002628 // If we need to invert the condition in the pred block to match, do so now.
2629 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002630 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002631
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002632 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2633 CmpInst *CI = cast<CmpInst>(NewCond);
2634 CI->setPredicate(CI->getInversePredicate());
2635 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00002636 NewCond =
2637 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002638 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002639
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002640 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002641 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002642 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002643
Jingyue Wufc029672014-09-30 22:23:38 +00002644 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002645 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002646 // bonus instructions to a predecessor block.
2647 ValueToValueMapTy VMap; // maps original values to cloned values
2648 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002649 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002650 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002651 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002652 if (isa<DbgInfoIntrinsic>(BonusInst))
2653 continue;
2654 Instruction *NewBonusInst = BonusInst->clone();
2655 RemapInstruction(NewBonusInst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002656 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002657 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002658
2659 // If we moved a load, we cannot any longer claim any knowledge about
2660 // its potential value. The previous information might have been valid
2661 // only given the branch precondition.
2662 // For an analogous reason, we must also drop all the metadata whose
2663 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002664 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002665
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002666 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2667 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002668 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002669 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002670
Chris Lattner55eaae12008-07-13 21:20:19 +00002671 // Clone Cond into the predecessor basic block, and or/and the
2672 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002673 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002674 RemapInstruction(New, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002675 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002676 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002677 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002678 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002679
Manman Rend33f4ef2012-06-13 05:43:29 +00002680 if (BI->isConditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002681 Instruction *NewCond = cast<Instruction>(
2682 Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002683 PBI->setCondition(NewCond);
2684
Manman Renbfb9d432012-09-15 00:39:57 +00002685 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenf16376b2016-05-18 22:41:03 +00002686 bool HasWeights =
2687 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2688 SuccTrueWeight, SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002689 SmallVector<uint64_t, 8> NewWeights;
2690
Manman Rend33f4ef2012-06-13 05:43:29 +00002691 if (PBI->getSuccessor(0) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002692 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002693 // PBI: br i1 %x, BB, FalseDest
2694 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002695 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002696 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
Dehao Chenf6c00832016-05-18 19:44:21 +00002697 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002698 // TrueWeight for PBI * FalseWeight for BI.
2699 // We assume that total weights of a BranchInst can fit into 32 bits.
2700 // Therefore, we will not have overflow using 64-bit arithmetic.
Dehao Chenf6c00832016-05-18 19:44:21 +00002701 NewWeights.push_back(PredFalseWeight *
2702 (SuccFalseWeight + SuccTrueWeight) +
2703 PredTrueWeight * SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002704 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002705 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2706 PBI->setSuccessor(0, TrueDest);
2707 }
2708 if (PBI->getSuccessor(1) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002709 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002710 // PBI: br i1 %x, TrueDest, BB
2711 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002712 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002713 // FalseWeight for PBI * TrueWeight for BI.
Dehao Chenf6c00832016-05-18 19:44:21 +00002714 NewWeights.push_back(PredTrueWeight *
2715 (SuccFalseWeight + SuccTrueWeight) +
2716 PredFalseWeight * SuccTrueWeight);
2717 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002718 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2719 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002720 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2721 PBI->setSuccessor(1, FalseDest);
2722 }
Manman Renbfb9d432012-09-15 00:39:57 +00002723 if (NewWeights.size() == 2) {
2724 // Halve the weights if any of them cannot fit in an uint32_t
2725 FitWeights(NewWeights);
2726
Dehao Chenf6c00832016-05-18 19:44:21 +00002727 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2728 NewWeights.end());
2729 PBI->setMetadata(
2730 LLVMContext::MD_prof,
2731 MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
Manman Renbfb9d432012-09-15 00:39:57 +00002732 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002733 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002734 } else {
2735 // Update PHI nodes in the common successors.
2736 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002737 ConstantInt *PBI_C = cast<ConstantInt>(
Dehao Chenf6c00832016-05-18 19:44:21 +00002738 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
Manman Rend33f4ef2012-06-13 05:43:29 +00002739 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002740 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002741 if (PBI->getSuccessor(0) == TrueDest) {
2742 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2743 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2744 // is false: !PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002745 Instruction *NotCond = cast<Instruction>(
2746 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2747 MergedCond = cast<Instruction>(
2748 Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002749 if (PBI_C->isOne())
Dehao Chenf6c00832016-05-18 19:44:21 +00002750 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2751 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002752 } else {
2753 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2754 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2755 // is false: PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002756 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2757 Instruction::And, PBI->getCondition(), New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002758 if (PBI_C->isOne()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002759 Instruction *NotCond = cast<Instruction>(
2760 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2761 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2762 Instruction::Or, NotCond, MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002763 }
2764 }
2765 // Update PHI Node.
2766 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2767 MergedCond);
2768 }
2769 // Change PBI from Conditional to Unconditional.
2770 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2771 EraseTerminatorInstAndDCECond(PBI);
2772 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002773 }
Devang Pateld715ec82011-04-06 22:37:20 +00002774
Michael Kuperstein3ca147e2016-12-16 21:23:59 +00002775 // If BI was a loop latch, it may have had associated loop metadata.
2776 // We need to copy it to the new latch, that is, PBI.
2777 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
2778 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
2779
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002780 // TODO: If BB is reachable from all paths through PredBlock, then we
2781 // could replace PBI's branch probabilities with BI's.
2782
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002783 // Copy any debug value intrinsics into the end of PredBlock.
Benjamin Kramer135f7352016-06-26 12:28:59 +00002784 for (Instruction &I : *BB)
2785 if (isa<DbgInfoIntrinsic>(I))
2786 I.clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002787
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002788 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002789 }
2790 return false;
2791}
2792
James Molloy4de84dd2015-11-04 15:28:04 +00002793// If there is only one store in BB1 and BB2, return it, otherwise return
2794// nullptr.
2795static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2796 StoreInst *S = nullptr;
2797 for (auto *BB : {BB1, BB2}) {
2798 if (!BB)
2799 continue;
2800 for (auto &I : *BB)
2801 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2802 if (S)
2803 // Multiple stores seen.
2804 return nullptr;
2805 else
2806 S = SI;
2807 }
2808 }
2809 return S;
2810}
2811
2812static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2813 Value *AlternativeV = nullptr) {
2814 // PHI is going to be a PHI node that allows the value V that is defined in
2815 // BB to be referenced in BB's only successor.
2816 //
2817 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2818 // doesn't matter to us what the other operand is (it'll never get used). We
2819 // could just create a new PHI with an undef incoming value, but that could
2820 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2821 // other PHI. So here we directly look for some PHI in BB's successor with V
2822 // as an incoming operand. If we find one, we use it, else we create a new
2823 // one.
2824 //
2825 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2826 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2827 // where OtherBB is the single other predecessor of BB's only successor.
2828 PHINode *PHI = nullptr;
2829 BasicBlock *Succ = BB->getSingleSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00002830
James Molloy4de84dd2015-11-04 15:28:04 +00002831 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2832 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2833 PHI = cast<PHINode>(I);
2834 if (!AlternativeV)
2835 break;
2836
2837 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2838 auto PredI = pred_begin(Succ);
2839 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2840 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2841 break;
2842 PHI = nullptr;
2843 }
2844 if (PHI)
2845 return PHI;
2846
James Molloy3d21dcf2015-12-16 14:12:44 +00002847 // If V is not an instruction defined in BB, just return it.
2848 if (!AlternativeV &&
2849 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2850 return V;
2851
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002852 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002853 PHI->addIncoming(V, BB);
2854 for (BasicBlock *PredBB : predecessors(Succ))
2855 if (PredBB != BB)
Dehao Chenf6c00832016-05-18 19:44:21 +00002856 PHI->addIncoming(
2857 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
James Molloy4de84dd2015-11-04 15:28:04 +00002858 return PHI;
2859}
2860
2861static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2862 BasicBlock *QTB, BasicBlock *QFB,
2863 BasicBlock *PostBB, Value *Address,
2864 bool InvertPCond, bool InvertQCond) {
2865 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2866 return Operator::getOpcode(&I) == Instruction::BitCast &&
2867 I.getType()->isPointerTy();
2868 };
2869
2870 // If we're not in aggressive mode, we only optimize if we have some
2871 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2872 auto IsWorthwhile = [&](BasicBlock *BB) {
2873 if (!BB)
2874 return true;
2875 // Heuristic: if the block can be if-converted/phi-folded and the
2876 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2877 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002878 unsigned N = 0;
2879 for (auto &I : *BB) {
2880 // Cheap instructions viable for folding.
2881 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2882 isa<StoreInst>(I))
2883 ++N;
2884 // Free instructions.
2885 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2886 IsaBitcastOfPointerType(I))
2887 continue;
2888 else
James Molloy4de84dd2015-11-04 15:28:04 +00002889 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002890 }
2891 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002892 };
2893
Dehao Chenf6c00832016-05-18 19:44:21 +00002894 if (!MergeCondStoresAggressively &&
2895 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2896 !IsWorthwhile(QFB)))
James Molloy4de84dd2015-11-04 15:28:04 +00002897 return false;
2898
2899 // For every pointer, there must be exactly two stores, one coming from
2900 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2901 // store (to any address) in PTB,PFB or QTB,QFB.
2902 // FIXME: We could relax this restriction with a bit more work and performance
2903 // testing.
2904 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2905 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2906 if (!PStore || !QStore)
2907 return false;
2908
2909 // Now check the stores are compatible.
2910 if (!QStore->isUnordered() || !PStore->isUnordered())
2911 return false;
2912
2913 // Check that sinking the store won't cause program behavior changes. Sinking
2914 // the store out of the Q blocks won't change any behavior as we're sinking
2915 // from a block to its unconditional successor. But we're moving a store from
2916 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2917 // So we need to check that there are no aliasing loads or stores in
2918 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2919 // operations between PStore and the end of its parent block.
2920 //
2921 // The ideal way to do this is to query AliasAnalysis, but we don't
2922 // preserve AA currently so that is dangerous. Be super safe and just
2923 // check there are no other memory operations at all.
2924 for (auto &I : *QFB->getSinglePredecessor())
2925 if (I.mayReadOrWriteMemory())
2926 return false;
2927 for (auto &I : *QFB)
2928 if (&I != QStore && I.mayReadOrWriteMemory())
2929 return false;
2930 if (QTB)
2931 for (auto &I : *QTB)
2932 if (&I != QStore && I.mayReadOrWriteMemory())
2933 return false;
2934 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2935 I != E; ++I)
2936 if (&*I != PStore && I->mayReadOrWriteMemory())
2937 return false;
2938
2939 // OK, we're going to sink the stores to PostBB. The store has to be
2940 // conditional though, so first create the predicate.
2941 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2942 ->getCondition();
2943 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2944 ->getCondition();
2945
2946 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2947 PStore->getParent());
2948 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2949 QStore->getParent(), PPHI);
2950
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002951 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2952
James Molloy4de84dd2015-11-04 15:28:04 +00002953 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2954 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2955
2956 if (InvertPCond)
2957 PPred = QB.CreateNot(PPred);
2958 if (InvertQCond)
2959 QPred = QB.CreateNot(QPred);
2960 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2961
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002962 auto *T =
2963 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002964 QB.SetInsertPoint(T);
2965 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2966 AAMDNodes AAMD;
2967 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2968 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2969 SI->setAAMetadata(AAMD);
2970
2971 QStore->eraseFromParent();
2972 PStore->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00002973
James Molloy4de84dd2015-11-04 15:28:04 +00002974 return true;
2975}
2976
2977static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2978 // The intention here is to find diamonds or triangles (see below) where each
2979 // conditional block contains a store to the same address. Both of these
2980 // stores are conditional, so they can't be unconditionally sunk. But it may
2981 // be profitable to speculatively sink the stores into one merged store at the
2982 // end, and predicate the merged store on the union of the two conditions of
2983 // PBI and QBI.
2984 //
2985 // This can reduce the number of stores executed if both of the conditions are
2986 // true, and can allow the blocks to become small enough to be if-converted.
2987 // This optimization will also chain, so that ladders of test-and-set
2988 // sequences can be if-converted away.
2989 //
2990 // We only deal with simple diamonds or triangles:
2991 //
2992 // PBI or PBI or a combination of the two
2993 // / \ | \
2994 // PTB PFB | PFB
2995 // \ / | /
2996 // QBI QBI
2997 // / \ | \
2998 // QTB QFB | QFB
2999 // \ / | /
3000 // PostBB PostBB
3001 //
3002 // We model triangles as a type of diamond with a nullptr "true" block.
3003 // Triangles are canonicalized so that the fallthrough edge is represented by
3004 // a true condition, as in the diagram above.
Dehao Chenf6c00832016-05-18 19:44:21 +00003005 //
James Molloy4de84dd2015-11-04 15:28:04 +00003006 BasicBlock *PTB = PBI->getSuccessor(0);
3007 BasicBlock *PFB = PBI->getSuccessor(1);
3008 BasicBlock *QTB = QBI->getSuccessor(0);
3009 BasicBlock *QFB = QBI->getSuccessor(1);
3010 BasicBlock *PostBB = QFB->getSingleSuccessor();
3011
Craig Topper7af07882017-04-21 15:53:42 +00003012 // Make sure we have a good guess for PostBB. If QTB's only successor is
3013 // QFB, then QFB is a better PostBB.
3014 if (QTB->getSingleSuccessor() == QFB)
3015 PostBB = QFB;
3016
3017 // If we couldn't find a good PostBB, stop.
3018 if (!PostBB)
3019 return false;
3020
James Molloy4de84dd2015-11-04 15:28:04 +00003021 bool InvertPCond = false, InvertQCond = false;
3022 // Canonicalize fallthroughs to the true branches.
3023 if (PFB == QBI->getParent()) {
3024 std::swap(PFB, PTB);
3025 InvertPCond = true;
3026 }
3027 if (QFB == PostBB) {
3028 std::swap(QFB, QTB);
3029 InvertQCond = true;
3030 }
3031
3032 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3033 // and QFB may not. Model fallthroughs as a nullptr block.
3034 if (PTB == QBI->getParent())
3035 PTB = nullptr;
3036 if (QTB == PostBB)
3037 QTB = nullptr;
3038
3039 // Legality bailouts. We must have at least the non-fallthrough blocks and
3040 // the post-dominating block, and the non-fallthroughs must only have one
3041 // predecessor.
3042 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003043 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
James Molloy4de84dd2015-11-04 15:28:04 +00003044 };
Craig Topper7af07882017-04-21 15:53:42 +00003045 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
James Molloy4de84dd2015-11-04 15:28:04 +00003046 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3047 return false;
3048 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3049 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3050 return false;
Craig Topperc2280682017-04-17 22:13:00 +00003051 if (!PostBB->hasNUses(2) || !QBI->getParent()->hasNUses(2))
James Molloy4de84dd2015-11-04 15:28:04 +00003052 return false;
3053
3054 // OK, this is a sequence of two diamonds or triangles.
3055 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
Dehao Chenf6c00832016-05-18 19:44:21 +00003056 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
James Molloy4de84dd2015-11-04 15:28:04 +00003057 for (auto *BB : {PTB, PFB}) {
3058 if (!BB)
3059 continue;
3060 for (auto &I : *BB)
3061 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3062 PStoreAddresses.insert(SI->getPointerOperand());
3063 }
3064 for (auto *BB : {QTB, QFB}) {
3065 if (!BB)
3066 continue;
3067 for (auto &I : *BB)
3068 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3069 QStoreAddresses.insert(SI->getPointerOperand());
3070 }
Dehao Chenf6c00832016-05-18 19:44:21 +00003071
James Molloy4de84dd2015-11-04 15:28:04 +00003072 set_intersect(PStoreAddresses, QStoreAddresses);
3073 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3074 // clear what it contains.
3075 auto &CommonAddresses = PStoreAddresses;
3076
3077 bool Changed = false;
3078 for (auto *Address : CommonAddresses)
3079 Changed |= mergeConditionalStoreToAddress(
3080 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
3081 return Changed;
3082}
3083
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003084/// If we have a conditional branch as a predecessor of another block,
3085/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00003086/// that PBI and BI are both conditional branches, and BI is in one of the
3087/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00003088static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3089 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00003090 assert(PBI->isConditional() && BI->isConditional());
3091 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00003092
Chris Lattner9aada1d2008-07-13 21:53:26 +00003093 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00003094 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00003095 // this conditional branch redundant.
3096 if (PBI->getCondition() == BI->getCondition() &&
3097 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3098 // Okay, the outcome of this conditional branch is statically
3099 // knowable. If this block had a single pred, handle specially.
3100 if (BB->getSinglePredecessor()) {
3101 // Turn this into a branch on constant.
3102 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003103 BI->setCondition(
3104 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3105 return true; // Nuke the branch on constant.
Chris Lattner9aada1d2008-07-13 21:53:26 +00003106 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003107
Chris Lattner9aada1d2008-07-13 21:53:26 +00003108 // Otherwise, if there are multiple predecessors, insert a PHI that merges
3109 // in the constant and simplify the block result. Subsequent passes of
3110 // simplifycfg will thread the block.
3111 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00003112 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003113 PHINode *NewPN = PHINode::Create(
3114 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3115 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00003116 // Okay, we're going to insert the PHI node. Since PBI is not the only
3117 // predecessor, compute the PHI'd conditional value for all of the preds.
3118 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00003119 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00003120 BasicBlock *P = *PI;
Dehao Chenf6c00832016-05-18 19:44:21 +00003121 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3122 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00003123 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3124 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003125 NewPN->addIncoming(
3126 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3127 P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003128 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00003129 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003130 }
Gabor Greif8629f122010-07-12 10:59:23 +00003131 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003132
Chris Lattner9aada1d2008-07-13 21:53:26 +00003133 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003134 return true;
3135 }
3136 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003137
Philip Reamesb42db212015-10-14 22:46:19 +00003138 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3139 if (CE->canTrap())
3140 return false;
3141
James Molloy4de84dd2015-11-04 15:28:04 +00003142 // If both branches are conditional and both contain stores to the same
3143 // address, remove the stores from the conditionals and create a conditional
3144 // merged store at the end.
3145 if (MergeCondStores && mergeConditionalStores(PBI, BI))
3146 return true;
3147
Chris Lattner9aada1d2008-07-13 21:53:26 +00003148 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00003149 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00003150 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00003151 BasicBlock::iterator BBI = BB->begin();
3152 // Ignore dbg intrinsics.
3153 while (isa<DbgInfoIntrinsic>(BBI))
3154 ++BBI;
3155 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00003156 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00003157
Chris Lattner834ab4e2008-07-13 22:04:41 +00003158 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00003159 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3160 PBIOp = 0;
3161 BIOp = 0;
3162 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3163 PBIOp = 0;
3164 BIOp = 1;
3165 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3166 PBIOp = 1;
3167 BIOp = 0;
3168 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3169 PBIOp = 1;
3170 BIOp = 1;
3171 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003172 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00003173 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003174
Chris Lattner834ab4e2008-07-13 22:04:41 +00003175 // Check to make sure that the other destination of this branch
3176 // isn't BB itself. If so, this is an infinite loop that will
3177 // keep getting unwound.
3178 if (PBI->getSuccessor(PBIOp) == BB)
3179 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003180
3181 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00003182 // insertion of a large number of select instructions. For targets
3183 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003184
Sanjay Patela932da82014-07-07 21:19:00 +00003185 // Also do not perform this transformation if any phi node in the common
3186 // destination block can trap when reached by BB or PBB (PR17073). In that
3187 // case, it would be unsafe to hoist the operation into a select instruction.
3188
3189 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003190 unsigned NumPhis = 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00003191 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3192 ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003193 if (NumPhis > 2) // Disable this xform.
3194 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003195
Sanjay Patela932da82014-07-07 21:19:00 +00003196 PHINode *PN = cast<PHINode>(II);
3197 Value *BIV = PN->getIncomingValueForBlock(BB);
3198 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3199 if (CE->canTrap())
3200 return false;
3201
3202 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3203 Value *PBIV = PN->getIncomingValue(PBBIdx);
3204 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3205 if (CE->canTrap())
3206 return false;
3207 }
3208
Chris Lattner834ab4e2008-07-13 22:04:41 +00003209 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00003210 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003211
David Greene725c7c32010-01-05 01:26:52 +00003212 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00003213 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003214
Chris Lattner80b03a12008-07-13 22:23:11 +00003215 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3216 // branch in it, where one edge (OtherDest) goes back to itself but the other
3217 // exits. We don't *know* that the program avoids the infinite loop
3218 // (even though that seems likely). If we do this xform naively, we'll end up
3219 // recursively unpeeling the loop. Since we know that (after the xform is
3220 // done) that the block *is* infinite if reached, we just make it an obviously
3221 // infinite loop with no cond branch.
3222 if (OtherDest == BB) {
3223 // Insert it at the end of the function, because it's either code,
3224 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00003225 BasicBlock *InfLoopBlock =
3226 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00003227 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3228 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003229 }
3230
David Greene725c7c32010-01-05 01:26:52 +00003231 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00003232
Chris Lattner834ab4e2008-07-13 22:04:41 +00003233 // BI may have other predecessors. Because of this, we leave
3234 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003235
Chris Lattner834ab4e2008-07-13 22:04:41 +00003236 // Make sure we get to CommonDest on True&True directions.
3237 Value *PBICond = PBI->getCondition();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00003238 IRBuilder<NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003239 if (PBIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003240 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003241
Chris Lattner834ab4e2008-07-13 22:04:41 +00003242 Value *BICond = BI->getCondition();
3243 if (BIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003244 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003245
Chris Lattner834ab4e2008-07-13 22:04:41 +00003246 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00003247 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00003248
Chris Lattner834ab4e2008-07-13 22:04:41 +00003249 // Modify PBI to branch on the new condition to the new dests.
3250 PBI->setCondition(Cond);
3251 PBI->setSuccessor(0, CommonDest);
3252 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003253
Manman Ren2d4c10f2012-09-17 21:30:40 +00003254 // Update branch weight for PBI.
3255 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenb76e5d92016-05-10 23:07:19 +00003256 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
Dehao Chenf16376b2016-05-18 22:41:03 +00003257 bool HasWeights =
3258 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3259 SuccTrueWeight, SuccFalseWeight);
Dehao Chenb76e5d92016-05-10 23:07:19 +00003260 if (HasWeights) {
Dehao Chenb76e5d92016-05-10 23:07:19 +00003261 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3262 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3263 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3264 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
Manman Ren2d4c10f2012-09-17 21:30:40 +00003265 // The weight to CommonDest should be PredCommon * SuccTotal +
3266 // PredOther * SuccCommon.
3267 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00003268 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3269 PredOther * SuccCommon,
3270 PredOther * SuccOther};
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003271 // Halve the weights if any of them cannot fit in an uint32_t
Manman Ren2d4c10f2012-09-17 21:30:40 +00003272 FitWeights(NewWeights);
3273
Manman Ren2d4c10f2012-09-17 21:30:40 +00003274 PBI->setMetadata(LLVMContext::MD_prof,
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003275 MDBuilder(BI->getContext())
3276 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00003277 }
3278
Chris Lattner834ab4e2008-07-13 22:04:41 +00003279 // OtherDest may have phi nodes. If so, add an entry from PBI's
3280 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003281 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003282
Chris Lattner834ab4e2008-07-13 22:04:41 +00003283 // We know that the CommonDest already had an edge from PBI to
3284 // it. If it has PHIs though, the PHIs may have different
3285 // entries for BB and PBI's BB. If so, insert a select to make
3286 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003287 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00003288 for (BasicBlock::iterator II = CommonDest->begin();
3289 (PN = dyn_cast<PHINode>(II)); ++II) {
3290 Value *BIV = PN->getIncomingValueForBlock(BB);
3291 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3292 Value *PBIV = PN->getIncomingValue(PBBIdx);
3293 if (BIV != PBIV) {
3294 // Insert a select in PBI to pick the right value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003295 SelectInst *NV = cast<SelectInst>(
3296 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00003297 PN->setIncomingValue(PBBIdx, NV);
Sanjay Patel1cb62412016-05-06 18:07:46 +00003298 // Although the select has the same condition as PBI, the original branch
3299 // weights for PBI do not apply to the new select because the select's
3300 // 'logical' edges are incoming edges of the phi that is eliminated, not
3301 // the outgoing edges of PBI.
Dehao Chenf16376b2016-05-18 22:41:03 +00003302 if (HasWeights) {
Sanjay Patel1cb62412016-05-06 18:07:46 +00003303 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3304 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3305 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3306 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3307 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3308 // The weight to PredOtherDest should be PredOther * SuccCommon.
3309 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3310 PredOther * SuccCommon};
3311
3312 FitWeights(NewWeights);
3313
3314 NV->setMetadata(LLVMContext::MD_prof,
3315 MDBuilder(BI->getContext())
3316 .createBranchWeights(NewWeights[0], NewWeights[1]));
3317 }
Chris Lattner9aada1d2008-07-13 21:53:26 +00003318 }
3319 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003320
David Greene725c7c32010-01-05 01:26:52 +00003321 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3322 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003323
Chris Lattner834ab4e2008-07-13 22:04:41 +00003324 // This basic block is probably dead. We know it has at least
3325 // one fewer predecessor.
3326 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00003327}
3328
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003329// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3330// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00003331// Takes care of updating the successors and removing the old terminator.
3332// Also makes sure not to introduce new successors by assuming that edges to
3333// non-successor TrueBBs and FalseBBs aren't reachable.
3334static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00003335 BasicBlock *TrueBB, BasicBlock *FalseBB,
3336 uint32_t TrueWeight,
Dehao Chenf6c00832016-05-18 19:44:21 +00003337 uint32_t FalseWeight) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003338 // Remove any superfluous successor edges from the CFG.
3339 // First, figure out which successors to preserve.
3340 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3341 // successor.
3342 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00003343 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003344
3345 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00003346 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003347 // Make sure only to keep exactly one copy of each edge.
3348 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00003349 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003350 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00003351 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003352 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00003353 Succ->removePredecessor(OldTerm->getParent(),
3354 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00003355 }
3356
Devang Patel2c2ea222011-05-18 18:43:31 +00003357 IRBuilder<> Builder(OldTerm);
3358 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3359
Frits van Bommel8e158492011-01-11 12:52:11 +00003360 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00003361 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003362 if (TrueBB == FalseBB)
3363 // We were only looking for one successor, and it was present.
3364 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00003365 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00003366 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00003367 // We found both of the successors we were looking for.
3368 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00003369 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3370 if (TrueWeight != FalseWeight)
3371 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00003372 MDBuilder(OldTerm->getContext())
3373 .createBranchWeights(TrueWeight, FalseWeight));
Manman Ren774246a2012-09-17 22:28:55 +00003374 }
Frits van Bommel8e158492011-01-11 12:52:11 +00003375 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3376 // Neither of the selected blocks were successors, so this
3377 // terminator must be unreachable.
3378 new UnreachableInst(OldTerm->getContext(), OldTerm);
3379 } else {
3380 // One of the selected values was a successor, but the other wasn't.
3381 // Insert an unconditional branch to the one that was found;
3382 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00003383 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00003384 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003385 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003386 else
3387 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003388 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003389 }
3390
3391 EraseTerminatorInstAndDCECond(OldTerm);
3392 return true;
3393}
3394
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003395// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00003396// (switch (select cond, X, Y)) on constant X, Y
3397// with a branch - conditional if X and Y lead to distinct BBs,
3398// unconditional otherwise.
3399static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3400 // Check for constant integer values in the select.
3401 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3402 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3403 if (!TrueVal || !FalseVal)
3404 return false;
3405
3406 // Find the relevant condition and destinations.
3407 Value *Condition = Select->getCondition();
Chandler Carruth927d8e62017-04-12 07:27:28 +00003408 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3409 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00003410
Manman Ren774246a2012-09-17 22:28:55 +00003411 // Get weight for TrueBB and FalseBB.
3412 uint32_t TrueWeight = 0, FalseWeight = 0;
3413 SmallVector<uint64_t, 8> Weights;
3414 bool HasWeights = HasBranchWeights(SI);
3415 if (HasWeights) {
3416 GetBranchWeights(SI, Weights);
3417 if (Weights.size() == 1 + SI->getNumCases()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003418 TrueWeight =
Chandler Carruth927d8e62017-04-12 07:27:28 +00003419 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
Dehao Chenf6c00832016-05-18 19:44:21 +00003420 FalseWeight =
Chandler Carruth927d8e62017-04-12 07:27:28 +00003421 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
Manman Ren774246a2012-09-17 22:28:55 +00003422 }
3423 }
3424
Frits van Bommel8ae07992011-02-28 09:44:07 +00003425 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003426 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3427 FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003428}
3429
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003430// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003431// (indirectbr (select cond, blockaddress(@fn, BlockA),
3432// blockaddress(@fn, BlockB)))
3433// with
3434// (br cond, BlockA, BlockB).
3435static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3436 // Check that both operands of the select are block addresses.
3437 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3438 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3439 if (!TBA || !FBA)
3440 return false;
3441
3442 // Extract the actual blocks.
3443 BasicBlock *TrueBB = TBA->getBasicBlock();
3444 BasicBlock *FalseBB = FBA->getBasicBlock();
3445
Frits van Bommel8e158492011-01-11 12:52:11 +00003446 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003447 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3448 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003449}
3450
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003451/// This is called when we find an icmp instruction
3452/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003453/// block that ends with an uncond branch. We are looking for a very specific
3454/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3455/// this case, we merge the first two "or's of icmp" into a switch, but then the
3456/// default value goes to an uncond block with a seteq in it, we get something
3457/// like:
3458///
3459/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3460/// DEFAULT:
3461/// %tmp = icmp eq i8 %A, 92
3462/// br label %end
3463/// end:
3464/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003465///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003466/// We prefer to split the edge to 'end' so that there is a true/false entry to
3467/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003468static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003469 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003470 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3471 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003472 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003473
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003474 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3475 // complex.
Dehao Chenf6c00832016-05-18 19:44:21 +00003476 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3477 return false;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003478
3479 Value *V = ICI->getOperand(0);
3480 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003481
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003482 // The pattern we're looking for is where our only predecessor is a switch on
3483 // 'V' and this block is the default case for the switch. In this case we can
3484 // fold the compared value into the switch to simplify things.
3485 BasicBlock *Pred = BB->getSinglePredecessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00003486 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3487 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003488
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003489 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3490 if (SI->getCondition() != V)
3491 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003492
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003493 // If BB is reachable on a non-default case, then we simply know the value of
3494 // V in this block. Substitute it and constant fold the icmp instruction
3495 // away.
3496 if (SI->getDefaultDest() != BB) {
3497 ConstantInt *VVal = SI->findCaseDest(BB);
3498 assert(VVal && "Should have a unique destination value");
3499 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003500
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003501 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003502 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003503 ICI->eraseFromParent();
3504 }
3505 // BB is now empty, so it is likely to simplify away.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003506 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003507 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003508
Chris Lattner62cc76e2010-12-13 03:43:57 +00003509 // Ok, the block is reachable from the default dest. If the constant we're
3510 // comparing exists in one of the other edges, then we can constant fold ICI
3511 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003512 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003513 Value *V;
3514 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3515 V = ConstantInt::getFalse(BB->getContext());
3516 else
3517 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003518
Chris Lattner62cc76e2010-12-13 03:43:57 +00003519 ICI->replaceAllUsesWith(V);
3520 ICI->eraseFromParent();
3521 // BB is now empty, so it is likely to simplify away.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003522 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003523 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003524
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003525 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3526 // the block.
3527 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003528 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003529 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003530 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3531 return false;
3532
3533 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3534 // true in the PHI.
3535 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Dehao Chenf6c00832016-05-18 19:44:21 +00003536 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003537
3538 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3539 std::swap(DefaultCst, NewCst);
3540
3541 // Replace ICI (which is used by the PHI for the default value) with true or
3542 // false depending on if it is EQ or NE.
3543 ICI->replaceAllUsesWith(DefaultCst);
3544 ICI->eraseFromParent();
3545
3546 // Okay, the switch goes to this block on a default value. Add an edge from
3547 // the switch to the merge point on the compared value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003548 BasicBlock *NewBB =
3549 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003550 SmallVector<uint64_t, 8> Weights;
3551 bool HasWeights = HasBranchWeights(SI);
3552 if (HasWeights) {
3553 GetBranchWeights(SI, Weights);
3554 if (Weights.size() == 1 + SI->getNumCases()) {
3555 // Split weight for default case to case for "Cst".
Dehao Chenf6c00832016-05-18 19:44:21 +00003556 Weights[0] = (Weights[0] + 1) >> 1;
Manman Rence48ea72012-09-17 23:07:43 +00003557 Weights.push_back(Weights[0]);
3558
3559 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
Dehao Chenf6c00832016-05-18 19:44:21 +00003560 SI->setMetadata(
3561 LLVMContext::MD_prof,
3562 MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
Manman Rence48ea72012-09-17 23:07:43 +00003563 }
3564 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003565 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003566
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003567 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003568 Builder.SetInsertPoint(NewBB);
3569 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3570 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003571 PHIUse->addIncoming(NewCst, NewBB);
3572 return true;
3573}
3574
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003575/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003576/// Check to see if it is branching on an or/and chain of icmp instructions, and
3577/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003578static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3579 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003580 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +00003581 if (!Cond)
3582 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003583
Chris Lattnera69c4432010-12-13 05:03:41 +00003584 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3585 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3586 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003587
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003588 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003589 ConstantComparesGatherer ConstantCompare(Cond, DL);
3590 // Unpack the result
Dehao Chenf6c00832016-05-18 19:44:21 +00003591 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
Mehdi Aminiffd01002014-11-20 22:40:25 +00003592 Value *CompVal = ConstantCompare.CompValue;
3593 unsigned UsedICmps = ConstantCompare.UsedICmps;
3594 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003595
Chris Lattnera69c4432010-12-13 05:03:41 +00003596 // If we didn't have a multiply compared value, fail.
Dehao Chenf6c00832016-05-18 19:44:21 +00003597 if (!CompVal)
3598 return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003599
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003600 // Avoid turning single icmps into a switch.
3601 if (UsedICmps <= 1)
3602 return false;
3603
Mehdi Aminiffd01002014-11-20 22:40:25 +00003604 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3605
Chris Lattnera69c4432010-12-13 05:03:41 +00003606 // There might be duplicate constants in the list, which the switch
3607 // instruction can't handle, remove them now.
3608 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3609 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003610
Chris Lattnera69c4432010-12-13 05:03:41 +00003611 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003612 // transformation. A switch with one value is just a conditional branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00003613 if (ExtraCase && Values.size() < 2)
3614 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003615
Andrew Trick3051aa12012-08-29 21:46:38 +00003616 // TODO: Preserve branch weight metadata, similarly to how
3617 // FoldValueComparisonIntoPredecessors preserves it.
3618
Chris Lattnera69c4432010-12-13 05:03:41 +00003619 // Figure out which block is which destination.
3620 BasicBlock *DefaultBB = BI->getSuccessor(1);
Dehao Chenf6c00832016-05-18 19:44:21 +00003621 BasicBlock *EdgeBB = BI->getSuccessor(0);
3622 if (!TrueWhenEqual)
3623 std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003624
Chris Lattnera69c4432010-12-13 05:03:41 +00003625 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003626
Chris Lattnerd7beca32010-12-14 06:17:25 +00003627 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Dehao Chenf6c00832016-05-18 19:44:21 +00003628 << " cases into SWITCH. BB is:\n"
3629 << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003630
Chris Lattnera69c4432010-12-13 05:03:41 +00003631 // If there are any extra values that couldn't be folded into the switch
3632 // then we evaluate them with an explicit branch first. Split the block
3633 // right before the condbr to handle it.
3634 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003635 BasicBlock *NewBB =
3636 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003637 // Remove the uncond branch added to the old block.
3638 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003639 Builder.SetInsertPoint(OldTI);
3640
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003641 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003642 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003643 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003644 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003645
Chris Lattnera69c4432010-12-13 05:03:41 +00003646 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003647
Chris Lattnercb570f82010-12-13 05:34:18 +00003648 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3649 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003650 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003651
Chris Lattnerd7beca32010-12-14 06:17:25 +00003652 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
Dehao Chenf6c00832016-05-18 19:44:21 +00003653 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003654 BB = NewBB;
3655 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003656
3657 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003658 // Convert pointer to int before we switch.
3659 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003660 CompVal = Builder.CreatePtrToInt(
3661 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003662 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003663
Chris Lattnera69c4432010-12-13 05:03:41 +00003664 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003665 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003666
Chris Lattnera69c4432010-12-13 05:03:41 +00003667 // Add all of the 'cases' to the switch instruction.
3668 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3669 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003670
Chris Lattnera69c4432010-12-13 05:03:41 +00003671 // We added edges from PI to the EdgeBB. As such, if there were any
3672 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3673 // the number of edges added.
Dehao Chenf6c00832016-05-18 19:44:21 +00003674 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003675 PHINode *PN = cast<PHINode>(BBI);
3676 Value *InVal = PN->getIncomingValueForBlock(BB);
Dehao Chenf6c00832016-05-18 19:44:21 +00003677 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
Chris Lattnera69c4432010-12-13 05:03:41 +00003678 PN->addIncoming(InVal, BB);
3679 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003680
Chris Lattnera69c4432010-12-13 05:03:41 +00003681 // Erase the old branch instruction.
3682 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003683
Chris Lattnerd7beca32010-12-14 06:17:25 +00003684 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003685 return true;
3686}
3687
Duncan Sands29192d02011-09-05 12:57:57 +00003688bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003689 if (isa<PHINode>(RI->getValue()))
3690 return SimplifyCommonResume(RI);
3691 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3692 RI->getValue() == RI->getParent()->getFirstNonPHI())
3693 // The resume must unwind the exception that caused control to branch here.
3694 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003695
3696 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003697}
3698
3699// Simplify resume that is shared by several landing pads (phi of landing pad).
3700bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3701 BasicBlock *BB = RI->getParent();
3702
3703 // Check that there are no other instructions except for debug intrinsics
3704 // between the phi of landing pads (RI->getValue()) and resume instruction.
3705 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
Dehao Chenf6c00832016-05-18 19:44:21 +00003706 E = RI->getIterator();
Chen Li1689c2f2016-01-10 05:48:01 +00003707 while (++I != E)
3708 if (!isa<DbgInfoIntrinsic>(I))
3709 return false;
3710
Mandeep Singh Grang799a2ed2017-04-24 19:20:45 +00003711 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
Chen Li1689c2f2016-01-10 05:48:01 +00003712 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3713
3714 // Check incoming blocks to see if any of them are trivial.
Dehao Chenf6c00832016-05-18 19:44:21 +00003715 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3716 Idx++) {
Chen Li1689c2f2016-01-10 05:48:01 +00003717 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3718 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3719
3720 // If the block has other successors, we can not delete it because
3721 // it has other dependents.
3722 if (IncomingBB->getUniqueSuccessor() != BB)
3723 continue;
3724
Dehao Chenf6c00832016-05-18 19:44:21 +00003725 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003726 // Not the landing pad that caused the control to branch here.
3727 if (IncomingValue != LandingPad)
3728 continue;
3729
3730 bool isTrivial = true;
3731
3732 I = IncomingBB->getFirstNonPHI()->getIterator();
3733 E = IncomingBB->getTerminator()->getIterator();
3734 while (++I != E)
3735 if (!isa<DbgInfoIntrinsic>(I)) {
3736 isTrivial = false;
3737 break;
3738 }
3739
3740 if (isTrivial)
3741 TrivialUnwindBlocks.insert(IncomingBB);
3742 }
3743
3744 // If no trivial unwind blocks, don't do any simplifications.
Dehao Chenf6c00832016-05-18 19:44:21 +00003745 if (TrivialUnwindBlocks.empty())
3746 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003747
3748 // Turn all invokes that unwind here into calls.
3749 for (auto *TrivialBB : TrivialUnwindBlocks) {
3750 // Blocks that will be simplified should be removed from the phi node.
3751 // Note there could be multiple edges to the resume block, and we need
3752 // to remove them all.
3753 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3754 BB->removePredecessor(TrivialBB, true);
3755
3756 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3757 PI != PE;) {
3758 BasicBlock *Pred = *PI++;
3759 removeUnwindEdge(Pred);
3760 }
3761
3762 // In each SimplifyCFG run, only the current processed block can be erased.
3763 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3764 // of erasing TrivialBB, we only remove the branch to the common resume
3765 // block so that we can later erase the resume block since it has no
3766 // predecessors.
3767 TrivialBB->getTerminator()->eraseFromParent();
3768 new UnreachableInst(RI->getContext(), TrivialBB);
3769 }
3770
3771 // Delete the resume block if all its predecessors have been removed.
3772 if (pred_empty(BB))
3773 BB->eraseFromParent();
3774
3775 return !TrivialUnwindBlocks.empty();
3776}
3777
3778// Simplify resume that is only used by a single (non-phi) landing pad.
3779bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003780 BasicBlock *BB = RI->getParent();
3781 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Dehao Chenf6c00832016-05-18 19:44:21 +00003782 assert(RI->getValue() == LPInst &&
3783 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003784
Chen Li7009cd32015-10-23 21:13:01 +00003785 // Check that there are no other instructions except for debug intrinsics.
3786 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003787 while (++I != E)
3788 if (!isa<DbgInfoIntrinsic>(I))
3789 return false;
3790
Chen Lic6e28782015-10-22 20:48:38 +00003791 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003792 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3793 BasicBlock *Pred = *PI++;
3794 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003795 }
3796
Chen Li7009cd32015-10-23 21:13:01 +00003797 // The landingpad is now unreachable. Zap it.
3798 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003799 if (LoopHeaders)
3800 LoopHeaders->erase(BB);
Chen Li7009cd32015-10-23 21:13:01 +00003801 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003802}
3803
David Majnemer1efa23d2016-02-20 01:07:45 +00003804static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003805 // If this is a trivial cleanup pad that executes no instructions, it can be
3806 // eliminated. If the cleanup pad continues to the caller, any predecessor
3807 // that is an EH pad will be updated to continue to the caller and any
3808 // predecessor that terminates with an invoke instruction will have its invoke
3809 // instruction converted to a call instruction. If the cleanup pad being
3810 // simplified does not continue to the caller, each predecessor will be
3811 // updated to continue to the unwind destination of the cleanup pad being
3812 // simplified.
3813 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003814 CleanupPadInst *CPInst = RI->getCleanupPad();
3815 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003816 // This isn't an empty cleanup.
3817 return false;
3818
David Majnemer2482e1c2016-06-04 23:50:03 +00003819 // We cannot kill the pad if it has multiple uses. This typically arises
3820 // from unreachable basic blocks.
3821 if (!CPInst->hasOneUse())
3822 return false;
3823
David Majnemer9f92f4c2016-05-21 05:12:32 +00003824 // Check that there are no other instructions except for benign intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003825 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
David Majnemer9f92f4c2016-05-21 05:12:32 +00003826 while (++I != E) {
3827 auto *II = dyn_cast<IntrinsicInst>(I);
3828 if (!II)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003829 return false;
3830
David Majnemer9f92f4c2016-05-21 05:12:32 +00003831 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3832 switch (IntrinsicID) {
3833 case Intrinsic::dbg_declare:
3834 case Intrinsic::dbg_value:
3835 case Intrinsic::lifetime_end:
3836 break;
3837 default:
3838 return false;
3839 }
3840 }
3841
David Majnemer8a1c45d2015-12-12 05:38:55 +00003842 // If the cleanup return we are simplifying unwinds to the caller, this will
3843 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003844 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003845 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003846
3847 // We're about to remove BB from the control flow. Before we do, sink any
3848 // PHINodes into the unwind destination. Doing this before changing the
3849 // control flow avoids some potentially slow checks, since we can currently
3850 // be certain that UnwindDest and BB have no common predecessors (since they
3851 // are both EH pads).
3852 if (UnwindDest) {
3853 // First, go through the PHI nodes in UnwindDest and update any nodes that
3854 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003855 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003856 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003857 I != IE; ++I) {
3858 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003859
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003860 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003861 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003862 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003863 // This PHI node has an incoming value that corresponds to a control
3864 // path through the cleanup pad we are removing. If the incoming
3865 // value is in the cleanup pad, it must be a PHINode (because we
3866 // verified above that the block is otherwise empty). Otherwise, the
3867 // value is either a constant or a value that dominates the cleanup
3868 // pad being removed.
3869 //
3870 // Because BB and UnwindDest are both EH pads, all of their
3871 // predecessors must unwind to these blocks, and since no instruction
3872 // can have multiple unwind destinations, there will be no overlap in
3873 // incoming blocks between SrcPN and DestPN.
3874 Value *SrcVal = DestPN->getIncomingValue(Idx);
3875 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3876
3877 // Remove the entry for the block we are deleting.
3878 DestPN->removeIncomingValue(Idx, false);
3879
3880 if (SrcPN && SrcPN->getParent() == BB) {
3881 // If the incoming value was a PHI node in the cleanup pad we are
3882 // removing, we need to merge that PHI node's incoming values into
3883 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003884 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Dehao Chenf6c00832016-05-18 19:44:21 +00003885 SrcIdx != SrcE; ++SrcIdx) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003886 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3887 SrcPN->getIncomingBlock(SrcIdx));
3888 }
3889 } else {
3890 // Otherwise, the incoming value came from above BB and
3891 // so we can just reuse it. We must associate all of BB's
3892 // predecessors with this value.
3893 for (auto *pred : predecessors(BB)) {
3894 DestPN->addIncoming(SrcVal, pred);
3895 }
3896 }
3897 }
3898
3899 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003900 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003901 for (BasicBlock::iterator I = BB->begin(),
3902 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003903 I != IE;) {
3904 // The iterator must be incremented here because the instructions are
3905 // being moved to another block.
3906 PHINode *PN = cast<PHINode>(I++);
3907 if (PN->use_empty())
3908 // If the PHI node has no uses, just leave it. It will be erased
3909 // when we erase BB below.
3910 continue;
3911
3912 // Otherwise, sink this PHI node into UnwindDest.
3913 // Any predecessors to UnwindDest which are not already represented
3914 // must be back edges which inherit the value from the path through
3915 // BB. In this case, the PHI value must reference itself.
3916 for (auto *pred : predecessors(UnwindDest))
3917 if (pred != BB)
3918 PN->addIncoming(PN, pred);
3919 PN->moveBefore(InsertPt);
3920 }
3921 }
3922
3923 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3924 // The iterator must be updated here because we are removing this pred.
3925 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003926 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003927 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003928 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003929 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003930 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003931 }
3932 }
3933
3934 // The cleanup pad is now unreachable. Zap it.
3935 BB->eraseFromParent();
3936 return true;
3937}
3938
David Majnemer1efa23d2016-02-20 01:07:45 +00003939// Try to merge two cleanuppads together.
3940static bool mergeCleanupPad(CleanupReturnInst *RI) {
3941 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3942 // with.
3943 BasicBlock *UnwindDest = RI->getUnwindDest();
3944 if (!UnwindDest)
3945 return false;
3946
3947 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3948 // be safe to merge without code duplication.
3949 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3950 return false;
3951
3952 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3953 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3954 if (!SuccessorCleanupPad)
3955 return false;
3956
3957 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3958 // Replace any uses of the successor cleanupad with the predecessor pad
3959 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3960 // funclet bundle operands.
3961 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3962 // Remove the old cleanuppad.
3963 SuccessorCleanupPad->eraseFromParent();
3964 // Now, we simply replace the cleanupret with a branch to the unwind
3965 // destination.
3966 BranchInst::Create(UnwindDest, RI->getParent());
3967 RI->eraseFromParent();
3968
3969 return true;
3970}
3971
3972bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003973 // It is possible to transiantly have an undef cleanuppad operand because we
3974 // have deleted some, but not all, dead blocks.
3975 // Eventually, this block will be deleted.
3976 if (isa<UndefValue>(RI->getOperand(0)))
3977 return false;
3978
David Majnemer9f92f4c2016-05-21 05:12:32 +00003979 if (mergeCleanupPad(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00003980 return true;
3981
David Majnemer9f92f4c2016-05-21 05:12:32 +00003982 if (removeEmptyCleanup(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00003983 return true;
3984
3985 return false;
3986}
3987
Devang Pateldd14e0f2011-05-18 21:33:11 +00003988bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003989 BasicBlock *BB = RI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003990 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
3991 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003992
Chris Lattner25c3af32010-12-13 06:25:44 +00003993 // Find predecessors that end with branches.
Dehao Chenf6c00832016-05-18 19:44:21 +00003994 SmallVector<BasicBlock *, 8> UncondBranchPreds;
3995 SmallVector<BranchInst *, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003996 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3997 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003998 TerminatorInst *PTI = P->getTerminator();
3999 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4000 if (BI->isUnconditional())
4001 UncondBranchPreds.push_back(P);
4002 else
4003 CondBranchPreds.push_back(BI);
4004 }
4005 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004006
Chris Lattner25c3af32010-12-13 06:25:44 +00004007 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00004008 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004009 while (!UncondBranchPreds.empty()) {
4010 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4011 DEBUG(dbgs() << "FOLDING: " << *BB
Dehao Chenf6c00832016-05-18 19:44:21 +00004012 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00004013 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00004014 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004015
Chris Lattner25c3af32010-12-13 06:25:44 +00004016 // If we eliminated all predecessors of the block, delete the block now.
Hyojin Sung4673f102016-03-29 04:08:57 +00004017 if (pred_empty(BB)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004018 // We know there are no successors, so just nuke the block.
4019 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004020 if (LoopHeaders)
4021 LoopHeaders->erase(BB);
Hyojin Sung4673f102016-03-29 04:08:57 +00004022 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004023
Chris Lattner25c3af32010-12-13 06:25:44 +00004024 return true;
4025 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004026
Chris Lattner25c3af32010-12-13 06:25:44 +00004027 // Check out all of the conditional branches going to this return
4028 // instruction. If any of them just select between returns, change the
4029 // branch itself into a select/return pair.
4030 while (!CondBranchPreds.empty()) {
4031 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004032
Chris Lattner25c3af32010-12-13 06:25:44 +00004033 // Check to see if the non-BB successor is also a return block.
4034 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4035 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00004036 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004037 return true;
4038 }
4039 return false;
4040}
4041
Chris Lattner25c3af32010-12-13 06:25:44 +00004042bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
4043 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004044
Chris Lattner25c3af32010-12-13 06:25:44 +00004045 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004046
Chris Lattner25c3af32010-12-13 06:25:44 +00004047 // If there are any instructions immediately before the unreachable that can
4048 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004049 while (UI->getIterator() != BB->begin()) {
4050 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004051 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004052 // Do not delete instructions that can have side effects which might cause
4053 // the unreachable to not be reachable; specifically, calls and volatile
4054 // operations may have this effect.
Dehao Chenf6c00832016-05-18 19:44:21 +00004055 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4056 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004057
4058 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004059 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004060 if (SI->isVolatile())
4061 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004062 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004063 if (LI->isVolatile())
4064 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004065 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004066 if (RMWI->isVolatile())
4067 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004068 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004069 if (CXI->isVolatile())
4070 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004071 } else if (isa<CatchPadInst>(BBI)) {
4072 // A catchpad may invoke exception object constructors and such, which
4073 // in some languages can be arbitrary code, so be conservative by
4074 // default.
4075 // For CoreCLR, it just involves a type test, so can be removed.
4076 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4077 EHPersonality::CoreCLR)
4078 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004079 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4080 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004081 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004082 }
Bill Wendling55d875f2011-08-16 20:41:17 +00004083 // Note that deleting LandingPad's here is in fact okay, although it
4084 // involves a bit of subtle reasoning. If this inst is a LandingPad,
4085 // all the predecessors of this block will be the unwind edges of Invokes,
4086 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004087 }
4088
Eli Friedmanaac35b32011-03-09 00:48:33 +00004089 // Delete this instruction (any uses are guaranteed to be dead)
4090 if (!BBI->use_empty())
4091 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00004092 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00004093 Changed = true;
4094 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004095
Chris Lattner25c3af32010-12-13 06:25:44 +00004096 // If the unreachable instruction is the first in the block, take a gander
4097 // at all of the predecessors of this instruction, and simplify them.
Dehao Chenf6c00832016-05-18 19:44:21 +00004098 if (&BB->front() != UI)
4099 return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004100
Dehao Chenf6c00832016-05-18 19:44:21 +00004101 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner25c3af32010-12-13 06:25:44 +00004102 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4103 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00004104 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004105 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004106 if (BI->isUnconditional()) {
4107 if (BI->getSuccessor(0) == BB) {
4108 new UnreachableInst(TI->getContext(), TI);
4109 TI->eraseFromParent();
4110 Changed = true;
4111 }
4112 } else {
4113 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004114 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00004115 EraseTerminatorInstAndDCECond(BI);
4116 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004117 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00004118 EraseTerminatorInstAndDCECond(BI);
4119 Changed = true;
4120 }
4121 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004122 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Chandler Carruth0d256c02017-03-26 02:49:23 +00004123 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004124 if (i->getCaseSuccessor() != BB) {
Chandler Carruth0d256c02017-03-26 02:49:23 +00004125 ++i;
4126 continue;
Chris Lattner25c3af32010-12-13 06:25:44 +00004127 }
Chandler Carruth0d256c02017-03-26 02:49:23 +00004128 BB->removePredecessor(SI->getParent());
4129 i = SI->removeCase(i);
4130 e = SI->case_end();
4131 Changed = true;
4132 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004133 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4134 if (II->getUnwindDest() == BB) {
4135 removeUnwindEdge(TI->getParent());
4136 Changed = true;
4137 }
4138 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4139 if (CSI->getUnwindDest() == BB) {
4140 removeUnwindEdge(TI->getParent());
4141 Changed = true;
4142 continue;
4143 }
4144
4145 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4146 E = CSI->handler_end();
4147 I != E; ++I) {
4148 if (*I == BB) {
4149 CSI->removeHandler(I);
4150 --I;
4151 --E;
4152 Changed = true;
4153 }
4154 }
4155 if (CSI->getNumHandlers() == 0) {
4156 BasicBlock *CatchSwitchBB = CSI->getParent();
4157 if (CSI->hasUnwindDest()) {
4158 // Redirect preds to the unwind dest
4159 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4160 } else {
4161 // Rewrite all preds to unwind to caller (or from invoke to call).
4162 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4163 for (BasicBlock *EHPred : EHPreds)
4164 removeUnwindEdge(EHPred);
4165 }
4166 // The catchswitch is no longer reachable.
4167 new UnreachableInst(CSI->getContext(), CSI);
4168 CSI->eraseFromParent();
4169 Changed = true;
4170 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004171 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00004172 new UnreachableInst(TI->getContext(), TI);
4173 TI->eraseFromParent();
4174 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004175 }
4176 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004177
Chris Lattner25c3af32010-12-13 06:25:44 +00004178 // If this block is now dead, remove it.
Dehao Chenf6c00832016-05-18 19:44:21 +00004179 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004180 // We know there are no successors, so just nuke the block.
4181 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004182 if (LoopHeaders)
4183 LoopHeaders->erase(BB);
Chris Lattner25c3af32010-12-13 06:25:44 +00004184 return true;
4185 }
4186
4187 return Changed;
4188}
4189
Hans Wennborg68000082015-01-26 19:52:32 +00004190static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4191 assert(Cases.size() >= 1);
4192
4193 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4194 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4195 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4196 return false;
4197 }
4198 return true;
4199}
4200
4201/// Turn a switch with two reachable destinations into an integer range
4202/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004203static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004204 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004205
Hans Wennborg68000082015-01-26 19:52:32 +00004206 bool HasDefault =
4207 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004208
Hans Wennborg68000082015-01-26 19:52:32 +00004209 // Partition the cases into two sets with different destinations.
4210 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4211 BasicBlock *DestB = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004212 SmallVector<ConstantInt *, 16> CasesA;
4213 SmallVector<ConstantInt *, 16> CasesB;
Hans Wennborg68000082015-01-26 19:52:32 +00004214
Chandler Carruth927d8e62017-04-12 07:27:28 +00004215 for (auto Case : SI->cases()) {
4216 BasicBlock *Dest = Case.getCaseSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00004217 if (!DestA)
4218 DestA = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004219 if (Dest == DestA) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004220 CasesA.push_back(Case.getCaseValue());
Hans Wennborg68000082015-01-26 19:52:32 +00004221 continue;
4222 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004223 if (!DestB)
4224 DestB = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004225 if (Dest == DestB) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004226 CasesB.push_back(Case.getCaseValue());
Hans Wennborg68000082015-01-26 19:52:32 +00004227 continue;
4228 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004229 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004230 }
4231
Dehao Chenf6c00832016-05-18 19:44:21 +00004232 assert(DestA && DestB &&
4233 "Single-destination switch should have been folded.");
Hans Wennborg68000082015-01-26 19:52:32 +00004234 assert(DestA != DestB);
4235 assert(DestB != SI->getDefaultDest());
4236 assert(!CasesB.empty() && "There must be non-default cases.");
4237 assert(!CasesA.empty() || HasDefault);
4238
4239 // Figure out if one of the sets of cases form a contiguous range.
4240 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4241 BasicBlock *ContiguousDest = nullptr;
4242 BasicBlock *OtherDest = nullptr;
4243 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4244 ContiguousCases = &CasesA;
4245 ContiguousDest = DestA;
4246 OtherDest = DestB;
4247 } else if (CasesAreContiguous(CasesB)) {
4248 ContiguousCases = &CasesB;
4249 ContiguousDest = DestB;
4250 OtherDest = DestA;
4251 } else
4252 return false;
4253
4254 // Start building the compare and branch.
4255
4256 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
Dehao Chenf6c00832016-05-18 19:44:21 +00004257 Constant *NumCases =
4258 ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004259
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00004260 Value *Sub = SI->getCondition();
4261 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00004262 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4263
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004264 Value *Cmp;
4265 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00004266 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004267 Cmp = ConstantInt::getTrue(SI->getContext());
4268 else
4269 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00004270 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004271
Manman Ren56575552012-09-18 00:47:33 +00004272 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00004273 if (HasBranchWeights(SI)) {
4274 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00004275 GetBranchWeights(SI, Weights);
4276 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00004277 uint64_t TrueWeight = 0;
4278 uint64_t FalseWeight = 0;
4279 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4280 if (SI->getSuccessor(I) == ContiguousDest)
4281 TrueWeight += Weights[I];
4282 else
4283 FalseWeight += Weights[I];
4284 }
4285 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4286 TrueWeight /= 2;
4287 FalseWeight /= 2;
4288 }
Manman Ren56575552012-09-18 00:47:33 +00004289 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004290 MDBuilder(SI->getContext())
4291 .createBranchWeights((uint32_t)TrueWeight,
4292 (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00004293 }
4294 }
4295
Hans Wennborg68000082015-01-26 19:52:32 +00004296 // Prune obsolete incoming values off the successors' PHI nodes.
4297 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4298 unsigned PreviousEdges = ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004299 if (ContiguousDest == SI->getDefaultDest())
4300 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004301 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004302 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4303 }
Hans Wennborg68000082015-01-26 19:52:32 +00004304 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4305 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004306 if (OtherDest == SI->getDefaultDest())
4307 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004308 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4309 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4310 }
4311
4312 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004313 SI->eraseFromParent();
4314
4315 return true;
4316}
Chris Lattner25c3af32010-12-13 06:25:44 +00004317
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004318/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004319/// and use it to remove dead cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004320static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4321 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004322 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00004323 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Craig Topper8205a1a2017-05-24 16:53:07 +00004324 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004325
Sanjay Patel75892a12016-05-20 14:53:09 +00004326 // We can also eliminate cases by determining that their values are outside of
4327 // the limited range of the condition based on how many significant (non-sign)
4328 // bits are in the condition value.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004329 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
Sanjay Patel75892a12016-05-20 14:53:09 +00004330 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4331
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004332 // Gather dead cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00004333 SmallVector<ConstantInt *, 8> DeadCases;
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004334 for (auto &Case : SI->cases()) {
Craig Toppere777fed2017-05-22 00:49:35 +00004335 const APInt &CaseVal = Case.getCaseValue()->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00004336 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
Sanjay Patel75892a12016-05-20 14:53:09 +00004337 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004338 DeadCases.push_back(Case.getCaseValue());
Sanjay Patel75892a12016-05-20 14:53:09 +00004339 DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004340 }
4341 }
4342
Dehao Chenf6c00832016-05-18 19:44:21 +00004343 // If we can prove that the cases must cover all possible values, the
4344 // default destination becomes dead and we can remove it. If we know some
Philip Reames05370132015-09-10 17:44:47 +00004345 // of the bits in the value, we can use that to more precisely compute the
4346 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00004347 bool HasDefault =
Dehao Chenf6c00832016-05-18 19:44:21 +00004348 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4349 const unsigned NumUnknownBits =
Craig Topperb45eabc2017-04-26 16:39:58 +00004350 Bits - (Known.Zero | Known.One).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00004351 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00004352 if (HasDefault && DeadCases.empty() &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004353 NumUnknownBits < 64 /* avoid overflow */ &&
Philip Reames05370132015-09-10 17:44:47 +00004354 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00004355 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
Dehao Chenf6c00832016-05-18 19:44:21 +00004356 BasicBlock *NewDefault =
4357 SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004358 SI->setDefaultDest(&*NewDefault);
4359 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00004360 auto *OldTI = NewDefault->getTerminator();
4361 new UnreachableInst(SI->getContext(), OldTI);
4362 EraseTerminatorInstAndDCECond(OldTI);
4363 return true;
4364 }
4365
Manman Ren56575552012-09-18 00:47:33 +00004366 SmallVector<uint64_t, 8> Weights;
4367 bool HasWeight = HasBranchWeights(SI);
4368 if (HasWeight) {
4369 GetBranchWeights(SI, Weights);
4370 HasWeight = (Weights.size() == 1 + SI->getNumCases());
4371 }
4372
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004373 // Remove dead cases from the switch.
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004374 for (ConstantInt *DeadCase : DeadCases) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004375 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4376 assert(CaseI != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004377 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00004378 if (HasWeight) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004379 std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.back());
Manman Ren56575552012-09-18 00:47:33 +00004380 Weights.pop_back();
4381 }
4382
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004383 // Prune unused values from PHI nodes.
Chandler Carruth927d8e62017-04-12 07:27:28 +00004384 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4385 SI->removeCase(CaseI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004386 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00004387 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00004388 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4389 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004390 MDBuilder(SI->getParent()->getContext())
4391 .createBranchWeights(MDWeights));
Manman Ren56575552012-09-18 00:47:33 +00004392 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004393
4394 return !DeadCases.empty();
4395}
4396
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004397/// If BB would be eligible for simplification by
4398/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004399/// by an unconditional branch), look at the phi node for BB in the successor
4400/// block and see if the incoming value is equal to CaseValue. If so, return
4401/// the phi node, and set PhiIndex to BB's index in the phi node.
4402static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
Dehao Chenf6c00832016-05-18 19:44:21 +00004403 BasicBlock *BB, int *PhiIndex) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004404 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00004405 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004406 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00004407 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004408
4409 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4410 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00004411 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004412
4413 BasicBlock *Succ = Branch->getSuccessor(0);
4414
4415 BasicBlock::iterator I = Succ->begin();
4416 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4417 int Idx = PHI->getBasicBlockIndex(BB);
4418 assert(Idx >= 0 && "PHI has no entry for predecessor?");
4419
4420 Value *InValue = PHI->getIncomingValue(Idx);
Dehao Chenf6c00832016-05-18 19:44:21 +00004421 if (InValue != CaseValue)
4422 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004423
4424 *PhiIndex = Idx;
4425 return PHI;
4426 }
4427
Craig Topperf40110f2014-04-25 05:29:35 +00004428 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004429}
4430
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004431/// Try to forward the condition of a switch instruction to a phi node
4432/// dominated by the switch, if that would mean that some of the destination
4433/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004434/// Returns true if a change is made.
4435static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004436 typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004437 ForwardingNodesMap ForwardingNodes;
4438
Chandler Carruth927d8e62017-04-12 07:27:28 +00004439 for (auto Case : SI->cases()) {
4440 ConstantInt *CaseValue = Case.getCaseValue();
4441 BasicBlock *CaseDest = Case.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004442
4443 int PhiIndex;
Dehao Chenf6c00832016-05-18 19:44:21 +00004444 PHINode *PHI =
4445 FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex);
4446 if (!PHI)
4447 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004448
4449 ForwardingNodes[PHI].push_back(PhiIndex);
4450 }
4451
4452 bool Changed = false;
4453
4454 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
Dehao Chenf6c00832016-05-18 19:44:21 +00004455 E = ForwardingNodes.end();
4456 I != E; ++I) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004457 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00004458 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004459
Dehao Chenf6c00832016-05-18 19:44:21 +00004460 if (Indexes.size() < 2)
4461 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004462
4463 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
4464 Phi->setIncomingValue(Indexes[I], SI->getCondition());
4465 Changed = true;
4466 }
4467
4468 return Changed;
4469}
4470
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004471/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004472/// initializing an array of constants like C.
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004473static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00004474 if (C->isThreadDependent())
4475 return false;
4476 if (C->isDLLImportDependent())
4477 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004478
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004479 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4480 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4481 !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4482 return false;
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004483
Oliver Stannardfe4432b2016-10-17 12:00:24 +00004484 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004485 if (!CE->isGEPWithNoNotionalOverIndexing())
4486 return false;
Oliver Stannardfe4432b2016-10-17 12:00:24 +00004487 if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4488 return false;
4489 }
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004490
4491 if (!TTI.shouldBuildLookupTablesForConstant(C))
4492 return false;
4493
4494 return true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004495}
4496
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004497/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004498/// its constant value in ConstantPool, returning 0 if it's not there.
Dehao Chenf6c00832016-05-18 19:44:21 +00004499static Constant *
4500LookupConstant(Value *V,
4501 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004502 if (Constant *C = dyn_cast<Constant>(V))
4503 return C;
4504 return ConstantPool.lookup(V);
4505}
4506
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004507/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004508/// simple instructions such as binary operations where both operands are
4509/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004510/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004511static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004512ConstantFold(Instruction *I, const DataLayout &DL,
4513 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004514 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004515 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4516 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004517 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004518 if (A->isAllOnesValue())
4519 return LookupConstant(Select->getTrueValue(), ConstantPool);
4520 if (A->isNullValue())
4521 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004522 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004523 }
4524
Benjamin Kramer7c302602013-11-12 12:24:36 +00004525 SmallVector<Constant *, 4> COps;
4526 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4527 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4528 COps.push_back(A);
4529 else
Craig Topperf40110f2014-04-25 05:29:35 +00004530 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004531 }
4532
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004533 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004534 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4535 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004536 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004537
Manuel Jacobe9024592016-01-21 06:33:22 +00004538 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004539}
4540
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004541/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004542/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004543/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004544/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004545static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004546GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004547 BasicBlock **CommonDest,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004548 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004549 const DataLayout &DL, const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004550 // The block from which we enter the common destination.
4551 BasicBlock *Pred = SI->getParent();
4552
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004553 // If CaseDest is empty except for some side-effect free instructions through
4554 // which we can constant-propagate the CaseVal, continue to its successor.
Dehao Chenf6c00832016-05-18 19:44:21 +00004555 SmallDenseMap<Value *, Constant *> ConstantPool;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004556 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4557 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4558 ++I) {
4559 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4560 // If the terminator is a simple branch, continue to the next block.
David Majnemer8c03c1b2016-10-07 01:38:35 +00004561 if (T->getNumSuccessors() != 1 || T->isExceptional())
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004562 return false;
4563 Pred = CaseDest;
4564 CaseDest = T->getSuccessor(0);
4565 } else if (isa<DbgInfoIntrinsic>(I)) {
4566 // Skip debug intrinsic.
4567 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004568 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004569 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004570
4571 // If the instruction has uses outside this block or a phi node slot for
4572 // the block, it is not safe to bypass the instruction since it would then
4573 // no longer dominate all its uses.
4574 for (auto &Use : I->uses()) {
4575 User *User = Use.getUser();
4576 if (Instruction *I = dyn_cast<Instruction>(User))
4577 if (I->getParent() == CaseDest)
4578 continue;
4579 if (PHINode *Phi = dyn_cast<PHINode>(User))
4580 if (Phi->getIncomingBlock(Use) == CaseDest)
4581 continue;
4582 return false;
4583 }
4584
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004585 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004586 } else {
4587 break;
4588 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004589 }
4590
4591 // If we did not have a CommonDest before, use the current one.
4592 if (!*CommonDest)
4593 *CommonDest = CaseDest;
4594 // If the destination isn't the common one, abort.
4595 if (CaseDest != *CommonDest)
4596 return false;
4597
4598 // Get the values for this case from phi nodes in the destination block.
4599 BasicBlock::iterator I = (*CommonDest)->begin();
4600 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4601 int Idx = PHI->getBasicBlockIndex(Pred);
4602 if (Idx == -1)
4603 continue;
4604
Dehao Chenf6c00832016-05-18 19:44:21 +00004605 Constant *ConstVal =
4606 LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004607 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004608 return false;
4609
4610 // Be conservative about which kinds of constants we support.
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004611 if (!ValidLookupTableConstant(ConstVal, TTI))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004612 return false;
4613
4614 Res.push_back(std::make_pair(PHI, ConstVal));
4615 }
4616
Hans Wennborgac114a32014-01-12 00:44:41 +00004617 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004618}
4619
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004620// Helper function used to add CaseVal to the list of cases that generate
4621// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004622static void MapCaseToResult(ConstantInt *CaseVal,
Dehao Chenf6c00832016-05-18 19:44:21 +00004623 SwitchCaseResultVectorTy &UniqueResults,
4624 Constant *Result) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004625 for (auto &I : UniqueResults) {
4626 if (I.first == Result) {
4627 I.second.push_back(CaseVal);
4628 return;
4629 }
4630 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004631 UniqueResults.push_back(
4632 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004633}
4634
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004635// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004636// results for the PHI node of the common destination block for a switch
4637// instruction. Returns false if multiple PHI nodes have been found or if
4638// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004639static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4640 BasicBlock *&CommonDest,
4641 SwitchCaseResultVectorTy &UniqueResults,
4642 Constant *&DefaultResult,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004643 const DataLayout &DL,
4644 const TargetTransformInfo &TTI) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004645 for (auto &I : SI->cases()) {
4646 ConstantInt *CaseVal = I.getCaseValue();
4647
4648 // Resulting value at phi nodes for this case value.
4649 SwitchCaseResultsTy Results;
4650 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004651 DL, TTI))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004652 return false;
4653
4654 // Only one value per case is permitted
4655 if (Results.size() > 1)
4656 return false;
4657 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4658
4659 // Check the PHI consistency.
4660 if (!PHI)
4661 PHI = Results[0].first;
4662 else if (PHI != Results[0].first)
4663 return false;
4664 }
4665 // Find the default result value.
4666 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4667 BasicBlock *DefaultDest = SI->getDefaultDest();
4668 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004669 DL, TTI);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004670 // If the default value is not found abort unless the default destination
4671 // is unreachable.
4672 DefaultResult =
4673 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4674 if ((!DefaultResult &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004675 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004676 return false;
4677
4678 return true;
4679}
4680
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004681// Helper function that checks if it is possible to transform a switch with only
4682// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004683// Example:
4684// switch (a) {
4685// case 10: %0 = icmp eq i32 %a, 10
4686// return 10; %1 = select i1 %0, i32 10, i32 4
4687// case 20: ----> %2 = icmp eq i32 %a, 20
4688// return 2; %3 = select i1 %2, i32 2, i32 %1
4689// default:
4690// return 4;
4691// }
Dehao Chenf6c00832016-05-18 19:44:21 +00004692static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4693 Constant *DefaultResult, Value *Condition,
4694 IRBuilder<> &Builder) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004695 assert(ResultVector.size() == 2 &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004696 "We should have exactly two unique results at this point");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004697 // If we are selecting between only two cases transform into a simple
4698 // select or a two-way select if default is possible.
4699 if (ResultVector[0].second.size() == 1 &&
4700 ResultVector[1].second.size() == 1) {
4701 ConstantInt *const FirstCase = ResultVector[0].second[0];
4702 ConstantInt *const SecondCase = ResultVector[1].second[0];
4703
4704 bool DefaultCanTrigger = DefaultResult;
4705 Value *SelectValue = ResultVector[1].first;
4706 if (DefaultCanTrigger) {
4707 Value *const ValueCompare =
4708 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4709 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4710 DefaultResult, "switch.select");
4711 }
4712 Value *const ValueCompare =
4713 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
Dehao Chenf6c00832016-05-18 19:44:21 +00004714 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4715 SelectValue, "switch.select");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004716 }
4717
4718 return nullptr;
4719}
4720
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004721// Helper function to cleanup a switch instruction that has been converted into
4722// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004723static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4724 Value *SelectValue,
4725 IRBuilder<> &Builder) {
4726 BasicBlock *SelectBB = SI->getParent();
4727 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4728 PHI->removeIncomingValue(SelectBB);
4729 PHI->addIncoming(SelectValue, SelectBB);
4730
4731 Builder.CreateBr(PHI->getParent());
4732
4733 // Remove the switch.
4734 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4735 BasicBlock *Succ = SI->getSuccessor(i);
4736
4737 if (Succ == PHI->getParent())
4738 continue;
4739 Succ->removePredecessor(SelectBB);
4740 }
4741 SI->eraseFromParent();
4742}
4743
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004744/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004745/// phi nodes in a common successor block with only two different
4746/// constant values, replace the switch with select.
4747static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004748 AssumptionCache *AC, const DataLayout &DL,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004749 const TargetTransformInfo &TTI) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004750 Value *const Cond = SI->getCondition();
4751 PHINode *PHI = nullptr;
4752 BasicBlock *CommonDest = nullptr;
4753 Constant *DefaultResult;
4754 SwitchCaseResultVectorTy UniqueResults;
4755 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004756 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004757 DL, TTI))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004758 return false;
4759 // Selects choose between maximum two values.
4760 if (UniqueResults.size() != 2)
4761 return false;
4762 assert(PHI != nullptr && "PHI for value select not found");
4763
4764 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00004765 Value *SelectValue =
4766 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004767 if (SelectValue) {
4768 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4769 return true;
4770 }
4771 // The switch couldn't be converted into a select.
4772 return false;
4773}
4774
Hans Wennborg776d7122012-09-26 09:34:53 +00004775namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004776
Dehao Chenf6c00832016-05-18 19:44:21 +00004777/// This class represents a lookup table that can be used to replace a switch.
4778class SwitchLookupTable {
4779public:
4780 /// Create a lookup table to use as a switch replacement with the contents
4781 /// of Values, using DefaultValue to fill any holes in the table.
4782 SwitchLookupTable(
4783 Module &M, uint64_t TableSize, ConstantInt *Offset,
4784 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4785 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004786
Dehao Chenf6c00832016-05-18 19:44:21 +00004787 /// Build instructions with Builder to retrieve the value at
4788 /// the position given by Index in the lookup table.
4789 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004790
Dehao Chenf6c00832016-05-18 19:44:21 +00004791 /// Return true if a table with TableSize elements of
4792 /// type ElementType would fit in a target-legal register.
4793 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4794 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004795
Dehao Chenf6c00832016-05-18 19:44:21 +00004796private:
4797 // Depending on the contents of the table, it can be represented in
4798 // different ways.
4799 enum {
4800 // For tables where each element contains the same value, we just have to
4801 // store that single value and return it for each lookup.
4802 SingleValueKind,
Hans Wennborg776d7122012-09-26 09:34:53 +00004803
Dehao Chenf6c00832016-05-18 19:44:21 +00004804 // For tables where there is a linear relationship between table index
4805 // and values. We calculate the result with a simple multiplication
4806 // and addition instead of a table lookup.
4807 LinearMapKind,
Erik Eckstein105374f2014-11-17 09:13:57 +00004808
Dehao Chenf6c00832016-05-18 19:44:21 +00004809 // For small tables with integer elements, we can pack them into a bitmap
4810 // that fits into a target-legal register. Values are retrieved by
4811 // shift and mask operations.
4812 BitMapKind,
Hans Wennborg39583b82012-09-26 09:44:49 +00004813
Dehao Chenf6c00832016-05-18 19:44:21 +00004814 // The table is stored as an array of values. Values are retrieved by load
4815 // instructions from the table.
4816 ArrayKind
4817 } Kind;
Hans Wennborg776d7122012-09-26 09:34:53 +00004818
Dehao Chenf6c00832016-05-18 19:44:21 +00004819 // For SingleValueKind, this is the single value.
4820 Constant *SingleValue;
Hans Wennborg776d7122012-09-26 09:34:53 +00004821
Dehao Chenf6c00832016-05-18 19:44:21 +00004822 // For BitMapKind, this is the bitmap.
4823 ConstantInt *BitMap;
4824 IntegerType *BitMapElementTy;
Hans Wennborg39583b82012-09-26 09:44:49 +00004825
Dehao Chenf6c00832016-05-18 19:44:21 +00004826 // For LinearMapKind, these are the constants used to derive the value.
4827 ConstantInt *LinearOffset;
4828 ConstantInt *LinearMultiplier;
Erik Eckstein105374f2014-11-17 09:13:57 +00004829
Dehao Chenf6c00832016-05-18 19:44:21 +00004830 // For ArrayKind, this is the array.
4831 GlobalVariable *Array;
4832};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004833
4834} // end anonymous namespace
Hans Wennborg776d7122012-09-26 09:34:53 +00004835
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004836SwitchLookupTable::SwitchLookupTable(
4837 Module &M, uint64_t TableSize, ConstantInt *Offset,
4838 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4839 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004840 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004841 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004842 assert(Values.size() && "Can't build lookup table without values!");
4843 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004844
4845 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004846 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004847
Hans Wennborgac114a32014-01-12 00:44:41 +00004848 Type *ValueType = Values.begin()->second->getType();
4849
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004850 // Build up the table contents.
Dehao Chenf6c00832016-05-18 19:44:21 +00004851 SmallVector<Constant *, 64> TableContents(TableSize);
Hans Wennborg776d7122012-09-26 09:34:53 +00004852 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4853 ConstantInt *CaseVal = Values[I].first;
4854 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004855 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004856
Dehao Chenf6c00832016-05-18 19:44:21 +00004857 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004858 TableContents[Idx] = CaseRes;
4859
Hans Wennborg776d7122012-09-26 09:34:53 +00004860 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004861 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004862 }
4863
4864 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004865 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004866 assert(DefaultValue &&
4867 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004868 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004869 for (uint64_t I = 0; I < TableSize; ++I) {
4870 if (!TableContents[I])
4871 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004872 }
4873
Hans Wennborg776d7122012-09-26 09:34:53 +00004874 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004875 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004876 }
4877
Hans Wennborg776d7122012-09-26 09:34:53 +00004878 // If each element in the table contains the same value, we only need to store
4879 // that single value.
4880 if (SingleValue) {
4881 Kind = SingleValueKind;
4882 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004883 }
4884
Erik Eckstein105374f2014-11-17 09:13:57 +00004885 // Check if we can derive the value with a linear transformation from the
4886 // table index.
4887 if (isa<IntegerType>(ValueType)) {
4888 bool LinearMappingPossible = true;
4889 APInt PrevVal;
4890 APInt DistToPrev;
4891 assert(TableSize >= 2 && "Should be a SingleValue table.");
4892 // Check if there is the same distance between two consecutive values.
4893 for (uint64_t I = 0; I < TableSize; ++I) {
4894 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4895 if (!ConstVal) {
4896 // This is an undef. We could deal with it, but undefs in lookup tables
4897 // are very seldom. It's probably not worth the additional complexity.
4898 LinearMappingPossible = false;
4899 break;
4900 }
Craig Toppere777fed2017-05-22 00:49:35 +00004901 const APInt &Val = ConstVal->getValue();
Erik Eckstein105374f2014-11-17 09:13:57 +00004902 if (I != 0) {
4903 APInt Dist = Val - PrevVal;
4904 if (I == 1) {
4905 DistToPrev = Dist;
4906 } else if (Dist != DistToPrev) {
4907 LinearMappingPossible = false;
4908 break;
4909 }
4910 }
4911 PrevVal = Val;
4912 }
4913 if (LinearMappingPossible) {
4914 LinearOffset = cast<ConstantInt>(TableContents[0]);
4915 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4916 Kind = LinearMapKind;
4917 ++NumLinearMaps;
4918 return;
4919 }
4920 }
4921
Hans Wennborg39583b82012-09-26 09:44:49 +00004922 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004923 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004924 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004925 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4926 for (uint64_t I = TableSize; I > 0; --I) {
4927 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004928 // Insert values into the bitmap. Undef values are set to zero.
4929 if (!isa<UndefValue>(TableContents[I - 1])) {
4930 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4931 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4932 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004933 }
4934 BitMap = ConstantInt::get(M.getContext(), TableInt);
4935 BitMapElementTy = IT;
4936 Kind = BitMapKind;
4937 ++NumBitMaps;
4938 return;
4939 }
4940
Hans Wennborg776d7122012-09-26 09:34:53 +00004941 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004942 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004943 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4944
Dehao Chenf6c00832016-05-18 19:44:21 +00004945 Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
4946 GlobalVariable::PrivateLinkage, Initializer,
Hans Wennborg776d7122012-09-26 09:34:53 +00004947 "switch.table");
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004948 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Hans Wennborg776d7122012-09-26 09:34:53 +00004949 Kind = ArrayKind;
4950}
4951
Manman Ren4d189fb2014-07-24 21:13:20 +00004952Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004953 switch (Kind) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004954 case SingleValueKind:
4955 return SingleValue;
4956 case LinearMapKind: {
4957 // Derive the result value from the input value.
4958 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4959 false, "switch.idx.cast");
4960 if (!LinearMultiplier->isOne())
4961 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4962 if (!LinearOffset->isZero())
4963 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4964 return Result;
4965 }
4966 case BitMapKind: {
4967 // Type of the bitmap (e.g. i59).
4968 IntegerType *MapTy = BitMap->getType();
Hans Wennborg39583b82012-09-26 09:44:49 +00004969
Dehao Chenf6c00832016-05-18 19:44:21 +00004970 // Cast Index to the same type as the bitmap.
4971 // Note: The Index is <= the number of elements in the table, so
4972 // truncating it to the width of the bitmask is safe.
4973 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004974
Dehao Chenf6c00832016-05-18 19:44:21 +00004975 // Multiply the shift amount by the element width.
4976 ShiftAmt = Builder.CreateMul(
4977 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4978 "switch.shiftamt");
Hans Wennborg39583b82012-09-26 09:44:49 +00004979
Dehao Chenf6c00832016-05-18 19:44:21 +00004980 // Shift down.
4981 Value *DownShifted =
4982 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
4983 // Mask off.
4984 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
4985 }
4986 case ArrayKind: {
4987 // Make sure the table index will not overflow when treated as signed.
4988 IntegerType *IT = cast<IntegerType>(Index->getType());
4989 uint64_t TableSize =
4990 Array->getInitializer()->getType()->getArrayNumElements();
4991 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4992 Index = Builder.CreateZExt(
4993 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
4994 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004995
Dehao Chenf6c00832016-05-18 19:44:21 +00004996 Value *GEPIndices[] = {Builder.getInt32(0), Index};
4997 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4998 GEPIndices, "switch.gep");
4999 return Builder.CreateLoad(GEP, "switch.load");
5000 }
Hans Wennborg776d7122012-09-26 09:34:53 +00005001 }
5002 llvm_unreachable("Unknown lookup table kind!");
5003}
5004
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005005bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00005006 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00005007 Type *ElementType) {
5008 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00005009 if (!IT)
5010 return false;
5011 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5012 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00005013
5014 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
Dehao Chenf6c00832016-05-18 19:44:21 +00005015 if (TableSize >= UINT_MAX / IT->getBitWidth())
Benjamin Kramerc2081d12012-09-27 18:29:58 +00005016 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005017 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00005018}
5019
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005020/// Determine whether a lookup table should be built for this switch, based on
5021/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005022static bool
5023ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5024 const TargetTransformInfo &TTI, const DataLayout &DL,
5025 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00005026 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5027 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00005028
Chandler Carruth77d433d2012-11-30 09:26:25 +00005029 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00005030 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00005031 for (const auto &I : ResultTypes) {
5032 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005033
5034 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005035 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005036
5037 // Saturate this flag to false.
Dehao Chenf6c00832016-05-18 19:44:21 +00005038 AllTablesFitInRegister =
5039 AllTablesFitInRegister &&
5040 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005041
5042 // If both flags saturate, we're done. NOTE: This *only* works with
5043 // saturating flags, and all flags have to saturate first due to the
5044 // non-deterministic behavior of iterating over a dense map.
5045 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00005046 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00005047 }
Evan Cheng65df8082012-11-30 02:02:42 +00005048
Chandler Carruth77d433d2012-11-30 09:26:25 +00005049 // If each table would fit in a register, we should build it anyway.
5050 if (AllTablesFitInRegister)
5051 return true;
5052
5053 // Don't build a table that doesn't fit in-register if it has illegal types.
5054 if (HasIllegalType)
5055 return false;
5056
5057 // The table density should be at least 40%. This is the same criterion as for
5058 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5059 // FIXME: Find the best cut-off.
5060 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005061}
5062
Erik Eckstein0d86c762014-11-27 15:13:14 +00005063/// Try to reuse the switch table index compare. Following pattern:
5064/// \code
5065/// if (idx < tablesize)
5066/// r = table[idx]; // table does not contain default_value
5067/// else
5068/// r = default_value;
5069/// if (r != default_value)
5070/// ...
5071/// \endcode
5072/// Is optimized to:
5073/// \code
5074/// cond = idx < tablesize;
5075/// if (cond)
5076/// r = table[idx];
5077/// else
5078/// r = default_value;
5079/// if (cond)
5080/// ...
5081/// \endcode
5082/// Jump threading will then eliminate the second if(cond).
Dehao Chenf6c00832016-05-18 19:44:21 +00005083static void reuseTableCompare(
5084 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5085 Constant *DefaultValue,
5086 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
Erik Eckstein0d86c762014-11-27 15:13:14 +00005087
5088 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5089 if (!CmpInst)
5090 return;
5091
5092 // We require that the compare is in the same block as the phi so that jump
5093 // threading can do its work afterwards.
5094 if (CmpInst->getParent() != PhiBlock)
5095 return;
5096
5097 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5098 if (!CmpOp1)
5099 return;
5100
5101 Value *RangeCmp = RangeCheckBranch->getCondition();
5102 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5103 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5104
5105 // Check if the compare with the default value is constant true or false.
5106 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5107 DefaultValue, CmpOp1, true);
5108 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5109 return;
5110
5111 // Check if the compare with the case values is distinct from the default
5112 // compare result.
5113 for (auto ValuePair : Values) {
5114 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
Dehao Chenf6c00832016-05-18 19:44:21 +00005115 ValuePair.second, CmpOp1, true);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005116 if (!CaseConst || CaseConst == DefaultConst)
5117 return;
5118 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5119 "Expect true or false as compare result.");
5120 }
Dehao Chenf6c00832016-05-18 19:44:21 +00005121
Erik Eckstein0d86c762014-11-27 15:13:14 +00005122 // Check if the branch instruction dominates the phi node. It's a simple
5123 // dominance check, but sufficient for our needs.
5124 // Although this check is invariant in the calling loops, it's better to do it
5125 // at this late stage. Practically we do it at most once for a switch.
5126 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5127 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5128 BasicBlock *Pred = *PI;
5129 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5130 return;
5131 }
5132
5133 if (DefaultConst == FalseConst) {
5134 // The compare yields the same result. We can replace it.
5135 CmpInst->replaceAllUsesWith(RangeCmp);
5136 ++NumTableCmpReuses;
5137 } else {
5138 // The compare yields the same result, just inverted. We can replace it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005139 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5140 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5141 RangeCheckBranch);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005142 CmpInst->replaceAllUsesWith(InvertedTableCmp);
5143 ++NumTableCmpReuses;
5144 }
5145}
5146
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005147/// If the switch is only used to initialize one or more phi nodes in a common
5148/// successor block with different constant values, replace the switch with
5149/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005150static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5151 const DataLayout &DL,
5152 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005153 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00005154
Hans Wennborgc3c8d952012-11-07 21:35:12 +00005155 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005156 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00005157 return false;
5158
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005159 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5160 // split off a dense part and build a lookup table for that.
5161
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005162 // FIXME: This creates arrays of GEPs to constant strings, which means each
5163 // GEP needs a runtime relocation in PIC code. We should just build one big
5164 // string and lookup indices into that.
5165
Dehao Chenf6c00832016-05-18 19:44:21 +00005166 // Ignore switches with less than three cases. Lookup tables will not make
5167 // them
Hans Wennborg4744ac12014-01-15 05:00:27 +00005168 // faster, so we don't analyze them.
5169 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005170 return false;
5171
5172 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00005173 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005174 assert(SI->case_begin() != SI->case_end());
5175 SwitchInst::CaseIt CI = SI->case_begin();
Chandler Carruth927d8e62017-04-12 07:27:28 +00005176 ConstantInt *MinCaseVal = CI->getCaseValue();
5177 ConstantInt *MaxCaseVal = CI->getCaseValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005178
Craig Topperf40110f2014-04-25 05:29:35 +00005179 BasicBlock *CommonDest = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00005180 typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy;
5181 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5182 SmallDenseMap<PHINode *, Constant *> DefaultResults;
5183 SmallDenseMap<PHINode *, Type *> ResultTypes;
5184 SmallVector<PHINode *, 4> PHIs;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005185
5186 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00005187 ConstantInt *CaseVal = CI->getCaseValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005188 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5189 MinCaseVal = CaseVal;
5190 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5191 MaxCaseVal = CaseVal;
5192
5193 // Resulting value at phi nodes for this case value.
Dehao Chenf6c00832016-05-18 19:44:21 +00005194 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005195 ResultsTy Results;
Chandler Carruth927d8e62017-04-12 07:27:28 +00005196 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00005197 Results, DL, TTI))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005198 return false;
5199
5200 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005201 for (const auto &I : Results) {
5202 PHINode *PHI = I.first;
5203 Constant *Value = I.second;
5204 if (!ResultLists.count(PHI))
5205 PHIs.push_back(PHI);
5206 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005207 }
5208 }
5209
Hans Wennborgac114a32014-01-12 00:44:41 +00005210 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005211 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00005212 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5213 }
5214
5215 uint64_t NumResults = ResultLists[PHIs[0]].size();
5216 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5217 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5218 bool TableHasHoles = (NumResults < TableSize);
5219
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005220 // If the table has holes, we need a constant result for the default case
5221 // or a bitmask that fits in a register.
Dehao Chenf6c00832016-05-18 19:44:21 +00005222 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
Oliver Stannard4df1cc02016-10-07 08:48:24 +00005223 bool HasDefaultResults =
5224 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5225 DefaultResultsList, DL, TTI);
Hans Wennborga6a11a92014-11-18 02:37:11 +00005226
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005227 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5228 if (NeedMask) {
5229 // As an extra penalty for the validity test we require more cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00005230 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005231 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005232 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005233 return false;
5234 }
Hans Wennborgac114a32014-01-12 00:44:41 +00005235
Hans Wennborga6a11a92014-11-18 02:37:11 +00005236 for (const auto &I : DefaultResultsList) {
5237 PHINode *PHI = I.first;
5238 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00005239 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005240 }
5241
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005242 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005243 return false;
5244
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005245 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00005246 Module &Mod = *CommonDest->getParent()->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00005247 BasicBlock *LookupBB = BasicBlock::Create(
5248 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005249
Michael Gottesmanc024f322013-10-20 07:04:37 +00005250 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005251 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00005252 Value *TableIndex =
5253 Builder.CreateSub(SI->getCondition(), MinCaseVal, "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00005254
5255 // Compute the maximum table size representable by the integer type we are
5256 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005257 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00005258 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00005259 assert(MaxTableSize >= TableSize &&
5260 "It is impossible for a switch to have more entries than the max "
5261 "representable value of its input integer type's size.");
5262
Hans Wennborgb64cb272015-01-26 19:52:34 +00005263 // If the default destination is unreachable, or if the lookup table covers
5264 // all values of the conditional variable, branch directly to the lookup table
5265 // BB. Otherwise, check that the condition is within the case range.
5266 const bool DefaultIsReachable =
5267 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5268 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005269 BranchInst *RangeCheckBranch = nullptr;
5270
Hans Wennborgb64cb272015-01-26 19:52:34 +00005271 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00005272 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00005273 // Note: We call removeProdecessor later since we need to be able to get the
5274 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00005275 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005276 Value *Cmp = Builder.CreateICmpULT(
5277 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5278 RangeCheckBranch =
5279 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00005280 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005281
5282 // Populate the BB that does the lookups.
5283 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005284
5285 if (NeedMask) {
5286 // Before doing the lookup we do the hole check.
5287 // The LookupBB is therefore re-purposed to do the hole check
5288 // and we create a new LookupBB.
5289 BasicBlock *MaskBB = LookupBB;
5290 MaskBB->setName("switch.hole_check");
Dehao Chenf6c00832016-05-18 19:44:21 +00005291 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5292 CommonDest->getParent(), CommonDest);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005293
Juergen Ributzkac9591e92014-11-17 19:39:56 +00005294 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
5295 // unnecessary illegal types.
5296 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5297 APInt MaskInt(TableSizePowOf2, 0);
5298 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005299 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005300 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5301 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005302 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5303 .getLimitedValue();
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005304 MaskInt |= One << Idx;
5305 }
5306 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5307
5308 // Get the TableIndex'th bit of the bitmask.
5309 // If this bit is 0 (meaning hole) jump to the default destination,
5310 // else continue with table lookup.
5311 IntegerType *MapTy = TableMask->getType();
Dehao Chenf6c00832016-05-18 19:44:21 +00005312 Value *MaskIndex =
5313 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5314 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5315 Value *LoBit = Builder.CreateTrunc(
5316 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005317 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5318
5319 Builder.SetInsertPoint(LookupBB);
5320 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5321 }
5322
Hans Wennborg86ac6302015-04-24 20:57:56 +00005323 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5324 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
5325 // do not delete PHINodes here.
5326 SI->getDefaultDest()->removePredecessor(SI->getParent(),
5327 /*DontDeleteUselessPHIs=*/true);
5328 }
5329
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005330 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00005331 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5332 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005333 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005334
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005335 // If using a bitmask, use any value to fill the lookup table holes.
5336 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005337 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00005338
Manman Ren4d189fb2014-07-24 21:13:20 +00005339 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005340
Hans Wennborgf744fa92012-09-19 14:24:21 +00005341 // If the result is used to return immediately from the function, we want to
5342 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005343 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5344 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00005345 Builder.CreateRet(Result);
5346 ReturnedEarly = true;
5347 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005348 }
5349
Erik Eckstein0d86c762014-11-27 15:13:14 +00005350 // Do a small peephole optimization: re-use the switch table compare if
5351 // possible.
5352 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5353 BasicBlock *PhiBlock = PHI->getParent();
5354 // Search for compare instructions which use the phi.
5355 for (auto *User : PHI->users()) {
5356 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5357 }
5358 }
5359
Hans Wennborgf744fa92012-09-19 14:24:21 +00005360 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005361 }
5362
5363 if (!ReturnedEarly)
5364 Builder.CreateBr(CommonDest);
5365
5366 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005367 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005368 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00005369
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005370 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00005371 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005372 Succ->removePredecessor(SI->getParent());
5373 }
5374 SI->eraseFromParent();
5375
5376 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005377 if (NeedMask)
5378 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005379 return true;
5380}
5381
James Molloyb2e436d2016-08-01 07:45:11 +00005382static bool isSwitchDense(ArrayRef<int64_t> Values) {
5383 // See also SelectionDAGBuilder::isDense(), which this function was based on.
5384 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5385 uint64_t Range = Diff + 1;
5386 uint64_t NumCases = Values.size();
5387 // 40% is the default density for building a jump table in optsize/minsize mode.
5388 uint64_t MinDensity = 40;
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005389
James Molloyb2e436d2016-08-01 07:45:11 +00005390 return NumCases * 100 >= Range * MinDensity;
5391}
5392
5393// Try and transform a switch that has "holes" in it to a contiguous sequence
5394// of cases.
5395//
5396// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5397// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5398//
5399// This converts a sparse switch into a dense switch which allows better
5400// lowering and could also allow transforming into a lookup table.
5401static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5402 const DataLayout &DL,
5403 const TargetTransformInfo &TTI) {
5404 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5405 if (CondTy->getIntegerBitWidth() > 64 ||
5406 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5407 return false;
5408 // Only bother with this optimization if there are more than 3 switch cases;
5409 // SDAG will only bother creating jump tables for 4 or more cases.
5410 if (SI->getNumCases() < 4)
5411 return false;
5412
5413 // This transform is agnostic to the signedness of the input or case values. We
5414 // can treat the case values as signed or unsigned. We can optimize more common
5415 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5416 // as signed.
5417 SmallVector<int64_t,4> Values;
5418 for (auto &C : SI->cases())
5419 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5420 std::sort(Values.begin(), Values.end());
5421
5422 // If the switch is already dense, there's nothing useful to do here.
5423 if (isSwitchDense(Values))
5424 return false;
5425
5426 // First, transform the values such that they start at zero and ascend.
5427 int64_t Base = Values[0];
5428 for (auto &V : Values)
5429 V -= Base;
5430
5431 // Now we have signed numbers that have been shifted so that, given enough
5432 // precision, there are no negative values. Since the rest of the transform
5433 // is bitwise only, we switch now to an unsigned representation.
5434 uint64_t GCD = 0;
5435 for (auto &V : Values)
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005436 GCD = GreatestCommonDivisor64(GCD, (uint64_t)V);
James Molloyb2e436d2016-08-01 07:45:11 +00005437
5438 // This transform can be done speculatively because it is so cheap - it results
5439 // in a single rotate operation being inserted. This can only happen if the
5440 // factor extracted is a power of 2.
5441 // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5442 // inverse of GCD and then perform this transform.
5443 // FIXME: It's possible that optimizing a switch on powers of two might also
5444 // be beneficial - flag values are often powers of two and we could use a CLZ
5445 // as the key function.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005446 if (GCD <= 1 || !isPowerOf2_64(GCD))
James Molloyb2e436d2016-08-01 07:45:11 +00005447 // No common divisor found or too expensive to compute key function.
5448 return false;
5449
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005450 unsigned Shift = Log2_64(GCD);
James Molloyb2e436d2016-08-01 07:45:11 +00005451 for (auto &V : Values)
5452 V = (int64_t)((uint64_t)V >> Shift);
5453
5454 if (!isSwitchDense(Values))
5455 // Transform didn't create a dense switch.
5456 return false;
5457
5458 // The obvious transform is to shift the switch condition right and emit a
5459 // check that the condition actually cleanly divided by GCD, i.e.
5460 // C & (1 << Shift - 1) == 0
5461 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5462 //
5463 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5464 // shift and puts the shifted-off bits in the uppermost bits. If any of these
5465 // are nonzero then the switch condition will be very large and will hit the
5466 // default case.
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005467
James Molloyb2e436d2016-08-01 07:45:11 +00005468 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5469 Builder.SetInsertPoint(SI);
5470 auto *ShiftC = ConstantInt::get(Ty, Shift);
5471 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
Benjamin Krameraa160c22016-08-05 14:55:02 +00005472 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5473 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5474 auto *Rot = Builder.CreateOr(LShr, Shl);
James Molloyb2e436d2016-08-01 07:45:11 +00005475 SI->replaceUsesOfWith(SI->getCondition(), Rot);
5476
Chandler Carruth927d8e62017-04-12 07:27:28 +00005477 for (auto Case : SI->cases()) {
5478 auto *Orig = Case.getCaseValue();
James Molloyb2e436d2016-08-01 07:45:11 +00005479 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005480 Case.setValue(
James Molloybade86c2016-08-01 09:34:48 +00005481 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
James Molloyb2e436d2016-08-01 07:45:11 +00005482 }
5483 return true;
5484}
5485
Devang Patela7ec47d2011-05-18 20:35:38 +00005486bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005487 BasicBlock *BB = SI->getParent();
5488
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005489 if (isValueEqualityComparison(SI)) {
5490 // If we only have one predecessor, and if it is a branch on this value,
5491 // see if that predecessor totally determines the outcome of this switch.
5492 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5493 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005494 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005495
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005496 Value *Cond = SI->getCondition();
5497 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5498 if (SimplifySwitchOnSelect(SI, Select))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005499 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005500
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005501 // If the block only contains the switch, see if we can fold the block
5502 // away into any preds.
5503 BasicBlock::iterator BBI = BB->begin();
5504 // Ignore dbg intrinsics.
5505 while (isa<DbgInfoIntrinsic>(BBI))
5506 ++BBI;
5507 if (SI == &*BBI)
5508 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005509 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005510 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00005511
5512 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00005513 if (TurnSwitchRangeIntoICmp(SI, Builder))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005514 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005515
5516 // Remove unreachable cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005517 if (EliminateDeadSwitchCases(SI, AC, DL))
5518 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005519
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005520 if (SwitchToSelect(SI, Builder, AC, DL, TTI))
5521 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00005522
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005523 if (ForwardSwitchConditionToPHI(SI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005524 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005525
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +00005526 // The conversion from switch to lookup tables results in difficult
5527 // to analyze code and makes pruning branches much harder.
5528 // This is a problem of the switch expression itself can still be
5529 // restricted as a result of inlining or CVP. There only apply this
5530 // transformation during late steps of the optimisation chain.
5531 if (LateSimplifyCFG && SwitchToLookupTable(SI, Builder, DL, TTI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005532 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005533
James Molloyb2e436d2016-08-01 07:45:11 +00005534 if (ReduceSwitchRange(SI, Builder, DL, TTI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005535 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
James Molloyb2e436d2016-08-01 07:45:11 +00005536
Chris Lattner25c3af32010-12-13 06:25:44 +00005537 return false;
5538}
5539
5540bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5541 BasicBlock *BB = IBI->getParent();
5542 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005543
Chris Lattner25c3af32010-12-13 06:25:44 +00005544 // Eliminate redundant destinations.
5545 SmallPtrSet<Value *, 8> Succs;
5546 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5547 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00005548 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005549 Dest->removePredecessor(BB);
5550 IBI->removeDestination(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00005551 --i;
5552 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00005553 Changed = true;
5554 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005555 }
Chris Lattner25c3af32010-12-13 06:25:44 +00005556
5557 if (IBI->getNumDestinations() == 0) {
5558 // If the indirectbr has no successors, change it to unreachable.
5559 new UnreachableInst(IBI->getContext(), IBI);
5560 EraseTerminatorInstAndDCECond(IBI);
5561 return true;
5562 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005563
Chris Lattner25c3af32010-12-13 06:25:44 +00005564 if (IBI->getNumDestinations() == 1) {
5565 // If the indirectbr has one successor, change it to a direct branch.
5566 BranchInst::Create(IBI->getDestination(0), IBI);
5567 EraseTerminatorInstAndDCECond(IBI);
5568 return true;
5569 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005570
Chris Lattner25c3af32010-12-13 06:25:44 +00005571 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5572 if (SimplifyIndirectBrOnSelect(IBI, SI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005573 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005574 }
5575 return Changed;
5576}
5577
Philip Reames2b969d72015-03-24 22:28:45 +00005578/// Given an block with only a single landing pad and a unconditional branch
5579/// try to find another basic block which this one can be merged with. This
5580/// handles cases where we have multiple invokes with unique landing pads, but
5581/// a shared handler.
5582///
5583/// We specifically choose to not worry about merging non-empty blocks
5584/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
5585/// practice, the optimizer produces empty landing pad blocks quite frequently
5586/// when dealing with exception dense code. (see: instcombine, gvn, if-else
5587/// sinking in this file)
5588///
5589/// This is primarily a code size optimization. We need to avoid performing
5590/// any transform which might inhibit optimization (such as our ability to
5591/// specialize a particular handler via tail commoning). We do this by not
5592/// merging any blocks which require us to introduce a phi. Since the same
5593/// values are flowing through both blocks, we don't loose any ability to
5594/// specialize. If anything, we make such specialization more likely.
5595///
5596/// TODO - This transformation could remove entries from a phi in the target
5597/// block when the inputs in the phi are the same for the two blocks being
5598/// merged. In some cases, this could result in removal of the PHI entirely.
5599static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5600 BasicBlock *BB) {
5601 auto Succ = BB->getUniqueSuccessor();
5602 assert(Succ);
5603 // If there's a phi in the successor block, we'd likely have to introduce
5604 // a phi into the merged landing pad block.
5605 if (isa<PHINode>(*Succ->begin()))
5606 return false;
5607
5608 for (BasicBlock *OtherPred : predecessors(Succ)) {
5609 if (BB == OtherPred)
5610 continue;
5611 BasicBlock::iterator I = OtherPred->begin();
5612 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5613 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5614 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00005615 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5616 }
Philip Reames2b969d72015-03-24 22:28:45 +00005617 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5618 if (!BI2 || !BI2->isIdenticalTo(BI))
5619 continue;
5620
David Majnemer1efa23d2016-02-20 01:07:45 +00005621 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005622 // path instead and make ourselves dead.
5623 SmallSet<BasicBlock *, 16> Preds;
5624 Preds.insert(pred_begin(BB), pred_end(BB));
5625 for (BasicBlock *Pred : Preds) {
5626 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +00005627 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5628 "unexpected successor");
Philip Reames2b969d72015-03-24 22:28:45 +00005629 II->setUnwindDest(OtherPred);
5630 }
5631
5632 // The debug info in OtherPred doesn't cover the merged control flow that
5633 // used to go through BB. We need to delete it or update it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005634 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5635 Instruction &Inst = *I;
5636 I++;
Philip Reames2b969d72015-03-24 22:28:45 +00005637 if (isa<DbgInfoIntrinsic>(Inst))
5638 Inst.eraseFromParent();
5639 }
5640
5641 SmallSet<BasicBlock *, 16> Succs;
5642 Succs.insert(succ_begin(BB), succ_end(BB));
5643 for (BasicBlock *Succ : Succs) {
5644 Succ->removePredecessor(BB);
5645 }
5646
5647 IRBuilder<> Builder(BI);
5648 Builder.CreateUnreachable();
5649 BI->eraseFromParent();
5650 return true;
5651 }
5652 return false;
5653}
5654
Dehao Chenf6c00832016-05-18 19:44:21 +00005655bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5656 IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005657 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005658
Manman Ren93ab6492012-09-20 22:37:36 +00005659 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5660 return true;
Reid Klecknerbca59d22016-05-02 19:43:22 +00005661
5662 // If the Terminator is the only non-phi instruction, simplify the block.
5663 // if LoopHeader is provided, check if the block is a loop header
Hyojin Sung4673f102016-03-29 04:08:57 +00005664 // (This is for early invocations before loop simplify and vectorization
5665 // to keep canonical loop forms for nested loops.
5666 // These blocks can be eliminated when the pass is invoked later
5667 // in the back-end.)
Reid Klecknerbca59d22016-05-02 19:43:22 +00005668 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005669 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
Hans Wennborge9134892016-04-11 20:35:01 +00005670 (!LoopHeaders || !LoopHeaders->count(BB)) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00005671 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5672 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005673
Chris Lattner25c3af32010-12-13 06:25:44 +00005674 // If the only instruction in the block is a seteq/setne comparison
5675 // against a constant, try to simplify the block.
5676 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5677 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5678 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5679 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005680 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005681 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005682 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005683 return true;
5684 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005685
Philip Reames2b969d72015-03-24 22:28:45 +00005686 // See if we can merge an empty landing pad block with another which is
5687 // equivalent.
5688 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005689 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5690 }
5691 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
Philip Reames2b969d72015-03-24 22:28:45 +00005692 return true;
5693 }
5694
Manman Rend33f4ef2012-06-13 05:43:29 +00005695 // If this basic block is ONLY a compare and a branch, and if a predecessor
5696 // branches to us and our successor, fold the comparison into the
5697 // predecessor and use logical operations to update the incoming value
5698 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005699 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005700 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005701 return false;
5702}
5703
James Molloy4de84dd2015-11-04 15:28:04 +00005704static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5705 BasicBlock *PredPred = nullptr;
5706 for (auto *P : predecessors(BB)) {
5707 BasicBlock *PPred = P->getSinglePredecessor();
5708 if (!PPred || (PredPred && PredPred != PPred))
5709 return nullptr;
5710 PredPred = PPred;
5711 }
5712 return PredPred;
5713}
Chris Lattner25c3af32010-12-13 06:25:44 +00005714
Devang Patela7ec47d2011-05-18 20:35:38 +00005715bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005716 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005717
Chris Lattner25c3af32010-12-13 06:25:44 +00005718 // Conditional branch
5719 if (isValueEqualityComparison(BI)) {
5720 // If we only have one predecessor, and if it is a branch on this value,
5721 // see if that predecessor totally determines the outcome of this
5722 // switch.
5723 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005724 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005725 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005726
Chris Lattner25c3af32010-12-13 06:25:44 +00005727 // This block must be empty, except for the setcond inst, if it exists.
5728 // Ignore dbg intrinsics.
5729 BasicBlock::iterator I = BB->begin();
5730 // Ignore dbg intrinsics.
5731 while (isa<DbgInfoIntrinsic>(I))
5732 ++I;
5733 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005734 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005735 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005736 } else if (&*I == cast<Instruction>(BI->getCondition())) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005737 ++I;
5738 // Ignore dbg intrinsics.
5739 while (isa<DbgInfoIntrinsic>(I))
5740 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005741 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005742 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005743 }
5744 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005745
Chris Lattner25c3af32010-12-13 06:25:44 +00005746 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005747 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005748 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005749
Chad Rosier4ab37c02016-05-06 14:25:14 +00005750 // If this basic block has a single dominating predecessor block and the
5751 // dominating block's condition implies BI's condition, we know the direction
5752 // of the BI branch.
5753 if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5754 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5755 if (PBI && PBI->isConditional() &&
5756 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
5757 (PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB)) {
5758 bool CondIsFalse = PBI->getSuccessor(1) == BB;
5759 Optional<bool> Implication = isImpliedCondition(
5760 PBI->getCondition(), BI->getCondition(), DL, CondIsFalse);
5761 if (Implication) {
5762 // Turn this into a branch on constant.
5763 auto *OldCond = BI->getCondition();
5764 ConstantInt *CI = *Implication
5765 ? ConstantInt::getTrue(BB->getContext())
5766 : ConstantInt::getFalse(BB->getContext());
5767 BI->setCondition(CI);
5768 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005769 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chad Rosier4ab37c02016-05-06 14:25:14 +00005770 }
5771 }
5772 }
5773
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005774 // If this basic block is ONLY a compare and a branch, and if a predecessor
5775 // branches to us and one of our successors, fold the comparison into the
5776 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005777 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005778 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005779
Chris Lattner25c3af32010-12-13 06:25:44 +00005780 // We have a conditional branch to two blocks that are only reachable
5781 // from BI. We know that the condbr dominates the two blocks, so see if
5782 // there is any identical code in the "then" and "else" blocks. If so, we
5783 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005784 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5785 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005786 if (HoistThenElseCodeToIf(BI, TTI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005787 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005788 } else {
5789 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005790 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005791 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5792 if (Succ0TI->getNumSuccessors() == 1 &&
5793 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005794 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005795 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005796 }
Craig Topperf40110f2014-04-25 05:29:35 +00005797 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005798 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005799 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005800 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5801 if (Succ1TI->getNumSuccessors() == 1 &&
5802 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005803 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005804 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005805 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005806
Chris Lattner25c3af32010-12-13 06:25:44 +00005807 // If this is a branch on a phi node in the current block, thread control
5808 // through this block if any PHI node entries are constants.
5809 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5810 if (PN->getParent() == BI->getParent())
Peter Collingbourne0609acc2017-02-15 03:01:11 +00005811 if (FoldCondBranchOnPHI(BI, DL, AC))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005812 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005813
Chris Lattner25c3af32010-12-13 06:25:44 +00005814 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005815 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5816 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005817 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005818 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005819 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005820
James Molloy4de84dd2015-11-04 15:28:04 +00005821 // Look for diamond patterns.
5822 if (MergeCondStores)
5823 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5824 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5825 if (PBI != BI && PBI->isConditional())
5826 if (mergeConditionalStores(PBI, BI))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005827 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005828
Chris Lattner25c3af32010-12-13 06:25:44 +00005829 return false;
5830}
5831
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005832/// Check if passing a value to an instruction will cause undefined behavior.
5833static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5834 Constant *C = dyn_cast<Constant>(V);
5835 if (!C)
5836 return false;
5837
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005838 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005839 return false;
5840
David Majnemer1fea77c2016-06-25 07:37:27 +00005841 if (C->isNullValue() || isa<UndefValue>(C)) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005842 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005843 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005844
5845 // Now make sure that there are no instructions in between that can alter
5846 // control flow (eg. calls)
Duncan P. N. Exon Smith0a12729f2016-08-16 23:57:56 +00005847 for (BasicBlock::iterator
5848 i = ++BasicBlock::iterator(I),
5849 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5850 i != UI; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005851 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005852 return false;
5853
5854 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5855 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5856 if (GEP->getPointerOperand() == I)
5857 return passingValueIsAlwaysUndefined(V, GEP);
5858
5859 // Look through bitcasts.
5860 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5861 return passingValueIsAlwaysUndefined(V, BC);
5862
Benjamin Kramer0655b782011-08-26 02:25:55 +00005863 // Load from null is undefined.
5864 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005865 if (!LI->isVolatile())
5866 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005867
Benjamin Kramer0655b782011-08-26 02:25:55 +00005868 // Store to null is undefined.
5869 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005870 if (!SI->isVolatile())
Dehao Chenf6c00832016-05-18 19:44:21 +00005871 return SI->getPointerAddressSpace() == 0 &&
5872 SI->getPointerOperand() == I;
David Majnemer1fea77c2016-06-25 07:37:27 +00005873
5874 // A call to null is undefined.
5875 if (auto CS = CallSite(Use))
5876 return CS.getCalledValue() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005877 }
5878 return false;
5879}
5880
5881/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005882/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005883static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5884 for (BasicBlock::iterator i = BB->begin();
5885 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5886 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5887 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5888 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5889 IRBuilder<> Builder(T);
5890 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5891 BB->removePredecessor(PHI->getIncomingBlock(i));
5892 // Turn uncoditional branches into unreachables and remove the dead
5893 // destination from conditional branches.
5894 if (BI->isUnconditional())
5895 Builder.CreateUnreachable();
5896 else
Dehao Chenf6c00832016-05-18 19:44:21 +00005897 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5898 : BI->getSuccessor(0));
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005899 BI->eraseFromParent();
5900 return true;
5901 }
5902 // TODO: SwitchInst.
5903 }
5904
5905 return false;
5906}
5907
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005908bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005909 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005910
Chris Lattnerd7beca32010-12-14 06:17:25 +00005911 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005912 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005913
Dan Gohman4a63fad2010-08-14 00:29:42 +00005914 // Remove basic blocks that have no predecessors (except the entry block)...
5915 // or that just have themself as a predecessor. These are unreachable.
Dehao Chenf6c00832016-05-18 19:44:21 +00005916 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005917 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005918 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5919 DeleteDeadBlock(BB);
5920 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005921 }
5922
Chris Lattner031340a2003-08-17 19:41:53 +00005923 // Check to see if we can constant propagate this terminator instruction
5924 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005925 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005926
Dan Gohman1a951062009-10-30 22:39:04 +00005927 // Check for and eliminate duplicate PHI nodes in this block.
5928 Changed |= EliminateDuplicatePHINodes(BB);
5929
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005930 // Check for and remove branches that will always cause undefined behavior.
5931 Changed |= removeUndefIntroducingPredecessor(BB);
5932
Chris Lattner2e3832d2010-12-13 05:10:48 +00005933 // Merge basic blocks into their predecessor if there is only one distinct
5934 // pred, and if there is only one distinct successor of the predecessor, and
5935 // if there are no PHI nodes.
5936 //
5937 if (MergeBlockIntoPredecessor(BB))
5938 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005939
Devang Patel15ad6762011-05-18 18:01:27 +00005940 IRBuilder<> Builder(BB);
5941
Dan Gohman20af5a02008-03-11 21:53:06 +00005942 // If there is a trivial two-entry PHI node in this basic block, and we can
5943 // eliminate it, do so now.
5944 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5945 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005946 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005947
Devang Patela7ec47d2011-05-18 20:35:38 +00005948 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005949 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005950 if (BI->isUnconditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005951 if (SimplifyUncondBranch(BI, Builder))
5952 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005953 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005954 if (SimplifyCondBranch(BI, Builder))
5955 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005956 }
5957 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005958 if (SimplifyReturn(RI, Builder))
5959 return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005960 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005961 if (SimplifyResume(RI, Builder))
5962 return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005963 } else if (CleanupReturnInst *RI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005964 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5965 if (SimplifyCleanupReturn(RI))
5966 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005967 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005968 if (SimplifySwitch(SI, Builder))
5969 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005970 } else if (UnreachableInst *UI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005971 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5972 if (SimplifyUnreachable(UI))
5973 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005974 } else if (IndirectBrInst *IBI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005975 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5976 if (SimplifyIndirectBr(IBI))
5977 return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005978 }
5979
Chris Lattner031340a2003-08-17 19:41:53 +00005980 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005981}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005982
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005983/// This function is used to do simplification of a CFG.
5984/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005985/// eliminates unreachable basic blocks, and does other "peephole" optimization
5986/// of the CFG. It returns true if a modification was made.
5987///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005988bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005989 unsigned BonusInstThreshold, AssumptionCache *AC,
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +00005990 SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
5991 bool LateSimplifyCFG) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005992 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +00005993 BonusInstThreshold, AC, LoopHeaders, LateSimplifyCFG)
Dehao Chenf6c00832016-05-18 19:44:21 +00005994 .run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005995}