blob: c71cc764e6d861d60f5b4b6e7fd82139f21fd720 [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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
James Molloy4de84dd2015-11-04 15:28:04 +000019#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000022#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000025#include "llvm/ADT/StringRef.h"
Peter Collingbourne0609acc2017-02-15 03:01:11 +000026#include "llvm/Analysis/AssumptionCache.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000027#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000028#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000030#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000032#include "llvm/IR/Attributes.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000033#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000034#include "llvm/IR/CFG.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000035#include "llvm/IR/CallSite.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000036#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000037#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000041#include "llvm/IR/Function.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000042#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/GlobalVariable.h"
44#include "llvm/IR/IRBuilder.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000045#include "llvm/IR/InstrTypes.h"
46#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Instructions.h"
48#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000049#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/MDBuilder.h"
52#include "llvm/IR/Metadata.h"
53#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000054#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000056#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Type.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000058#include "llvm/IR/Use.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000059#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/Support/Casting.h"
Evan Chengd983eba2011-01-29 04:46:23 +000062#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000063#include "llvm/Support/Debug.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000064#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000065#include "llvm/Support/KnownBits.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000066#include "llvm/Support/MathExtras.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000067#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000068#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dehao Chenf6c00832016-05-18 19:44:21 +000069#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000070#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000071#include <algorithm>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000072#include <cassert>
73#include <climits>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
Chris Lattner5edb2f32004-10-18 04:07:22 +000077#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000078#include <set>
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000079#include <tuple>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000080#include <utility>
81#include <vector>
82
Chris Lattnerdf3c3422004-01-09 06:12:26 +000083using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000084using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000085
Chandler Carruth964daaa2014-04-22 02:55:47 +000086#define DEBUG_TYPE "simplifycfg"
87
James Molloy1b6207e2015-02-13 10:48:30 +000088// Chosen as 2 so as to be cheap, but still to have enough power to fold
89// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
90// To catch this, we need to fold a compare and a select, hence '2' being the
91// minimum reasonable default.
Dehao Chenf6c00832016-05-18 19:44:21 +000092static cl::opt<unsigned> PHINodeFoldingThreshold(
93 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
94 cl::desc(
95 "Control the amount of phi node folding to perform (default = 2)"));
96
97static cl::opt<bool> DupRet(
98 "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
99 cl::desc("Duplicate return instructions into unconditional branches"));
Peter Collingbourne616044a2011-04-29 18:47:38 +0000100
Evan Chengd983eba2011-01-29 04:46:23 +0000101static cl::opt<bool>
Dehao Chenf6c00832016-05-18 19:44:21 +0000102 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
103 cl::desc("Sink common instructions down to the end block"));
Manman Ren93ab6492012-09-20 22:37:36 +0000104
Alp Tokercb402912014-01-24 17:20:08 +0000105static cl::opt<bool> HoistCondStores(
106 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
107 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +0000108
James Molloy4de84dd2015-11-04 15:28:04 +0000109static cl::opt<bool> MergeCondStores(
110 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
111 cl::desc("Hoist conditional stores even if an unconditional store does not "
112 "precede - hoist multiple conditional stores into a single "
113 "predicated store"));
114
115static cl::opt<bool> MergeCondStoresAggressively(
116 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
117 cl::desc("When merging conditional stores, do so even if the resultant "
118 "basic blocks are unlikely to be if-converted as a result"));
119
David Majnemerfccf5c62016-01-27 02:59:41 +0000120static cl::opt<bool> SpeculateOneExpensiveInst(
121 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
122 cl::desc("Allow exactly one expensive instruction to be speculatively "
123 "executed"));
124
Sanjay Patel5264cc72016-01-27 19:22:45 +0000125static cl::opt<unsigned> MaxSpeculationDepth(
126 "max-speculation-depth", cl::Hidden, cl::init(10),
127 cl::desc("Limit maximum recursion depth when calculating costs of "
128 "speculatively executed instructions"));
129
Hans Wennborg39583b82012-09-26 09:44:49 +0000130STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Dehao Chenf6c00832016-05-18 19:44:21 +0000131STATISTIC(NumLinearMaps,
132 "Number of switch instructions turned into linear mapping");
133STATISTIC(NumLookupTables,
134 "Number of switch instructions turned into lookup tables");
135STATISTIC(
136 NumLookupTablesHoles,
137 "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000138STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Dehao Chenf6c00832016-05-18 19:44:21 +0000139STATISTIC(NumSinkCommons,
140 "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000141STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000142
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000143namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000144
Dehao Chenf6c00832016-05-18 19:44:21 +0000145// The first field contains the value that the switch produces when a certain
146// case group is selected, and the second field is a vector containing the
147// cases composing the case group.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000148using SwitchCaseResultVectorTy =
149 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
150
Dehao Chenf6c00832016-05-18 19:44:21 +0000151// The first field contains the phi node that generates a result of the switch
152// and the second field contains the value generated for a certain case in the
153// switch for that PHI.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000154using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000155
Dehao Chenf6c00832016-05-18 19:44:21 +0000156/// ValueEqualityComparisonCase - Represents a case of a switch.
157struct ValueEqualityComparisonCase {
158 ConstantInt *Value;
159 BasicBlock *Dest;
Eric Christopherb65acc62012-07-02 23:22:21 +0000160
Dehao Chenf6c00832016-05-18 19:44:21 +0000161 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
Eric Christopherb65acc62012-07-02 23:22:21 +0000162 : Value(Value), Dest(Dest) {}
163
Dehao Chenf6c00832016-05-18 19:44:21 +0000164 bool operator<(ValueEqualityComparisonCase RHS) const {
165 // Comparing pointers is ok as we only rely on the order for uniquing.
166 return Value < RHS.Value;
167 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000168
Dehao Chenf6c00832016-05-18 19:44:21 +0000169 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
170};
Eric Christopherb65acc62012-07-02 23:22:21 +0000171
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000172class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000173 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000174 const DataLayout &DL;
Hyojin Sung4673f102016-03-29 04:08:57 +0000175 SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
Sanjay Patel0f9b4772017-09-27 14:54:16 +0000176 const SimplifyCFGOptions &Options;
177
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000178 Value *isValueEqualityComparison(TerminatorInst *TI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000179 BasicBlock *GetValueEqualityComparisonCases(
180 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000181 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000182 BasicBlock *Pred,
183 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000184 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
185 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000186
Devang Pateldd14e0f2011-05-18 21:33:11 +0000187 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000188 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000189 bool SimplifySingleResume(ResumeInst *RI);
190 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000191 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000192 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000193 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000194 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000195 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
196 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000197
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000198public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000199 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +0000200 SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
Sanjay Patel0f9b4772017-09-27 14:54:16 +0000201 const SimplifyCFGOptions &Opts)
Sanjay Patel4c33d522017-10-04 20:26:25 +0000202 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
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;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000442
443 /// Value found for the switch comparison
444 Value *CompValue = nullptr;
445
446 /// Extra clause to be checked before the switch
447 Value *Extra = nullptr;
448
449 /// Set of integers to match in switch
450 SmallVector<ConstantInt *, 8> Vals;
451
452 /// Number of comparisons matched in the and/or chain
453 unsigned UsedICmps = 0;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000454
Mehdi Aminiffd01002014-11-20 22:40:25 +0000455 /// Construct and compute the result for the comparison instruction Cond
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000456 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000458 }
459
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000460 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000461 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000462 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000463
Mehdi Aminiffd01002014-11-20 22:40:25 +0000464private:
Mehdi Aminiffd01002014-11-20 22:40:25 +0000465 /// Try to set the current value used for the comparison, it succeeds only if
466 /// it wasn't set before or if the new value is the same as the old one
467 bool setValueOnce(Value *NewVal) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000468 if (CompValue && CompValue != NewVal)
469 return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000470 CompValue = NewVal;
471 return (CompValue != nullptr);
472 }
473
474 /// Try to match Instruction "I" as a comparison against a constant and
475 /// populates the array Vals with the set of values that match (or do not
476 /// match depending on isEQ).
477 /// Return false on failure. On success, the Value the comparison matched
478 /// against is placed in CompValue.
479 /// If CompValue is already set, the function is expected to fail if a match
480 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000481 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000482 // If this is an icmp against a constant, handle this as one of the cases.
483 ICmpInst *ICI;
484 ConstantInt *C;
485 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
Dehao Chenf6c00832016-05-18 19:44:21 +0000486 (C = GetConstantInt(I->getOperand(1), DL)))) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000487 return false;
488 }
489
490 Value *RHSVal;
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000491 const APInt *RHSC;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000492
493 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000494 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000495 // This undoes a transformation done by instcombine to fuse 2 compares.
Dehao Chenf6c00832016-05-18 19:44:21 +0000496 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000497 // It's a little bit hard to see why the following transformations are
498 // correct. Here is a CVC3 program to verify them for 64-bit values:
499
500 /*
501 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
502 x : BITVECTOR(64);
503 y : BITVECTOR(64);
504 z : BITVECTOR(64);
505 mask : BITVECTOR(64) = BVSHL(ONE, z);
506 QUERY( (y & ~mask = y) =>
507 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
508 );
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000509 QUERY( (y | mask = y) =>
510 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
511 );
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000512 */
513
514 // Please note that each pattern must be a dual implication (<--> or
515 // iff). One directional implication can create spurious matches. If the
516 // implication is only one-way, an unsatisfiable condition on the left
517 // side can imply a satisfiable condition on the right side. Dual
518 // implication ensures that satisfiable conditions are transformed to
519 // other satisfiable conditions and unsatisfiable conditions are
520 // transformed to other unsatisfiable conditions.
521
522 // Here is a concrete example of a unsatisfiable condition on the left
523 // implying a satisfiable condition on the right:
524 //
525 // mask = (1 << z)
526 // (x & ~mask) == y --> (x == y || x == (y | mask))
527 //
528 // Substituting y = 3, z = 0 yields:
529 // (x & -2) == 3 --> (x == 3 || x == 2)
530
531 // Pattern match a special case:
532 /*
533 QUERY( (y & ~mask = y) =>
534 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
535 );
536 */
Mehdi Aminiffd01002014-11-20 22:40:25 +0000537 if (match(ICI->getOperand(0),
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000538 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
539 APInt Mask = ~*RHSC;
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000540 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000541 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000542 if (!setValueOnce(RHSVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000543 return false;
544
545 Vals.push_back(C);
Dehao Chenf6c00832016-05-18 19:44:21 +0000546 Vals.push_back(
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000547 ConstantInt::get(C->getContext(),
548 C->getValue() | Mask));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000549 UsedICmps++;
550 return true;
551 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000552 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000553
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000554 // Pattern match a special case:
555 /*
556 QUERY( (y | mask = y) =>
557 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
558 );
559 */
560 if (match(ICI->getOperand(0),
561 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
562 APInt Mask = *RHSC;
563 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
564 // If we already have a value for the switch, it has to match!
565 if (!setValueOnce(RHSVal))
566 return false;
567
568 Vals.push_back(C);
569 Vals.push_back(ConstantInt::get(C->getContext(),
570 C->getValue() & ~Mask));
571 UsedICmps++;
572 return true;
573 }
574 }
575
Mehdi Aminiffd01002014-11-20 22:40:25 +0000576 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000577 if (!setValueOnce(ICI->getOperand(0)))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000578 return false;
579
580 UsedICmps++;
581 Vals.push_back(C);
582 return ICI->getOperand(0);
583 }
584
585 // 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 +0000586 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
587 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000588
589 // Shift the range if the compare is fed by an add. This is the range
590 // compare idiom as emitted by instcombine.
591 Value *CandidateVal = I->getOperand(0);
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000592 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
593 Span = Span.subtract(*RHSC);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000594 CandidateVal = RHSVal;
595 }
596
597 // If this is an and/!= check, then we are looking to build the set of
598 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
599 // x != 0 && x != 1.
600 if (!isEQ)
601 Span = Span.inverse();
602
603 // If there are a ton of values, we don't want to make a ginormous switch.
Craig Topper7e3e7af2017-05-07 22:22:11 +0000604 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000605 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000606 }
607
608 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000609 if (!setValueOnce(CandidateVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000610 return false;
611
612 // Add all values from the range to the set
613 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
614 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000615
616 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000617 return true;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000618 }
619
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000620 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000621 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
622 /// the value being compared, and stick the list constants into the Vals
623 /// vector.
624 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000626 Instruction *I = dyn_cast<Instruction>(V);
627 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000628
Mehdi Aminiffd01002014-11-20 22:40:25 +0000629 // Keep a stack (SmallVector for efficiency) for depth-first traversal
630 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000631 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000632
Mehdi Aminiffd01002014-11-20 22:40:25 +0000633 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000634 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000635 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000636
Dehao Chenf6c00832016-05-18 19:44:21 +0000637 while (!DFT.empty()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000638 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000639
Mehdi Aminiffd01002014-11-20 22:40:25 +0000640 if (Instruction *I = dyn_cast<Instruction>(V)) {
641 // If it is a || (or && depending on isEQ), process the operands.
642 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000643 if (Visited.insert(I->getOperand(1)).second)
644 DFT.push_back(I->getOperand(1));
645 if (Visited.insert(I->getOperand(0)).second)
646 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000647 continue;
648 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000649
Mehdi Aminiffd01002014-11-20 22:40:25 +0000650 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000651 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000652 // Match succeed, continue the loop
653 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000654 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000655
Mehdi Aminiffd01002014-11-20 22:40:25 +0000656 // One element of the sequence of || (or &&) could not be match as a
657 // comparison against the same value as the others.
658 // We allow only one "Extra" case to be checked before the switch
659 if (!Extra) {
660 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000661 continue;
662 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000663 // Failed to parse a proper sequence, abort now
664 CompValue = nullptr;
665 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000666 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000667 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000668};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000669
670} // end anonymous namespace
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000671
Eli Friedmancb61afb2008-12-16 20:54:32 +0000672static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000673 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000674 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
675 Cond = dyn_cast<Instruction>(SI->getCondition());
676 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
677 if (BI->isConditional())
678 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000679 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
680 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000681 }
682
683 TI->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000684 if (Cond)
685 RecursivelyDeleteTriviallyDeadInstructions(Cond);
Eli Friedmancb61afb2008-12-16 20:54:32 +0000686}
687
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000688/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000689/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000690Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000691 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000692 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
693 // Do not permit merging of large switch instructions into their
694 // predecessors unless there is only one predecessor.
Dehao Chenf6c00832016-05-18 19:44:21 +0000695 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
696 pred_end(SI->getParent())) <=
697 128)
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000698 CV = SI->getCondition();
699 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000700 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000702 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000703 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000705
706 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000707 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000708 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
709 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000710 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000711 CV = Ptr;
712 }
713 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000714 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000715}
716
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000717/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000718/// decode all of the 'cases' that it represents and return the 'default' block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000719BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
720 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000721 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000722 Cases.reserve(SI->getNumCases());
Chandler Carruth927d8e62017-04-12 07:27:28 +0000723 for (auto Case : SI->cases())
724 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
725 Case.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000726 return SI->getDefaultDest();
727 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000728
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000729 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000730 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000731 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
Dehao Chenf6c00832016-05-18 19:44:21 +0000732 Cases.push_back(ValueEqualityComparisonCase(
733 GetConstantInt(ICI->getOperand(1), DL), Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000734 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000735}
736
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000737/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000738/// in the list that match the specified block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000739static void
740EliminateBlockCases(BasicBlock *BB,
741 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000742 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000743}
744
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000745/// Return true if there are any keys in C1 that exist in C2 as well.
Dehao Chenf6c00832016-05-18 19:44:21 +0000746static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
747 std::vector<ValueEqualityComparisonCase> &C2) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000748 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
749
750 // Make V1 be smaller than V2.
751 if (V1->size() > V2->size())
752 std::swap(V1, V2);
753
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000754 if (V1->empty())
Dehao Chenf6c00832016-05-18 19:44:21 +0000755 return false;
Eric Christopherb65acc62012-07-02 23:22:21 +0000756 if (V1->size() == 1) {
757 // Just scan V2.
758 ConstantInt *TheVal = (*V1)[0].Value;
759 for (unsigned i = 0, e = V2->size(); i != e; ++i)
760 if (TheVal == (*V2)[i].Value)
761 return true;
762 }
763
764 // Otherwise, just sort both lists and compare element by element.
765 array_pod_sort(V1->begin(), V1->end());
766 array_pod_sort(V2->begin(), V2->end());
767 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
768 while (i1 != e1 && i2 != e2) {
769 if ((*V1)[i1].Value == (*V2)[i2].Value)
770 return true;
771 if ((*V1)[i1].Value < (*V2)[i2].Value)
772 ++i1;
773 else
774 ++i2;
775 }
776 return false;
777}
778
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000779/// If TI is known to be a terminator instruction and its block is known to
780/// only have a single predecessor block, check to see if that predecessor is
781/// also a value comparison with the same value, and if that comparison
782/// determines the outcome of this comparison. If so, simplify TI. This does a
783/// very limited form of jump threading.
Dehao Chenf6c00832016-05-18 19:44:21 +0000784bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
785 TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000786 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +0000787 if (!PredVal)
788 return false; // Not a value comparison in predecessor.
Chris Lattner1cca9592005-02-24 06:17:52 +0000789
790 Value *ThisVal = isValueEqualityComparison(TI);
791 assert(ThisVal && "This isn't a value comparison!!");
Dehao Chenf6c00832016-05-18 19:44:21 +0000792 if (ThisVal != PredVal)
793 return false; // Different predicates.
Chris Lattner1cca9592005-02-24 06:17:52 +0000794
Andrew Trick3051aa12012-08-29 21:46:38 +0000795 // TODO: Preserve branch weight metadata, similarly to how
796 // FoldValueComparisonIntoPredecessors preserves it.
797
Chris Lattner1cca9592005-02-24 06:17:52 +0000798 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000799 std::vector<ValueEqualityComparisonCase> PredCases;
Dehao Chenf6c00832016-05-18 19:44:21 +0000800 BasicBlock *PredDef =
801 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
802 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000803
Chris Lattner1cca9592005-02-24 06:17:52 +0000804 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000805 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000806 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Dehao Chenf6c00832016-05-18 19:44:21 +0000807 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000808
809 // If TI's block is the default block from Pred's comparison, potentially
810 // simplify TI based on this knowledge.
811 if (PredDef == TI->getParent()) {
812 // If we are here, we know that the value is none of those cases listed in
813 // PredCases. If there are any cases in ThisCases that are in PredCases, we
814 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000815 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000816 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000817
Chris Lattner4088e2b2010-12-13 01:47:07 +0000818 if (isa<BranchInst>(TI)) {
819 // Okay, one of the successors of this condbr is dead. Convert it to a
820 // uncond br.
821 assert(ThisCases.size() == 1 && "Branch can only have one case!");
822 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000823 Instruction *NI = Builder.CreateBr(ThisDef);
Dehao Chenf6c00832016-05-18 19:44:21 +0000824 (void)NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000825
Chris Lattner4088e2b2010-12-13 01:47:07 +0000826 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000827 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000828
Chris Lattner4088e2b2010-12-13 01:47:07 +0000829 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000830 << "Through successor TI: " << *TI << "Leaving: " << *NI
831 << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000832
Chris Lattner4088e2b2010-12-13 01:47:07 +0000833 EraseTerminatorInstAndDCECond(TI);
834 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000835 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000836
Chris Lattner4088e2b2010-12-13 01:47:07 +0000837 SwitchInst *SI = cast<SwitchInst>(TI);
838 // Okay, TI has cases that are statically dead, prune them away.
Dehao Chenf6c00832016-05-18 19:44:21 +0000839 SmallPtrSet<Constant *, 16> DeadCases;
Eric Christopherb65acc62012-07-02 23:22:21 +0000840 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
841 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000842
David Greene725c7c32010-01-05 01:26:52 +0000843 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000844 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000845
Manman Ren8691e522012-09-14 21:53:06 +0000846 // Collect branch weights into a vector.
847 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000848 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000849 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
850 if (HasWeight)
851 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
852 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000853 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000854 Weights.push_back(CI->getValue().getZExtValue());
855 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000856 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
857 --i;
Chandler Carruth927d8e62017-04-12 07:27:28 +0000858 if (DeadCases.count(i->getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000859 if (HasWeight) {
Chandler Carruth927d8e62017-04-12 07:27:28 +0000860 std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
Manman Ren8691e522012-09-14 21:53:06 +0000861 Weights.pop_back();
862 }
Chandler Carruth927d8e62017-04-12 07:27:28 +0000863 i->getCaseSuccessor()->removePredecessor(TI->getParent());
Eric Christopherb65acc62012-07-02 23:22:21 +0000864 SI->removeCase(i);
865 }
866 }
Manman Ren97c18762012-10-11 22:28:34 +0000867 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000868 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +0000869 MDBuilder(SI->getParent()->getContext())
870 .createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000871
872 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000873 return true;
874 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000875
Chris Lattner4088e2b2010-12-13 01:47:07 +0000876 // Otherwise, TI's block must correspond to some matched value. Find out
877 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000878 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000879 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000880 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
881 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000882 if (TIV)
Dehao Chenf6c00832016-05-18 19:44:21 +0000883 return false; // Cannot handle multiple values coming to this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000884 TIV = PredCases[i].Value;
885 }
886 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000887
888 // Okay, we found the one constant that our value can be if we get into TI's
889 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000890 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000891 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
892 if (ThisCases[i].Value == TIV) {
893 TheRealDest = ThisCases[i].Dest;
894 break;
895 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000896
897 // If not handled by any explicit cases, it is handled by the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +0000898 if (!TheRealDest)
899 TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000900
901 // Remove PHI node entries for dead edges.
902 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000903 for (BasicBlock *Succ : successors(TIBB))
904 if (Succ != CheckEdge)
905 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000906 else
Craig Topperf40110f2014-04-25 05:29:35 +0000907 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000908
909 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000910 Instruction *NI = Builder.CreateBr(TheRealDest);
Dehao Chenf6c00832016-05-18 19:44:21 +0000911 (void)NI;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000912
913 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000914 << "Through successor TI: " << *TI << "Leaving: " << *NI
915 << "\n");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000916
917 EraseTerminatorInstAndDCECond(TI);
918 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000919}
920
Dale Johannesen7f99d222009-03-12 21:01:11 +0000921namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000922
Dehao Chenf6c00832016-05-18 19:44:21 +0000923/// This class implements a stable ordering of constant
924/// integers that does not depend on their address. This is important for
925/// applications that sort ConstantInt's to ensure uniqueness.
926struct ConstantIntOrdering {
927 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
928 return LHS->getValue().ult(RHS->getValue());
929 }
930};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000931
932} // end anonymous namespace
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000933
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000934static int ConstantIntSortPredicate(ConstantInt *const *P1,
935 ConstantInt *const *P2) {
936 const ConstantInt *LHS = *P1;
937 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000938 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000939 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000940 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000941}
942
Dehao Chenf6c00832016-05-18 19:44:21 +0000943static inline bool HasBranchWeights(const Instruction *I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000944 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000945 if (ProfMD && ProfMD->getOperand(0))
Dehao Chenf6c00832016-05-18 19:44:21 +0000946 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
Andrew Trick3051aa12012-08-29 21:46:38 +0000947 return MDS->getString().equals("branch_weights");
948
949 return false;
950}
951
Manman Ren571d9e42012-09-11 17:43:35 +0000952/// Get Weights of a given TerminatorInst, the default weight is at the front
953/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
954/// metadata.
955static void GetBranchWeights(TerminatorInst *TI,
956 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000957 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000958 assert(MD);
959 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000960 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000961 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000962 }
963
Manman Ren571d9e42012-09-11 17:43:35 +0000964 // If TI is a conditional eq, the default case is the false case,
965 // and the corresponding branch-weight data is at index 2. We swap the
966 // default weight to be the first entry.
Dehao Chenf6c00832016-05-18 19:44:21 +0000967 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Manman Ren571d9e42012-09-11 17:43:35 +0000968 assert(Weights.size() == 2);
969 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
970 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
971 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000972 }
973}
974
Sanjay Patel84a0bf62016-05-06 17:51:37 +0000975/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000976static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000977 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
978 if (Max > UINT_MAX) {
979 unsigned Offset = 32 - countLeadingZeros(Max);
980 for (uint64_t &I : Weights)
981 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000982 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000983}
984
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000985/// The specified terminator is a value equality comparison instruction
986/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000987/// See if any of the predecessors of the terminator block are value comparisons
988/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000989bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
990 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000991 BasicBlock *BB = TI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000992 Value *CV = isValueEqualityComparison(TI); // CondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000993 assert(CV && "Not a comparison?");
994 bool Changed = false;
995
Dehao Chenf6c00832016-05-18 19:44:21 +0000996 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000997 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000998 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000999
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001000 // See if the predecessor is a comparison with the same value.
1001 TerminatorInst *PTI = Pred->getTerminator();
Dehao Chenf6c00832016-05-18 19:44:21 +00001002 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001003
James Molloye6566422016-09-01 07:45:25 +00001004 if (PCV == CV && TI != PTI) {
James Molloy21744682016-09-01 09:01:34 +00001005 SmallSetVector<BasicBlock*, 4> FailBlocks;
James Molloye6566422016-09-01 07:45:25 +00001006 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1007 for (auto *Succ : FailBlocks) {
Benjamin Kramer46f5e2c2017-03-24 14:15:35 +00001008 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
James Molloye6566422016-09-01 07:45:25 +00001009 return false;
1010 }
1011 }
1012
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001013 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +00001014 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001015 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1016
Eric Christopherb65acc62012-07-02 23:22:21 +00001017 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001018 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1019
1020 // Based on whether the default edge from PTI goes to BB or not, fill in
1021 // PredCases and PredDefault with the new switch cases we would like to
1022 // build.
Dehao Chenf6c00832016-05-18 19:44:21 +00001023 SmallVector<BasicBlock *, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001024
Andrew Trick3051aa12012-08-29 21:46:38 +00001025 // Update the branch weight metadata along the way
1026 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +00001027 bool PredHasWeights = HasBranchWeights(PTI);
1028 bool SuccHasWeights = HasBranchWeights(TI);
1029
Manman Ren5e5049d2012-09-14 19:05:19 +00001030 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001031 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001032 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001033 if (Weights.size() != 1 + PredCases.size())
1034 PredHasWeights = SuccHasWeights = false;
1035 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +00001036 // If there are no predecessor weights but there are successor weights,
1037 // populate Weights with 1, which will later be scaled to the sum of
1038 // successor's weights
1039 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001040
Manman Ren571d9e42012-09-11 17:43:35 +00001041 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +00001042 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001043 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001044 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001045 if (SuccWeights.size() != 1 + BBCases.size())
1046 PredHasWeights = SuccHasWeights = false;
1047 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +00001048 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001049
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001050 if (PredDefault == BB) {
1051 // If this is the default destination from PTI, only the edges in TI
1052 // that don't occur in PTI, or that branch to BB will be activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001053 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001054 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1055 if (PredCases[i].Dest != BB)
1056 PTIHandled.insert(PredCases[i].Value);
1057 else {
1058 // The default destination is BB, we don't need explicit targets.
1059 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001060
Manman Ren571d9e42012-09-11 17:43:35 +00001061 if (PredHasWeights || SuccHasWeights) {
1062 // Increase weight for the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +00001063 Weights[0] += Weights[i + 1];
1064 std::swap(Weights[i + 1], Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001065 Weights.pop_back();
1066 }
1067
Eric Christopherb65acc62012-07-02 23:22:21 +00001068 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001069 --i;
1070 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001071 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001072
Eric Christopherb65acc62012-07-02 23:22:21 +00001073 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001074 if (PredDefault != BBDefault) {
1075 PredDefault->removePredecessor(Pred);
1076 PredDefault = BBDefault;
1077 NewSuccessors.push_back(BBDefault);
1078 }
Andrew Trick3051aa12012-08-29 21:46:38 +00001079
Manman Ren571d9e42012-09-11 17:43:35 +00001080 unsigned CasesFromPred = Weights.size();
1081 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +00001082 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1083 if (!PTIHandled.count(BBCases[i].Value) &&
1084 BBCases[i].Dest != BBDefault) {
1085 PredCases.push_back(BBCases[i]);
1086 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +00001087 if (SuccHasWeights || PredHasWeights) {
1088 // The default weight is at index 0, so weight for the ith case
1089 // should be at index i+1. Scale the cases from successor by
1090 // PredDefaultWeight (Weights[0]).
Dehao Chenf6c00832016-05-18 19:44:21 +00001091 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1092 ValidTotalSuccWeight += SuccWeights[i + 1];
Andrew Trick3051aa12012-08-29 21:46:38 +00001093 }
Eric Christopherb65acc62012-07-02 23:22:21 +00001094 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001095
Manman Ren571d9e42012-09-11 17:43:35 +00001096 if (SuccHasWeights || PredHasWeights) {
1097 ValidTotalSuccWeight += SuccWeights[0];
1098 // Scale the cases from predecessor by ValidTotalSuccWeight.
1099 for (unsigned i = 1; i < CasesFromPred; ++i)
1100 Weights[i] *= ValidTotalSuccWeight;
1101 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1102 Weights[0] *= SuccWeights[0];
1103 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001104 } else {
1105 // If this is not the default destination from PSI, only the edges
1106 // in SI that occur in PSI with a destination of BB will be
1107 // activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001108 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1109 std::map<ConstantInt *, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001110 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1111 if (PredCases[i].Dest == BB) {
1112 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +00001113
1114 if (PredHasWeights || SuccHasWeights) {
Dehao Chenf6c00832016-05-18 19:44:21 +00001115 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1116 std::swap(Weights[i + 1], Weights.back());
Manman Rend81b8e82012-09-14 17:29:56 +00001117 Weights.pop_back();
1118 }
1119
Eric Christopherb65acc62012-07-02 23:22:21 +00001120 std::swap(PredCases[i], PredCases.back());
1121 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001122 --i;
1123 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001124 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001125
1126 // Okay, now we know which constants were sent to BB from the
1127 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +00001128 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1129 if (PTIHandled.count(BBCases[i].Value)) {
1130 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +00001131 if (PredHasWeights || SuccHasWeights)
1132 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001133 PredCases.push_back(BBCases[i]);
1134 NewSuccessors.push_back(BBCases[i].Dest);
Dehao Chenf6c00832016-05-18 19:44:21 +00001135 PTIHandled.erase(
1136 BBCases[i].Value); // This constant is taken care of
Eric Christopherb65acc62012-07-02 23:22:21 +00001137 }
1138
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001139 // If there are any constants vectored to BB that TI doesn't handle,
1140 // they must go to the default destination of TI.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001141 for (ConstantInt *I : PTIHandled) {
Andrew Trick90f50292012-11-15 18:40:29 +00001142 if (PredHasWeights || SuccHasWeights)
Benjamin Kramer135f7352016-06-26 12:28:59 +00001143 Weights.push_back(WeightsForHandled[I]);
1144 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001145 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001146 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001147 }
1148
1149 // Okay, at this point, we know which new successor Pred will get. Make
1150 // sure we update the number of entries in the PHI nodes for these
1151 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001152 for (BasicBlock *NewSuccessor : NewSuccessors)
1153 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001154
Devang Patel58380552011-05-18 20:53:17 +00001155 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001156 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001157 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001158 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001159 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001160 }
1161
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001162 // Now that the successors are updated, create the new Switch instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001163 SwitchInst *NewSI =
1164 Builder.CreateSwitch(CV, PredDefault, PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001165 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001166 for (ValueEqualityComparisonCase &V : PredCases)
1167 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001168
Andrew Trick3051aa12012-08-29 21:46:38 +00001169 if (PredHasWeights || SuccHasWeights) {
1170 // Halve the weights if any of them cannot fit in an uint32_t
1171 FitWeights(Weights);
1172
1173 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1174
Dehao Chenf6c00832016-05-18 19:44:21 +00001175 NewSI->setMetadata(
1176 LLVMContext::MD_prof,
1177 MDBuilder(BB->getContext()).createBranchWeights(MDWeights));
Andrew Trick3051aa12012-08-29 21:46:38 +00001178 }
1179
Eli Friedmancb61afb2008-12-16 20:54:32 +00001180 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001181
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001182 // Okay, last check. If BB is still a successor of PSI, then we must
1183 // have an infinite loop case. If so, add an infinitely looping block
1184 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001185 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001186 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1187 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001188 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001189 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001190 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00001191 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
1192 BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001193 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001194 }
1195 NewSI->setSuccessor(i, InfLoopBlock);
1196 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001197
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001198 Changed = true;
1199 }
1200 }
1201 return Changed;
1202}
1203
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001204// If we would need to insert a select that uses the value of this invoke
1205// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1206// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001207static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1208 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001209 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001210 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001211 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001212 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1213 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1214 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001215 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001216 return false;
1217 }
1218 }
1219 }
1220 return true;
1221}
1222
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001223static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1224
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001225/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1226/// in the two blocks up into the branch block. The caller of this function
1227/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001228static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001229 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001230 // This does very trivial matching, with limited scanning, to find identical
1231 // instructions in the two blocks. In particular, we don't want to get into
1232 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1233 // such, we currently just scan for obviously identical instructions in an
1234 // identical order.
Dehao Chenf6c00832016-05-18 19:44:21 +00001235 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1236 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
Chris Lattner389cfac2004-11-30 00:29:14 +00001237
Devang Patelf10e2872009-02-04 00:03:08 +00001238 BasicBlock::iterator BB1_Itr = BB1->begin();
1239 BasicBlock::iterator BB2_Itr = BB2->begin();
1240
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001241 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001242 // Skip debug info if it is not identical.
1243 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1244 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1245 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1246 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001247 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001248 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001249 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001250 }
Devang Patele48ddf82011-04-07 00:30:15 +00001251 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001252 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001253 return false;
1254
Chris Lattner389cfac2004-11-30 00:29:14 +00001255 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001256
David Majnemerc82f27a2013-06-03 20:43:12 +00001257 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001258 do {
1259 // If we are hoisting the terminator instruction, don't move one (making a
1260 // broken BB), instead clone it, and remove BI.
1261 if (isa<TerminatorInst>(I1))
1262 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001263
Chad Rosier54390052015-02-23 19:15:16 +00001264 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1265 return Changed;
1266
Chris Lattner389cfac2004-11-30 00:29:14 +00001267 // For a normal instruction, we just move one to right before the branch,
1268 // then replace all uses of the other with the first. Finally, we remove
1269 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001270 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001271 if (!I2->use_empty())
1272 I2->replaceAllUsesWith(I1);
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +00001273 I1->andIRFlags(I2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001274 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1275 LLVMContext::MD_range,
1276 LLVMContext::MD_fpmath,
1277 LLVMContext::MD_invariant_load,
1278 LLVMContext::MD_nonnull,
1279 LLVMContext::MD_invariant_group,
1280 LLVMContext::MD_align,
1281 LLVMContext::MD_dereferenceable,
1282 LLVMContext::MD_dereferenceable_or_null,
1283 LLVMContext::MD_mem_parallel_loop_access};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001284 combineMetadata(I1, I2, KnownIDs);
Dehao Chen87823f82016-09-08 21:53:33 +00001285
Robert Lougherb0124c12017-01-12 21:11:09 +00001286 // I1 and I2 are being combined into a single instruction. Its debug
1287 // location is the merged locations of the original instructions.
Dehao Chenf4646272017-10-02 18:13:14 +00001288 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
Taewook Oh505a25a2017-01-28 07:05:43 +00001289
Chris Lattnerd7beca32010-12-14 06:17:25 +00001290 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001291 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001292
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001293 I1 = &*BB1_Itr++;
1294 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001295 // Skip debug info if it is not identical.
1296 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1297 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1298 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1299 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001300 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001301 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001302 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001303 }
Devang Patele48ddf82011-04-07 00:30:15 +00001304 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001305
1306 return true;
1307
1308HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001309 // It may not be possible to hoist an invoke.
1310 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001311 return Changed;
1312
Sanjay Patel5781d842016-03-12 16:52:17 +00001313 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001314 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001315 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001316 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1317 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1318 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1319 if (BB1V == BB2V)
1320 continue;
1321
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001322 // Check for passingValueIsAlwaysUndefined here because we would rather
1323 // eliminate undefined control flow then converting it to a select.
1324 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1325 passingValueIsAlwaysUndefined(BB2V, PN))
Dehao Chenf6c00832016-05-18 19:44:21 +00001326 return Changed;
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001327
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001328 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001329 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001330 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001331 return Changed;
1332 }
1333 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001334
Chris Lattner389cfac2004-11-30 00:29:14 +00001335 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001336 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001337 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001338 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001339 I1->replaceAllUsesWith(NT);
1340 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001341 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001342 }
1343
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001344 IRBuilder<NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001345 // Hoisting one of the terminators from our successor is a great thing.
1346 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1347 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1348 // nodes, so we insert select instruction to compute the final result.
Dehao Chenf6c00832016-05-18 19:44:21 +00001349 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001350 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001351 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001352 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001353 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001354 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1355 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001356 if (BB1V == BB2V)
1357 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001358
Chris Lattner4088e2b2010-12-13 01:47:07 +00001359 // These values do not agree. Insert a select instruction before NT
1360 // that determines the right value.
1361 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001362 if (!SI)
Dehao Chenf6c00832016-05-18 19:44:21 +00001363 SI = cast<SelectInst>(
1364 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1365 BB1V->getName() + "." + BB2V->getName(), BI));
Devang Patel1407fb42011-05-19 20:52:46 +00001366
Chris Lattner4088e2b2010-12-13 01:47:07 +00001367 // Make the PHI node use the select for all incoming values for BB1/BB2
1368 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1369 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1370 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001371 }
1372 }
1373
1374 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001375 for (BasicBlock *Succ : successors(BB1))
1376 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001377
Eli Friedmancb61afb2008-12-16 20:54:32 +00001378 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001379 return true;
1380}
1381
James Molloyeec6df32016-09-01 10:44:35 +00001382// All instructions in Insts belong to different blocks that all unconditionally
1383// branch to a common successor. Analyze each instruction and return true if it
1384// would be possible to sink them into their successor, creating one common
1385// instruction instead. For every value that would be required to be provided by
1386// PHI node (because an operand varies in each input block), add to PHIOperands.
1387static bool canSinkInstructions(
1388 ArrayRef<Instruction *> Insts,
1389 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
James Molloy5bf21142016-08-22 19:07:15 +00001390 // Prune out obviously bad instructions to move. Any non-store instruction
1391 // must have exactly one use, and we check later that use is by a single,
1392 // common PHI instruction in the successor.
1393 for (auto *I : Insts) {
1394 // These instructions may change or break semantics if moved.
1395 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1396 I->getType()->isTokenTy())
1397 return false;
Akira Hatanaka4ec7b202017-01-25 06:21:51 +00001398
1399 // Conservatively return false if I is an inline-asm instruction. Sinking
1400 // and merging inline-asm instructions can potentially create arguments
1401 // that cannot satisfy the inline-asm constraints.
1402 if (const auto *C = dyn_cast<CallInst>(I))
1403 if (C->isInlineAsm())
1404 return false;
1405
James Molloy5bf21142016-08-22 19:07:15 +00001406 // Everything must have only one use too, apart from stores which
1407 // have no uses.
1408 if (!isa<StoreInst>(I) && !I->hasOneUse())
1409 return false;
1410 }
1411
1412 const Instruction *I0 = Insts.front();
1413 for (auto *I : Insts)
1414 if (!I->isSameOperationAs(I0))
1415 return false;
1416
James Molloyeec6df32016-09-01 10:44:35 +00001417 // All instructions in Insts are known to be the same opcode. If they aren't
1418 // stores, check the only user of each is a PHI or in the same block as the
1419 // instruction, because if a user is in the same block as an instruction
1420 // we're contemplating sinking, it must already be determined to be sinkable.
James Molloy5bf21142016-08-22 19:07:15 +00001421 if (!isa<StoreInst>(I0)) {
1422 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
James Molloy6c009c12016-09-07 09:01:22 +00001423 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
Eric Liu8c7d28b2017-03-15 15:29:42 +00001424 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
James Molloyeec6df32016-09-01 10:44:35 +00001425 auto *U = cast<Instruction>(*I->user_begin());
Eric Liu8c7d28b2017-03-15 15:29:42 +00001426 return (PNUse &&
1427 PNUse->getParent() == Succ &&
1428 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1429 U->getParent() == I->getParent();
James Molloy5bf21142016-08-22 19:07:15 +00001430 }))
1431 return false;
1432 }
1433
Aditya Kumar24f6ad512017-03-16 14:09:18 +00001434 // Because SROA can't handle speculating stores of selects, try not
1435 // to sink loads or stores of allocas when we'd have to create a PHI for
1436 // the address operand. Also, because it is likely that loads or stores
1437 // of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
1438 // This can cause code churn which can have unintended consequences down
1439 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1440 // FIXME: This is a workaround for a deficiency in SROA - see
1441 // https://llvm.org/bugs/show_bug.cgi?id=30188
1442 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1443 return isa<AllocaInst>(I->getOperand(1));
1444 }))
1445 return false;
1446 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1447 return isa<AllocaInst>(I->getOperand(0));
1448 }))
1449 return false;
1450
James Molloy5bf21142016-08-22 19:07:15 +00001451 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1452 if (I0->getOperand(OI)->getType()->isTokenTy())
1453 // Don't touch any operand of token type.
1454 return false;
James Molloy104370a2016-09-11 09:00:03 +00001455
James Molloy5bf21142016-08-22 19:07:15 +00001456 auto SameAsI0 = [&I0, OI](const Instruction *I) {
James Molloyeec6df32016-09-01 10:44:35 +00001457 assert(I->getNumOperands() == I0->getNumOperands());
1458 return I->getOperand(OI) == I0->getOperand(OI);
James Molloy5bf21142016-08-22 19:07:15 +00001459 };
1460 if (!all_of(Insts, SameAsI0)) {
1461 if (!canReplaceOperandWithVariable(I0, OI))
1462 // We can't create a PHI from this GEP.
1463 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001464 // Don't create indirect calls! The called value is the final operand.
1465 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
James Molloy5bf21142016-08-22 19:07:15 +00001466 // FIXME: if the call was *already* indirect, we should do this.
1467 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001468 }
James Molloyeec6df32016-09-01 10:44:35 +00001469 for (auto *I : Insts)
1470 PHIOperands[I].push_back(I->getOperand(OI));
James Molloy5bf21142016-08-22 19:07:15 +00001471 }
1472 }
1473 return true;
1474}
1475
1476// Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1477// instruction of every block in Blocks to their common successor, commoning
1478// into one instruction.
James Molloyeec6df32016-09-01 10:44:35 +00001479static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
James Molloy5bf21142016-08-22 19:07:15 +00001480 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1481
1482 // canSinkLastInstruction returning true guarantees that every block has at
1483 // least one non-terminator instruction.
1484 SmallVector<Instruction*,4> Insts;
Dehao Chen018a3af2016-10-17 19:28:44 +00001485 for (auto *BB : Blocks) {
1486 Instruction *I = BB->getTerminator();
1487 do {
1488 I = I->getPrevNode();
1489 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1490 if (!isa<DbgInfoIntrinsic>(I))
1491 Insts.push_back(I);
1492 }
James Molloy5bf21142016-08-22 19:07:15 +00001493
James Molloyeec6df32016-09-01 10:44:35 +00001494 // The only checking we need to do now is that all users of all instructions
1495 // are the same PHI node. canSinkLastInstruction should have checked this but
1496 // it is slightly over-aggressive - it gets confused by commutative instructions
1497 // so double-check it here.
James Molloy5bf21142016-08-22 19:07:15 +00001498 Instruction *I0 = Insts.front();
James Molloyeec6df32016-09-01 10:44:35 +00001499 if (!isa<StoreInst>(I0)) {
1500 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1501 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1502 auto *U = cast<Instruction>(*I->user_begin());
1503 return U == PNUse;
1504 }))
1505 return false;
1506 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001507
James Molloyeec6df32016-09-01 10:44:35 +00001508 // We don't need to do any more checking here; canSinkLastInstruction should
1509 // have done it all for us.
James Molloy5bf21142016-08-22 19:07:15 +00001510 SmallVector<Value*, 4> NewOperands;
1511 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1512 // This check is different to that in canSinkLastInstruction. There, we
1513 // cared about the global view once simplifycfg (and instcombine) have
1514 // completed - it takes into account PHIs that become trivially
1515 // simplifiable. However here we need a more local view; if an operand
1516 // differs we create a PHI and rely on instcombine to clean up the very
1517 // small mess we may make.
1518 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1519 return I->getOperand(O) != I0->getOperand(O);
1520 });
1521 if (!NeedPHI) {
1522 NewOperands.push_back(I0->getOperand(O));
1523 continue;
1524 }
1525
1526 // Create a new PHI in the successor block and populate it.
1527 auto *Op = I0->getOperand(O);
1528 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1529 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1530 Op->getName() + ".sink", &BBEnd->front());
1531 for (auto *I : Insts)
1532 PN->addIncoming(I->getOperand(O), I->getParent());
1533 NewOperands.push_back(PN);
1534 }
1535
1536 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1537 // and move it to the start of the successor block.
1538 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1539 I0->getOperandUse(O).set(NewOperands[O]);
1540 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1541
Robert Lougher5bf04162017-01-04 17:40:32 +00001542 // Update metadata and IR flags, and merge debug locations.
James Molloyd13b1232016-08-30 10:56:08 +00001543 for (auto *I : Insts)
James Molloy0efb96a2016-09-19 08:23:08 +00001544 if (I != I0) {
Dehao Chenf4646272017-10-02 18:13:14 +00001545 // The debug location for the "common" instruction is the merged locations
1546 // of all the commoned instructions. We start with the original location
1547 // of the "common" instruction and iteratively merge each location in the
1548 // loop below.
1549 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1550 // However, as N-way merge for CallInst is rare, so we use simplified API
1551 // instead of using complex API for N-way merge.
1552 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
James Molloyd13b1232016-08-30 10:56:08 +00001553 combineMetadataForCSE(I0, I);
James Molloy0efb96a2016-09-19 08:23:08 +00001554 I0->andIRFlags(I);
1555 }
James Molloyd13b1232016-08-30 10:56:08 +00001556
James Molloy5bf21142016-08-22 19:07:15 +00001557 if (!isa<StoreInst>(I0)) {
1558 // canSinkLastInstruction checked that all instructions were used by
1559 // one and only one PHI node. Find that now, RAUW it to our common
1560 // instruction and nuke it.
1561 assert(I0->hasOneUse());
1562 auto *PN = cast<PHINode>(*I0->user_begin());
1563 PN->replaceAllUsesWith(I0);
1564 PN->eraseFromParent();
1565 }
1566
1567 // Finally nuke all instructions apart from the common instruction.
1568 for (auto *I : Insts)
1569 if (I != I0)
1570 I->eraseFromParent();
James Molloyeec6df32016-09-01 10:44:35 +00001571
1572 return true;
1573}
1574
1575namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001576
James Molloyeec6df32016-09-01 10:44:35 +00001577 // LockstepReverseIterator - Iterates through instructions
1578 // in a set of blocks in reverse order from the first non-terminator.
1579 // For example (assume all blocks have size n):
1580 // LockstepReverseIterator I([B1, B2, B3]);
1581 // *I-- = [B1[n], B2[n], B3[n]];
1582 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1583 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1584 // ...
1585 class LockstepReverseIterator {
1586 ArrayRef<BasicBlock*> Blocks;
1587 SmallVector<Instruction*,4> Insts;
1588 bool Fail;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00001589
James Molloyeec6df32016-09-01 10:44:35 +00001590 public:
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00001591 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
James Molloyeec6df32016-09-01 10:44:35 +00001592 reset();
1593 }
1594
1595 void reset() {
1596 Fail = false;
1597 Insts.clear();
1598 for (auto *BB : Blocks) {
Dehao Chen018a3af2016-10-17 19:28:44 +00001599 Instruction *Inst = BB->getTerminator();
1600 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1601 Inst = Inst->getPrevNode();
1602 if (!Inst) {
1603 // Block wasn't big enough.
1604 Fail = true;
1605 return;
James Molloyeec6df32016-09-01 10:44:35 +00001606 }
Dehao Chen018a3af2016-10-17 19:28:44 +00001607 Insts.push_back(Inst);
James Molloyeec6df32016-09-01 10:44:35 +00001608 }
1609 }
1610
1611 bool isValid() const {
1612 return !Fail;
1613 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001614
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00001615 void operator--() {
James Molloyeec6df32016-09-01 10:44:35 +00001616 if (Fail)
1617 return;
1618 for (auto *&Inst : Insts) {
Dehao Chen018a3af2016-10-17 19:28:44 +00001619 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1620 Inst = Inst->getPrevNode();
Benjamin Kramerd8b07972016-10-15 13:15:05 +00001621 // Already at beginning of block.
1622 if (!Inst) {
James Molloyeec6df32016-09-01 10:44:35 +00001623 Fail = true;
1624 return;
1625 }
James Molloyeec6df32016-09-01 10:44:35 +00001626 }
1627 }
1628
1629 ArrayRef<Instruction*> operator * () const {
1630 return Insts;
1631 }
1632 };
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001633
1634} // end anonymous namespace
James Molloy5bf21142016-08-22 19:07:15 +00001635
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001636/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001637/// check whether BBEnd has only two predecessors and the other predecessor
1638/// ends with an unconditional branch. If it is true, sink any common code
1639/// in the two predecessors to BBEnd.
1640static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1641 assert(BI1->isUnconditional());
Manman Ren93ab6492012-09-20 22:37:36 +00001642 BasicBlock *BBEnd = BI1->getSuccessor(0);
1643
James Molloy88cad7e2016-09-01 12:58:13 +00001644 // We support two situations:
1645 // (1) all incoming arcs are unconditional
1646 // (2) one incoming arc is conditional
1647 //
1648 // (2) is very common in switch defaults and
1649 // else-if patterns;
1650 //
1651 // if (a) f(1);
1652 // else if (b) f(2);
1653 //
1654 // produces:
1655 //
1656 // [if]
1657 // / \
1658 // [f(1)] [if]
1659 // | | \
Amaury Sechet2fec7e42017-01-23 15:13:01 +00001660 // | | |
James Molloy88cad7e2016-09-01 12:58:13 +00001661 // | [f(2)]|
1662 // \ | /
1663 // [ end ]
1664 //
1665 // [end] has two unconditional predecessor arcs and one conditional. The
1666 // conditional refers to the implicit empty 'else' arc. This conditional
1667 // arc can also be caused by an empty default block in a switch.
1668 //
1669 // In this case, we attempt to sink code from all *unconditional* arcs.
1670 // If we can sink instructions from these arcs (determined during the scan
1671 // phase below) we insert a common successor for all unconditional arcs and
1672 // connect that to [end], to enable sinking:
1673 //
1674 // [if]
1675 // / \
1676 // [x(1)] [if]
1677 // | | \
1678 // | | \
1679 // | [x(2)] |
1680 // \ / |
1681 // [sink.split] |
1682 // \ /
1683 // [ end ]
1684 //
1685 SmallVector<BasicBlock*,4> UnconditionalPreds;
1686 Instruction *Cond = nullptr;
1687 for (auto *B : predecessors(BBEnd)) {
1688 auto *T = B->getTerminator();
1689 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1690 UnconditionalPreds.push_back(B);
1691 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1692 Cond = T;
1693 else
1694 return false;
1695 }
1696 if (UnconditionalPreds.size() < 2)
James Molloy475f4a72016-08-22 18:13:12 +00001697 return false;
Taewook Oh505a25a2017-01-28 07:05:43 +00001698
Manman Ren93ab6492012-09-20 22:37:36 +00001699 bool Changed = false;
James Molloyeec6df32016-09-01 10:44:35 +00001700 // We take a two-step approach to tail sinking. First we scan from the end of
1701 // each block upwards in lockstep. If the n'th instruction from the end of each
1702 // block can be sunk, those instructions are added to ValuesToSink and we
1703 // carry on. If we can sink an instruction but need to PHI-merge some operands
1704 // (because they're not identical in each instruction) we add these to
1705 // PHIOperands.
1706 unsigned ScanIdx = 0;
1707 SmallPtrSet<Value*,4> InstructionsToSink;
1708 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
James Molloy88cad7e2016-09-01 12:58:13 +00001709 LockstepReverseIterator LRI(UnconditionalPreds);
James Molloyeec6df32016-09-01 10:44:35 +00001710 while (LRI.isValid() &&
1711 canSinkInstructions(*LRI, PHIOperands)) {
1712 DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] << "\n");
1713 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1714 ++ScanIdx;
1715 --LRI;
1716 }
1717
James Molloy18d96e82016-09-11 08:07:30 +00001718 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
James Molloy88cad7e2016-09-01 12:58:13 +00001719 unsigned NumPHIdValues = 0;
1720 for (auto *I : *LRI)
1721 for (auto *V : PHIOperands[I])
1722 if (InstructionsToSink.count(V) == 0)
1723 ++NumPHIdValues;
1724 DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1725 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1726 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1727 NumPHIInsts++;
Taewook Oh505a25a2017-01-28 07:05:43 +00001728
James Molloy88cad7e2016-09-01 12:58:13 +00001729 return NumPHIInsts <= 1;
1730 };
1731
1732 if (ScanIdx > 0 && Cond) {
James Molloy18d96e82016-09-11 08:07:30 +00001733 // Check if we would actually sink anything first! This mutates the CFG and
1734 // adds an extra block. The goal in doing this is to allow instructions that
1735 // couldn't be sunk before to be sunk - obviously, speculatable instructions
1736 // (such as trunc, add) can be sunk and predicated already. So we check that
1737 // we're going to sink at least one non-speculatable instruction.
1738 LRI.reset();
1739 unsigned Idx = 0;
1740 bool Profitable = false;
1741 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1742 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
1743 Profitable = true;
1744 break;
1745 }
1746 --LRI;
1747 ++Idx;
1748 }
1749 if (!Profitable)
James Molloy88cad7e2016-09-01 12:58:13 +00001750 return false;
Taewook Oh505a25a2017-01-28 07:05:43 +00001751
James Molloy88cad7e2016-09-01 12:58:13 +00001752 DEBUG(dbgs() << "SINK: Splitting edge\n");
1753 // We have a conditional edge and we're going to sink some instructions.
1754 // Insert a new block postdominating all blocks we're going to sink from.
1755 if (!SplitBlockPredecessors(BI1->getSuccessor(0), UnconditionalPreds,
1756 ".sink.split"))
1757 // Edges couldn't be split.
1758 return false;
1759 Changed = true;
1760 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001761
James Molloyeec6df32016-09-01 10:44:35 +00001762 // Now that we've analyzed all potential sinking candidates, perform the
1763 // actual sink. We iteratively sink the last non-terminator of the source
1764 // blocks into their common successor unless doing so would require too
1765 // many PHI instructions to be generated (currently only one PHI is allowed
1766 // per sunk instruction).
1767 //
1768 // We can use InstructionsToSink to discount values needing PHI-merging that will
1769 // actually be sunk in a later iteration. This allows us to be more
1770 // aggressive in what we sink. This does allow a false positive where we
1771 // sink presuming a later value will also be sunk, but stop half way through
1772 // and never actually sink it which means we produce more PHIs than intended.
1773 // This is unlikely in practice though.
1774 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1775 DEBUG(dbgs() << "SINK: Sink: "
James Molloy88cad7e2016-09-01 12:58:13 +00001776 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
James Molloyeec6df32016-09-01 10:44:35 +00001777 << "\n");
1778
1779 // Because we've sunk every instruction in turn, the current instruction to
1780 // sink is always at index 0.
James Molloy18d96e82016-09-11 08:07:30 +00001781 LRI.reset();
1782 if (!ProfitableToSinkInstruction(LRI)) {
James Molloyeec6df32016-09-01 10:44:35 +00001783 // Too many PHIs would be created.
James Molloy88cad7e2016-09-01 12:58:13 +00001784 DEBUG(dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
James Molloyeec6df32016-09-01 10:44:35 +00001785 break;
James Molloy88cad7e2016-09-01 12:58:13 +00001786 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001787
James Molloy88cad7e2016-09-01 12:58:13 +00001788 if (!sinkLastInstruction(UnconditionalPreds))
James Molloyeec6df32016-09-01 10:44:35 +00001789 return Changed;
Manman Ren93ab6492012-09-20 22:37:36 +00001790 NumSinkCommons++;
1791 Changed = true;
1792 }
1793 return Changed;
1794}
1795
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001796/// \brief Determine if we can hoist sink a sole store instruction out of a
1797/// conditional block.
1798///
1799/// We are looking for code like the following:
1800/// BrBB:
1801/// store i32 %add, i32* %arrayidx2
1802/// ... // No other stores or function calls (we could be calling a memory
1803/// ... // function).
1804/// %cmp = icmp ult %x, %y
1805/// br i1 %cmp, label %EndBB, label %ThenBB
1806/// ThenBB:
1807/// store i32 %add5, i32* %arrayidx2
1808/// br label EndBB
1809/// EndBB:
1810/// ...
1811/// We are going to transform this into:
1812/// BrBB:
1813/// store i32 %add, i32* %arrayidx2
1814/// ... //
1815/// %cmp = icmp ult %x, %y
1816/// %add.add5 = select i1 %cmp, i32 %add, %add5
1817/// store i32 %add.add5, i32* %arrayidx2
1818/// ...
1819///
1820/// \return The pointer to the value of the previous store if the store can be
1821/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001822static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1823 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001824 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1825 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001826 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001827
1828 // Volatile or atomic.
1829 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001830 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001831
1832 Value *StorePtr = StoreToHoist->getPointerOperand();
1833
1834 // Look for a store to the same pointer in BrBB.
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001835 unsigned MaxNumInstToLookAt = 9;
David Majnemerd7708772016-06-24 04:05:21 +00001836 for (Instruction &CurI : reverse(*BrBB)) {
1837 if (!MaxNumInstToLookAt)
1838 break;
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001839 // Skip debug info.
1840 if (isa<DbgInfoIntrinsic>(CurI))
1841 continue;
1842 --MaxNumInstToLookAt;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001843
David L Kreitzer96674172016-08-12 21:06:53 +00001844 // Could be calling an instruction that affects memory like free().
David Majnemerd7708772016-06-24 04:05:21 +00001845 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001846 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001847
David Majnemerd7708772016-06-24 04:05:21 +00001848 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1849 // Found the previous store make sure it stores to the same location.
1850 if (SI->getPointerOperand() == StorePtr)
1851 // Found the previous store, return its value operand.
1852 return SI->getValueOperand();
Craig Topperf40110f2014-04-25 05:29:35 +00001853 return nullptr; // Unknown store.
David Majnemerd7708772016-06-24 04:05:21 +00001854 }
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001855 }
1856
Craig Topperf40110f2014-04-25 05:29:35 +00001857 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001858}
1859
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001860/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001861///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001862/// Note that this is a very risky transform currently. Speculating
1863/// instructions like this is most often not desirable. Instead, there is an MI
1864/// pass which can do it with full awareness of the resource constraints.
1865/// However, some cases are "obvious" and we should do directly. An example of
1866/// this is speculating a single, reasonably cheap instruction.
1867///
1868/// There is only one distinct advantage to flattening the CFG at the IR level:
1869/// it makes very common but simplistic optimizations such as are common in
1870/// instcombine and the DAG combiner more powerful by removing CFG edges and
1871/// modeling their effects with easier to reason about SSA value graphs.
1872///
1873///
1874/// An illustration of this transform is turning this IR:
1875/// \code
1876/// BB:
1877/// %cmp = icmp ult %x, %y
1878/// br i1 %cmp, label %EndBB, label %ThenBB
1879/// ThenBB:
1880/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001881/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001882/// EndBB:
1883/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1884/// ...
1885/// \endcode
1886///
1887/// Into this IR:
1888/// \code
1889/// BB:
1890/// %cmp = icmp ult %x, %y
1891/// %sub = sub %x, %y
1892/// %cond = select i1 %cmp, 0, %sub
1893/// ...
1894/// \endcode
1895///
1896/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001897static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001898 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001899 // Be conservative for now. FP select instruction can often be expensive.
1900 Value *BrCond = BI->getCondition();
1901 if (isa<FCmpInst>(BrCond))
1902 return false;
1903
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001904 BasicBlock *BB = BI->getParent();
1905 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1906
1907 // If ThenBB is actually on the false edge of the conditional branch, remember
1908 // to swap the select operands later.
1909 bool Invert = false;
1910 if (ThenBB != BI->getSuccessor(0)) {
1911 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1912 Invert = true;
1913 }
1914 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1915
Chandler Carruthceff2222013-01-25 05:40:09 +00001916 // Keep a count of how many times instructions are used within CondBB when
1917 // they are candidates for sinking into CondBB. Specifically:
1918 // - They are defined in BB, and
1919 // - They have no side effects, and
1920 // - All of their uses are in CondBB.
1921 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1922
Chandler Carruth7481ca82013-01-24 11:52:58 +00001923 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001924 Value *SpeculatedStoreValue = nullptr;
1925 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001926 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001927 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001928 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001929 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001930 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001931 if (isa<DbgInfoIntrinsic>(I))
1932 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001933
Mark Lacey274f48b2015-04-12 18:18:51 +00001934 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001935 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001936 ++SpeculationCost;
1937 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001938 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001939
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001940 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001941 if (!isSafeToSpeculativelyExecute(I) &&
1942 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1943 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001944 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001945 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001946 ComputeSpeculationCost(I, TTI) >
1947 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001948 return false;
1949
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001950 // Store the store speculation candidate.
1951 if (SpeculatedStoreValue)
1952 SpeculatedStore = cast<StoreInst>(I);
1953
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001954 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001955 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001956 // being sunk into the use block.
Dehao Chenf6c00832016-05-18 19:44:21 +00001957 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001958 Instruction *OpI = dyn_cast<Instruction>(*i);
Dehao Chenf6c00832016-05-18 19:44:21 +00001959 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
Chandler Carruthceff2222013-01-25 05:40:09 +00001960 continue; // Not a candidate for sinking.
1961
1962 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001963 }
1964 }
Evan Cheng89200c92008-06-07 08:52:29 +00001965
Chandler Carruthceff2222013-01-25 05:40:09 +00001966 // Consider any sink candidates which are only used in CondBB as costs for
1967 // speculation. Note, while we iterate over a DenseMap here, we are summing
1968 // and so iteration order isn't significant.
Dehao Chenf6c00832016-05-18 19:44:21 +00001969 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1970 I = SinkCandidateUseCounts.begin(),
1971 E = SinkCandidateUseCounts.end();
Chandler Carruthceff2222013-01-25 05:40:09 +00001972 I != E; ++I)
1973 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001974 ++SpeculationCost;
1975 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001976 return false;
1977 }
1978
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001979 // Check that the PHI nodes can be converted to selects.
1980 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001981 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001982 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001983 Value *OrigV = PN->getIncomingValueForBlock(BB);
1984 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001985
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001986 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001987 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001988 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001989 continue;
1990
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001991 // Don't convert to selects if we could remove undefined behavior instead.
1992 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1993 passingValueIsAlwaysUndefined(ThenV, PN))
1994 return false;
1995
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001996 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001997 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1998 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1999 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00002000 continue; // Known safe and cheap.
2001
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002002 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2003 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00002004 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002005 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
2006 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00002007 unsigned MaxCost =
2008 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
James Molloy7c336572015-02-11 12:15:41 +00002009 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00002010 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002011
Chandler Carruth01bffaa2013-01-24 12:05:17 +00002012 // Account for the cost of an unfolded ConstantExpr which could end up
2013 // getting expanded into Instructions.
2014 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00002015 // constant expression.
2016 ++SpeculationCost;
2017 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002018 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00002019 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002020
2021 // If there are no PHIs to process, bail early. This helps ensure idempotence
2022 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002023 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002024 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002025
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002026 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00002027 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00002028
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002029 // Insert a select of the value of the speculated store.
2030 if (SpeculatedStoreValue) {
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002031 IRBuilder<NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002032 Value *TrueV = SpeculatedStore->getValueOperand();
2033 Value *FalseV = SpeculatedStoreValue;
2034 if (Invert)
2035 std::swap(TrueV, FalseV);
Sanjay Patel796db352016-03-26 23:30:50 +00002036 Value *S = Builder.CreateSelect(
Craig Topper7c7fcab2017-10-31 19:03:51 +00002037 BrCond, TrueV, FalseV, "spec.store.select", BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002038 SpeculatedStore->setOperand(0, S);
Dehao Chenf4646272017-10-02 18:13:14 +00002039 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2040 SpeculatedStore->getDebugLoc());
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002041 }
2042
Igor Laevsky7310c682015-11-18 14:50:18 +00002043 // Metadata can be dependent on the condition we are hoisting above.
2044 // Conservatively strip all metadata on the instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002045 for (auto &I : *ThenBB)
Igor Laevsky7310c682015-11-18 14:50:18 +00002046 I.dropUnknownNonDebugMetadata();
2047
Chandler Carruth7481ca82013-01-24 11:52:58 +00002048 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002049 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2050 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00002051
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002052 // Insert selects and rewrite the PHI operands.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002053 IRBuilder<NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002054 for (BasicBlock::iterator I = EndBB->begin();
2055 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2056 unsigned OrigI = PN->getBasicBlockIndex(BB);
2057 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
2058 Value *OrigV = PN->getIncomingValue(OrigI);
2059 Value *ThenV = PN->getIncomingValue(ThenI);
2060
2061 // Skip PHIs which are trivial.
2062 if (OrigV == ThenV)
2063 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00002064
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002065 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002066 // false value is the preexisting value. Swap them if the branch
2067 // destinations were inverted.
2068 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002069 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002070 std::swap(TrueV, FalseV);
Sanjay Patelf11ab052016-04-15 15:32:12 +00002071 Value *V = Builder.CreateSelect(
Craig Topper7c7fcab2017-10-31 19:03:51 +00002072 BrCond, TrueV, FalseV, "spec.select", BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002073 PN->setIncomingValue(OrigI, V);
2074 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00002075 }
2076
Evan Cheng89553cc2008-06-12 21:15:59 +00002077 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00002078 return true;
2079}
2080
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002081/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002082static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2083 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00002084 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002085
Devang Patel84fceff2009-03-10 18:00:05 +00002086 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00002087 if (isa<DbgInfoIntrinsic>(BBI))
2088 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00002089 if (Size > 10)
2090 return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00002091 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002092
Dale Johannesened6f5a82009-03-12 23:18:09 +00002093 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00002094 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002095 for (User *U : BBI->users()) {
2096 Instruction *UI = cast<Instruction>(U);
Dehao Chenf6c00832016-05-18 19:44:21 +00002097 if (UI->getParent() != BB || isa<PHINode>(UI))
2098 return false;
Chris Lattner6c701062005-09-20 01:48:40 +00002099 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002100
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002101 // Looks ok, continue checking.
2102 }
Chris Lattner6c701062005-09-20 01:48:40 +00002103
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002104 return true;
2105}
2106
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002107/// If we have a conditional branch on a PHI node value that is defined in the
2108/// same block as the branch and if any PHI entries are constants, thread edges
2109/// corresponding to that entry to be branches to their ultimate destination.
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002110static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
2111 AssumptionCache *AC) {
Chris Lattner748f9032005-09-19 23:49:37 +00002112 BasicBlock *BB = BI->getParent();
2113 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00002114 // NOTE: we currently cannot transform this case if the PHI node is used
2115 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002116 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2117 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002118
Chris Lattner748f9032005-09-19 23:49:37 +00002119 // Degenerate case of a single entry PHI.
2120 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00002121 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002122 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00002123 }
2124
2125 // Now we know that this block has multiple preds and two succs.
Dehao Chenf6c00832016-05-18 19:44:21 +00002126 if (!BlockIsSimpleEnoughToThreadThrough(BB))
2127 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002128
Justin Lebardb639492016-02-12 21:01:36 +00002129 // Can't fold blocks that contain noduplicate or convergent calls.
David Majnemer0a16c222016-08-11 21:15:00 +00002130 if (any_of(*BB, [](const Instruction &I) {
Justin Lebardb639492016-02-12 21:01:36 +00002131 const CallInst *CI = dyn_cast<CallInst>(&I);
2132 return CI && (CI->cannotDuplicate() || CI->isConvergent());
2133 }))
2134 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00002135
Chris Lattner748f9032005-09-19 23:49:37 +00002136 // Okay, this is a simple enough basic block. See if any phi values are
2137 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002138 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002139 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Dehao Chenf6c00832016-05-18 19:44:21 +00002140 if (!CB || !CB->getType()->isIntegerTy(1))
2141 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002142
Chris Lattner4088e2b2010-12-13 01:47:07 +00002143 // Okay, we now know that all edges from PredBB should be revectored to
2144 // branch to RealDest.
2145 BasicBlock *PredBB = PN->getIncomingBlock(i);
2146 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002147
Dehao Chenf6c00832016-05-18 19:44:21 +00002148 if (RealDest == BB)
2149 continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00002150 // Skip if the predecessor's terminator is an indirect branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00002151 if (isa<IndirectBrInst>(PredBB->getTerminator()))
2152 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002153
Chris Lattner4088e2b2010-12-13 01:47:07 +00002154 // The dest block might have PHI nodes, other predecessors and other
2155 // difficult cases. Instead of being smart about this, just insert a new
2156 // block that jumps to the destination block, effectively splitting
2157 // the edge we are about to create.
Dehao Chenf6c00832016-05-18 19:44:21 +00002158 BasicBlock *EdgeBB =
2159 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2160 RealDest->getParent(), RealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002161 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002162
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002163 // Update PHI nodes.
2164 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002165
2166 // BB may have instructions that are being threaded over. Clone these
2167 // instructions into EdgeBB. We know that there will be no uses of the
2168 // cloned instructions outside of EdgeBB.
2169 BasicBlock::iterator InsertPt = EdgeBB->begin();
Dehao Chenf6c00832016-05-18 19:44:21 +00002170 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002171 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2172 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2173 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2174 continue;
2175 }
2176 // Clone the instruction.
2177 Instruction *N = BBI->clone();
Dehao Chenf6c00832016-05-18 19:44:21 +00002178 if (BBI->hasName())
2179 N->setName(BBI->getName() + ".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002180
Chris Lattner4088e2b2010-12-13 01:47:07 +00002181 // Update operands due to translation.
Dehao Chenf6c00832016-05-18 19:44:21 +00002182 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2183 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002184 if (PI != TranslateMap.end())
2185 *i = PI->second;
2186 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002187
Chris Lattner4088e2b2010-12-13 01:47:07 +00002188 // Check for trivial simplification.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002189 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
David Majnemerb8da3a22016-06-25 00:04:10 +00002190 if (!BBI->use_empty())
2191 TranslateMap[&*BBI] = V;
2192 if (!N->mayHaveSideEffects()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00002193 N->deleteValue(); // Instruction folded away, don't need actual inst
David Majnemerb8da3a22016-06-25 00:04:10 +00002194 N = nullptr;
2195 }
Chris Lattner4088e2b2010-12-13 01:47:07 +00002196 } else {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002197 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002198 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002199 }
David Majnemerb8da3a22016-06-25 00:04:10 +00002200 // Insert the new instruction into its new home.
2201 if (N)
2202 EdgeBB->getInstList().insert(InsertPt, N);
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002203
2204 // Register the new instruction with the assumption cache if necessary.
2205 if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2206 if (II->getIntrinsicID() == Intrinsic::assume)
2207 AC->registerAssumption(II);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002208 }
2209
2210 // Loop over all of the edges from PredBB to BB, changing them to branch
2211 // to EdgeBB instead.
2212 TerminatorInst *PredBBTI = PredBB->getTerminator();
2213 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2214 if (PredBBTI->getSuccessor(i) == BB) {
2215 BB->removePredecessor(PredBB);
2216 PredBBTI->setSuccessor(i, EdgeBB);
2217 }
Bill Wendling4f163df2011-06-04 09:42:04 +00002218
Chris Lattner4088e2b2010-12-13 01:47:07 +00002219 // Recurse, simplifying any other constants.
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002220 return FoldCondBranchOnPHI(BI, DL, AC) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00002221 }
Chris Lattner748f9032005-09-19 23:49:37 +00002222
2223 return false;
2224}
2225
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002226/// Given a BB that starts with the specified two-entry PHI node,
2227/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002228static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2229 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002230 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2231 // statement", which has a very simple dominance structure. Basically, we
2232 // are trying to find the condition that is being branched on, which
2233 // subsequently causes this merge to happen. We really want control
2234 // dependence information for this check, but simplifycfg can't keep it up
2235 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002236 BasicBlock *BB = PN->getParent();
2237 BasicBlock *IfTrue, *IfFalse;
2238 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00002239 if (!IfCond ||
2240 // Don't bother if the branch will be constant folded trivially.
2241 isa<ConstantInt>(IfCond))
2242 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002243
Chris Lattner95adf8f12006-11-18 19:19:36 +00002244 // Okay, we found that we can merge this two-entry phi node into a select.
2245 // Doing so would require us to fold *all* two entry phi nodes in this block.
2246 // At some point this becomes non-profitable (particularly if the target
2247 // doesn't support cmov's). Only do this transformation if there are two or
2248 // fewer PHI nodes in this block.
2249 unsigned NumPhis = 0;
2250 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2251 if (NumPhis > 2)
2252 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002253
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002254 // Loop over the PHI's seeing if we can promote them all to select
2255 // instructions. While we are at it, keep track of the instructions
2256 // that need to be moved to the dominating block.
Dehao Chenf6c00832016-05-18 19:44:21 +00002257 SmallPtrSet<Instruction *, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00002258 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2259 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00002260 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2261 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002262
Chris Lattner7499b452010-12-14 08:46:09 +00002263 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2264 PHINode *PN = cast<PHINode>(II++);
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002265 if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00002266 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00002267 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00002268 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002269 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002270
Peter Collingbournee3511e12011-04-29 18:47:31 +00002271 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002272 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00002273 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002274 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00002275 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002276 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002277
Sylvestre Ledru35521e22012-07-23 08:51:15 +00002278 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00002279 // we ran out of PHIs then we simplified them all.
2280 PN = dyn_cast<PHINode>(BB->begin());
Dehao Chenf6c00832016-05-18 19:44:21 +00002281 if (!PN)
2282 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002283
Chris Lattner7499b452010-12-14 08:46:09 +00002284 // Don't fold i1 branches on PHIs which contain binary operators. These can
2285 // often be turned into switches and other things.
2286 if (PN->getType()->isIntegerTy(1) &&
2287 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2288 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2289 isa<BinaryOperator>(IfCond)))
2290 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002291
Sanjay Patel2e002772016-03-12 18:05:53 +00002292 // If all PHI nodes are promotable, check to make sure that all instructions
2293 // in the predecessor blocks can be promoted as well. If not, we won't be able
2294 // to get rid of the control flow, so it's not worth promoting to select
2295 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00002296 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002297 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2298 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2299 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002300 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002301 } else {
2302 DomBlock = *pred_begin(IfBlock1);
Dehao Chenf6c00832016-05-18 19:44:21 +00002303 for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2304 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002305 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002306 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002307 // Because of this, we won't be able to get rid of the control flow, so
2308 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002309 return false;
2310 }
2311 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002312
Chris Lattner9ac168d2010-12-14 07:41:39 +00002313 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002314 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002315 } else {
2316 DomBlock = *pred_begin(IfBlock2);
Dehao Chenf6c00832016-05-18 19:44:21 +00002317 for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2318 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002319 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002320 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002321 // Because of this, we won't be able to get rid of the control flow, so
2322 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002323 return false;
2324 }
2325 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002326
Chris Lattner9fd838d2010-12-14 07:23:10 +00002327 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00002328 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002329
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002330 // If we can still promote the PHI nodes after this gauntlet of tests,
2331 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00002332 Instruction *InsertPt = DomBlock->getTerminator();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002333 IRBuilder<NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002334
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002335 // Move all 'aggressive' instructions, which are defined in the
2336 // conditional parts of the if's up to the dominating block.
David Majnemere8fd5f92016-08-29 17:14:08 +00002337 if (IfBlock1) {
2338 for (auto &I : *IfBlock1)
2339 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002340 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002341 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002342 IfBlock1->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002343 }
2344 if (IfBlock2) {
2345 for (auto &I : *IfBlock2)
2346 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002347 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002348 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002349 IfBlock2->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002350 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002351
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002352 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2353 // Change the PHI node into a select instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002354 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002355 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002356
Sanjay Patel9e23fed2016-03-17 15:30:52 +00002357 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2358 PN->replaceAllUsesWith(Sel);
2359 Sel->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00002360 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002361 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002362
Chris Lattner335f0e42010-12-14 08:01:53 +00002363 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2364 // has been flattened. Change DomBlock to jump directly to our new block to
2365 // avoid other simplifycfg's kicking in on the diamond.
2366 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00002367 Builder.SetInsertPoint(OldTI);
2368 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00002369 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002370 return true;
2371}
Chris Lattner748f9032005-09-19 23:49:37 +00002372
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002373/// If we found a conditional branch that goes to two returning blocks,
2374/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00002375/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002376static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00002377 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002378 assert(BI->isConditional() && "Must be a conditional branch");
2379 BasicBlock *TrueSucc = BI->getSuccessor(0);
2380 BasicBlock *FalseSucc = BI->getSuccessor(1);
2381 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2382 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002383
Chris Lattner86bbf332008-04-24 00:01:19 +00002384 // Check to ensure both blocks are empty (just a return) or optionally empty
2385 // with PHI nodes. If there are other instructions, merging would cause extra
2386 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002387 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002388 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002389 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002390 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00002391
Devang Pateldd14e0f2011-05-18 21:33:11 +00002392 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002393 // Okay, we found a branch that is going to two return nodes. If
2394 // there is no return value for this function, just change the
2395 // branch into a return.
2396 if (FalseRet->getNumOperands() == 0) {
2397 TrueSucc->removePredecessor(BI->getParent());
2398 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00002399 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00002400 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002401 return true;
2402 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002403
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002404 // Otherwise, figure out what the true and false return values are
2405 // so we can insert a new select instruction.
2406 Value *TrueValue = TrueRet->getReturnValue();
2407 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002408
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002409 // Unwrap any PHI nodes in the return blocks.
2410 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2411 if (TVPN->getParent() == TrueSucc)
2412 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2413 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2414 if (FVPN->getParent() == FalseSucc)
2415 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002416
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002417 // In order for this transformation to be safe, we must be able to
2418 // unconditionally execute both operands to the return. This is
2419 // normally the case, but we could have a potentially-trapping
2420 // constant expression that prevents this transformation from being
2421 // safe.
2422 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2423 if (TCV->canTrap())
2424 return false;
2425 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2426 if (FCV->canTrap())
2427 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002428
Chris Lattner86bbf332008-04-24 00:01:19 +00002429 // Okay, we collected all the mapped values and checked them for sanity, and
2430 // defined to really do this transformation. First, update the CFG.
2431 TrueSucc->removePredecessor(BI->getParent());
2432 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002433
Chris Lattner86bbf332008-04-24 00:01:19 +00002434 // Insert select instructions where needed.
2435 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002436 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002437 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002438 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2439 } else if (isa<UndefValue>(TrueValue)) {
2440 TrueValue = FalseValue;
2441 } else {
Sanjay Patelfacf45a2016-04-27 23:14:12 +00002442 TrueValue =
2443 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002444 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002445 }
2446
Dehao Chenf6c00832016-05-18 19:44:21 +00002447 Value *RI =
2448 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
Devang Pateldd14e0f2011-05-18 21:33:11 +00002449
Dehao Chenf6c00832016-05-18 19:44:21 +00002450 (void)RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002451
David Greene725c7c32010-01-05 01:26:52 +00002452 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002453 << "\n " << *BI << "NewRet = " << *RI
Dehao Chenf6c00832016-05-18 19:44:21 +00002454 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002455
Eli Friedmancb61afb2008-12-16 20:54:32 +00002456 EraseTerminatorInstAndDCECond(BI);
2457
Chris Lattner86bbf332008-04-24 00:01:19 +00002458 return true;
2459}
2460
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002461/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002462/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002463static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002464 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2465 return false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00002466 for (Instruction &I : *PB) {
2467 Instruction *PBI = &I;
Manman Rend33f4ef2012-06-13 05:43:29 +00002468 // Check whether Inst and PBI generate the same value.
2469 if (Inst->isIdenticalTo(PBI)) {
2470 Inst->replaceAllUsesWith(PBI);
2471 Inst->eraseFromParent();
2472 return true;
2473 }
2474 }
2475 return false;
2476}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002477
Dehao Chenf16376b2016-05-18 22:41:03 +00002478/// Return true if either PBI or BI has branch weight available, and store
2479/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2480/// not have branch weight, use 1:1 as its weight.
2481static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2482 uint64_t &PredTrueWeight,
2483 uint64_t &PredFalseWeight,
2484 uint64_t &SuccTrueWeight,
2485 uint64_t &SuccFalseWeight) {
2486 bool PredHasWeights =
2487 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2488 bool SuccHasWeights =
2489 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2490 if (PredHasWeights || SuccHasWeights) {
2491 if (!PredHasWeights)
2492 PredTrueWeight = PredFalseWeight = 1;
2493 if (!SuccHasWeights)
2494 SuccTrueWeight = SuccFalseWeight = 1;
2495 return true;
2496 } else {
2497 return false;
2498 }
2499}
2500
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002501/// If this basic block is simple enough, and if a predecessor branches to us
2502/// and one of our successors, fold the block into the predecessor and use
2503/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002504bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002505 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002506
Craig Topperf40110f2014-04-25 05:29:35 +00002507 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002508 if (BI->isConditional())
2509 Cond = dyn_cast<Instruction>(BI->getCondition());
2510 else {
2511 // For unconditional branch, check for a simple CFG pattern, where
2512 // BB has a single predecessor and BB's successor is also its predecessor's
Craig Topper36af40c2017-08-02 02:34:16 +00002513 // successor. If such pattern exists, check for CSE between BB and its
Manman Rend33f4ef2012-06-13 05:43:29 +00002514 // predecessor.
2515 if (BasicBlock *PB = BB->getSinglePredecessor())
2516 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2517 if (PBI->isConditional() &&
2518 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2519 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002520 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002521 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002522 if (isa<CmpInst>(Curr)) {
2523 Cond = Curr;
2524 break;
2525 }
2526 // Quit if we can't remove this instruction.
2527 if (!checkCSEInPredecessor(Curr, PB))
2528 return false;
2529 }
2530 }
2531
Craig Topperf40110f2014-04-25 05:29:35 +00002532 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002533 return false;
2534 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002535
Craig Topperf40110f2014-04-25 05:29:35 +00002536 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2537 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002538 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002539
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002540 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002541 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002542
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002543 // Ignore dbg intrinsics.
Dehao Chenf6c00832016-05-18 19:44:21 +00002544 while (isa<DbgInfoIntrinsic>(CondIt))
2545 ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002546
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002547 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002548 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002549
Jingyue Wufc029672014-09-30 22:23:38 +00002550 // Only allow this transformation if computing the condition doesn't involve
2551 // too many instructions and these involved instructions can be executed
2552 // unconditionally. We denote all involved instructions except the condition
2553 // as "bonus instructions", and only allow this transformation when the
2554 // number of the bonus instructions does not exceed a certain threshold.
2555 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002556 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002557 // Ignore dbg intrinsics.
2558 if (isa<DbgInfoIntrinsic>(I))
2559 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002560 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002561 return false;
2562 // I has only one use and can be executed unconditionally.
2563 Instruction *User = dyn_cast<Instruction>(I->user_back());
2564 if (User == nullptr || User->getParent() != BB)
2565 return false;
2566 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2567 // to use any other instruction, User must be an instruction between next(I)
2568 // and Cond.
2569 ++NumBonusInsts;
2570 // Early exits once we reach the limit.
2571 if (NumBonusInsts > BonusInstThreshold)
2572 return false;
2573 }
2574
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002575 // Cond is known to be a compare or binary operator. Check to make sure that
2576 // neither operand is a potentially-trapping constant expression.
2577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2578 if (CE->canTrap())
2579 return false;
2580 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2581 if (CE->canTrap())
2582 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002583
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002584 // Finally, don't infinitely unroll conditional loops.
Dehao Chenf6c00832016-05-18 19:44:21 +00002585 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002586 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002587 if (TrueDest == BB || FalseDest == BB)
2588 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002589
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002590 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2591 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002592 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002593
Chris Lattner80b03a12008-07-13 22:23:11 +00002594 // Check that we have two conditional branches. If there is a PHI node in
2595 // the common successor, verify that the same value flows in from both
2596 // blocks.
Dehao Chenf6c00832016-05-18 19:44:21 +00002597 SmallVector<PHINode *, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002598 if (!PBI || PBI->isUnconditional() ||
Dehao Chenf6c00832016-05-18 19:44:21 +00002599 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
Manman Rend33f4ef2012-06-13 05:43:29 +00002600 (!BI->isConditional() &&
2601 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002602 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002603
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002604 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002605 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002606 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002607
Manman Rend33f4ef2012-06-13 05:43:29 +00002608 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002609 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002610 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002611 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002612 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002613 } else if (PBI->getSuccessor(0) == FalseDest) {
2614 Opc = Instruction::And;
2615 InvertPredCond = true;
2616 } else if (PBI->getSuccessor(1) == TrueDest) {
2617 Opc = Instruction::Or;
2618 InvertPredCond = true;
2619 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002620 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002621 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002622 } else {
2623 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2624 continue;
2625 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002626
David Greene725c7c32010-01-05 01:26:52 +00002627 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002628 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002629
Chris Lattner55eaae12008-07-13 21:20:19 +00002630 // If we need to invert the condition in the pred block to match, do so now.
2631 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002632 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002633
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002634 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2635 CmpInst *CI = cast<CmpInst>(NewCond);
2636 CI->setPredicate(CI->getInversePredicate());
2637 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00002638 NewCond =
2639 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002640 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002641
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002642 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002643 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002644 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002645
Jingyue Wufc029672014-09-30 22:23:38 +00002646 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002647 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002648 // bonus instructions to a predecessor block.
2649 ValueToValueMapTy VMap; // maps original values to cloned values
2650 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002651 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002652 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002653 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002654 if (isa<DbgInfoIntrinsic>(BonusInst))
2655 continue;
2656 Instruction *NewBonusInst = BonusInst->clone();
2657 RemapInstruction(NewBonusInst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002658 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002659 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002660
2661 // If we moved a load, we cannot any longer claim any knowledge about
2662 // its potential value. The previous information might have been valid
2663 // only given the branch precondition.
2664 // For an analogous reason, we must also drop all the metadata whose
2665 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002666 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002667
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002668 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2669 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002670 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002671 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002672
Chris Lattner55eaae12008-07-13 21:20:19 +00002673 // Clone Cond into the predecessor basic block, and or/and the
2674 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002675 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002676 RemapInstruction(New, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002677 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002678 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002679 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002680 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002681
Manman Rend33f4ef2012-06-13 05:43:29 +00002682 if (BI->isConditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002683 Instruction *NewCond = cast<Instruction>(
2684 Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002685 PBI->setCondition(NewCond);
2686
Manman Renbfb9d432012-09-15 00:39:57 +00002687 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenf16376b2016-05-18 22:41:03 +00002688 bool HasWeights =
2689 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2690 SuccTrueWeight, SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002691 SmallVector<uint64_t, 8> NewWeights;
2692
Manman Rend33f4ef2012-06-13 05:43:29 +00002693 if (PBI->getSuccessor(0) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002694 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002695 // PBI: br i1 %x, BB, FalseDest
2696 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002697 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002698 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
Dehao Chenf6c00832016-05-18 19:44:21 +00002699 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002700 // TrueWeight for PBI * FalseWeight for BI.
2701 // We assume that total weights of a BranchInst can fit into 32 bits.
2702 // Therefore, we will not have overflow using 64-bit arithmetic.
Dehao Chenf6c00832016-05-18 19:44:21 +00002703 NewWeights.push_back(PredFalseWeight *
2704 (SuccFalseWeight + SuccTrueWeight) +
2705 PredTrueWeight * SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002706 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002707 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2708 PBI->setSuccessor(0, TrueDest);
2709 }
2710 if (PBI->getSuccessor(1) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002711 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002712 // PBI: br i1 %x, TrueDest, BB
2713 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002714 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002715 // FalseWeight for PBI * TrueWeight for BI.
Dehao Chenf6c00832016-05-18 19:44:21 +00002716 NewWeights.push_back(PredTrueWeight *
2717 (SuccFalseWeight + SuccTrueWeight) +
2718 PredFalseWeight * SuccTrueWeight);
2719 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002720 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2721 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002722 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2723 PBI->setSuccessor(1, FalseDest);
2724 }
Manman Renbfb9d432012-09-15 00:39:57 +00002725 if (NewWeights.size() == 2) {
2726 // Halve the weights if any of them cannot fit in an uint32_t
2727 FitWeights(NewWeights);
2728
Dehao Chenf6c00832016-05-18 19:44:21 +00002729 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2730 NewWeights.end());
2731 PBI->setMetadata(
2732 LLVMContext::MD_prof,
2733 MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
Manman Renbfb9d432012-09-15 00:39:57 +00002734 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002735 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002736 } else {
2737 // Update PHI nodes in the common successors.
2738 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002739 ConstantInt *PBI_C = cast<ConstantInt>(
Dehao Chenf6c00832016-05-18 19:44:21 +00002740 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
Manman Rend33f4ef2012-06-13 05:43:29 +00002741 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002742 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002743 if (PBI->getSuccessor(0) == TrueDest) {
2744 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2745 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2746 // is false: !PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002747 Instruction *NotCond = cast<Instruction>(
2748 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2749 MergedCond = cast<Instruction>(
2750 Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002751 if (PBI_C->isOne())
Dehao Chenf6c00832016-05-18 19:44:21 +00002752 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2753 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002754 } else {
2755 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2756 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2757 // is false: PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002758 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2759 Instruction::And, PBI->getCondition(), New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002760 if (PBI_C->isOne()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002761 Instruction *NotCond = cast<Instruction>(
2762 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2763 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2764 Instruction::Or, NotCond, MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002765 }
2766 }
2767 // Update PHI Node.
2768 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2769 MergedCond);
2770 }
2771 // Change PBI from Conditional to Unconditional.
2772 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2773 EraseTerminatorInstAndDCECond(PBI);
2774 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002775 }
Devang Pateld715ec82011-04-06 22:37:20 +00002776
Michael Kuperstein3ca147e2016-12-16 21:23:59 +00002777 // If BI was a loop latch, it may have had associated loop metadata.
2778 // We need to copy it to the new latch, that is, PBI.
2779 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
2780 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
2781
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002782 // TODO: If BB is reachable from all paths through PredBlock, then we
2783 // could replace PBI's branch probabilities with BI's.
2784
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002785 // Copy any debug value intrinsics into the end of PredBlock.
Benjamin Kramer135f7352016-06-26 12:28:59 +00002786 for (Instruction &I : *BB)
2787 if (isa<DbgInfoIntrinsic>(I))
2788 I.clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002789
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002790 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002791 }
2792 return false;
2793}
2794
James Molloy4de84dd2015-11-04 15:28:04 +00002795// If there is only one store in BB1 and BB2, return it, otherwise return
2796// nullptr.
2797static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2798 StoreInst *S = nullptr;
2799 for (auto *BB : {BB1, BB2}) {
2800 if (!BB)
2801 continue;
2802 for (auto &I : *BB)
2803 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2804 if (S)
2805 // Multiple stores seen.
2806 return nullptr;
2807 else
2808 S = SI;
2809 }
2810 }
2811 return S;
2812}
2813
2814static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2815 Value *AlternativeV = nullptr) {
2816 // PHI is going to be a PHI node that allows the value V that is defined in
2817 // BB to be referenced in BB's only successor.
2818 //
2819 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2820 // doesn't matter to us what the other operand is (it'll never get used). We
2821 // could just create a new PHI with an undef incoming value, but that could
2822 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2823 // other PHI. So here we directly look for some PHI in BB's successor with V
2824 // as an incoming operand. If we find one, we use it, else we create a new
2825 // one.
2826 //
2827 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2828 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2829 // where OtherBB is the single other predecessor of BB's only successor.
2830 PHINode *PHI = nullptr;
2831 BasicBlock *Succ = BB->getSingleSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00002832
James Molloy4de84dd2015-11-04 15:28:04 +00002833 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2834 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2835 PHI = cast<PHINode>(I);
2836 if (!AlternativeV)
2837 break;
2838
2839 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2840 auto PredI = pred_begin(Succ);
2841 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2842 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2843 break;
2844 PHI = nullptr;
2845 }
2846 if (PHI)
2847 return PHI;
2848
James Molloy3d21dcf2015-12-16 14:12:44 +00002849 // If V is not an instruction defined in BB, just return it.
2850 if (!AlternativeV &&
2851 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2852 return V;
2853
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002854 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002855 PHI->addIncoming(V, BB);
2856 for (BasicBlock *PredBB : predecessors(Succ))
2857 if (PredBB != BB)
Dehao Chenf6c00832016-05-18 19:44:21 +00002858 PHI->addIncoming(
2859 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
James Molloy4de84dd2015-11-04 15:28:04 +00002860 return PHI;
2861}
2862
2863static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2864 BasicBlock *QTB, BasicBlock *QFB,
2865 BasicBlock *PostBB, Value *Address,
Alexey Bataev978e2e42017-08-29 20:06:24 +00002866 bool InvertPCond, bool InvertQCond,
2867 const DataLayout &DL) {
James Molloy4de84dd2015-11-04 15:28:04 +00002868 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2869 return Operator::getOpcode(&I) == Instruction::BitCast &&
2870 I.getType()->isPointerTy();
2871 };
2872
2873 // If we're not in aggressive mode, we only optimize if we have some
2874 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2875 auto IsWorthwhile = [&](BasicBlock *BB) {
2876 if (!BB)
2877 return true;
2878 // Heuristic: if the block can be if-converted/phi-folded and the
2879 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2880 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002881 unsigned N = 0;
2882 for (auto &I : *BB) {
2883 // Cheap instructions viable for folding.
2884 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2885 isa<StoreInst>(I))
2886 ++N;
2887 // Free instructions.
2888 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2889 IsaBitcastOfPointerType(I))
2890 continue;
2891 else
James Molloy4de84dd2015-11-04 15:28:04 +00002892 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002893 }
2894 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002895 };
2896
Dehao Chenf6c00832016-05-18 19:44:21 +00002897 if (!MergeCondStoresAggressively &&
2898 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2899 !IsWorthwhile(QFB)))
James Molloy4de84dd2015-11-04 15:28:04 +00002900 return false;
2901
2902 // For every pointer, there must be exactly two stores, one coming from
2903 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2904 // store (to any address) in PTB,PFB or QTB,QFB.
2905 // FIXME: We could relax this restriction with a bit more work and performance
2906 // testing.
2907 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2908 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2909 if (!PStore || !QStore)
2910 return false;
2911
2912 // Now check the stores are compatible.
2913 if (!QStore->isUnordered() || !PStore->isUnordered())
2914 return false;
2915
2916 // Check that sinking the store won't cause program behavior changes. Sinking
2917 // the store out of the Q blocks won't change any behavior as we're sinking
2918 // from a block to its unconditional successor. But we're moving a store from
2919 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2920 // So we need to check that there are no aliasing loads or stores in
2921 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2922 // operations between PStore and the end of its parent block.
2923 //
2924 // The ideal way to do this is to query AliasAnalysis, but we don't
2925 // preserve AA currently so that is dangerous. Be super safe and just
2926 // check there are no other memory operations at all.
2927 for (auto &I : *QFB->getSinglePredecessor())
2928 if (I.mayReadOrWriteMemory())
2929 return false;
2930 for (auto &I : *QFB)
2931 if (&I != QStore && I.mayReadOrWriteMemory())
2932 return false;
2933 if (QTB)
2934 for (auto &I : *QTB)
2935 if (&I != QStore && I.mayReadOrWriteMemory())
2936 return false;
2937 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2938 I != E; ++I)
2939 if (&*I != PStore && I->mayReadOrWriteMemory())
2940 return false;
2941
2942 // OK, we're going to sink the stores to PostBB. The store has to be
2943 // conditional though, so first create the predicate.
2944 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2945 ->getCondition();
2946 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2947 ->getCondition();
2948
2949 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2950 PStore->getParent());
2951 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2952 QStore->getParent(), PPHI);
2953
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002954 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2955
James Molloy4de84dd2015-11-04 15:28:04 +00002956 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2957 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2958
2959 if (InvertPCond)
2960 PPred = QB.CreateNot(PPred);
2961 if (InvertQCond)
2962 QPred = QB.CreateNot(QPred);
2963 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2964
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002965 auto *T =
2966 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002967 QB.SetInsertPoint(T);
2968 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2969 AAMDNodes AAMD;
2970 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2971 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2972 SI->setAAMetadata(AAMD);
Alexey Bataev978e2e42017-08-29 20:06:24 +00002973 unsigned PAlignment = PStore->getAlignment();
2974 unsigned QAlignment = QStore->getAlignment();
2975 unsigned TypeAlignment =
2976 DL.getABITypeAlignment(SI->getValueOperand()->getType());
2977 unsigned MinAlignment;
2978 unsigned MaxAlignment;
2979 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
2980 // Choose the minimum alignment. If we could prove both stores execute, we
2981 // could use biggest one. In this case, though, we only know that one of the
2982 // stores executes. And we don't know it's safe to take the alignment from a
2983 // store that doesn't execute.
2984 if (MinAlignment != 0) {
2985 // Choose the minimum of all non-zero alignments.
2986 SI->setAlignment(MinAlignment);
2987 } else if (MaxAlignment != 0) {
2988 // Choose the minimal alignment between the non-zero alignment and the ABI
2989 // default alignment for the type of the stored value.
2990 SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
2991 } else {
2992 // If both alignments are zero, use ABI default alignment for the type of
2993 // the stored value.
2994 SI->setAlignment(TypeAlignment);
2995 }
James Molloy4de84dd2015-11-04 15:28:04 +00002996
2997 QStore->eraseFromParent();
2998 PStore->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00002999
James Molloy4de84dd2015-11-04 15:28:04 +00003000 return true;
3001}
3002
Alexey Bataev978e2e42017-08-29 20:06:24 +00003003static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3004 const DataLayout &DL) {
James Molloy4de84dd2015-11-04 15:28:04 +00003005 // The intention here is to find diamonds or triangles (see below) where each
3006 // conditional block contains a store to the same address. Both of these
3007 // stores are conditional, so they can't be unconditionally sunk. But it may
3008 // be profitable to speculatively sink the stores into one merged store at the
3009 // end, and predicate the merged store on the union of the two conditions of
3010 // PBI and QBI.
3011 //
3012 // This can reduce the number of stores executed if both of the conditions are
3013 // true, and can allow the blocks to become small enough to be if-converted.
3014 // This optimization will also chain, so that ladders of test-and-set
3015 // sequences can be if-converted away.
3016 //
3017 // We only deal with simple diamonds or triangles:
3018 //
3019 // PBI or PBI or a combination of the two
3020 // / \ | \
3021 // PTB PFB | PFB
3022 // \ / | /
3023 // QBI QBI
3024 // / \ | \
3025 // QTB QFB | QFB
3026 // \ / | /
3027 // PostBB PostBB
3028 //
3029 // We model triangles as a type of diamond with a nullptr "true" block.
3030 // Triangles are canonicalized so that the fallthrough edge is represented by
3031 // a true condition, as in the diagram above.
James Molloy4de84dd2015-11-04 15:28:04 +00003032 BasicBlock *PTB = PBI->getSuccessor(0);
3033 BasicBlock *PFB = PBI->getSuccessor(1);
3034 BasicBlock *QTB = QBI->getSuccessor(0);
3035 BasicBlock *QFB = QBI->getSuccessor(1);
3036 BasicBlock *PostBB = QFB->getSingleSuccessor();
3037
Craig Topper7af07882017-04-21 15:53:42 +00003038 // Make sure we have a good guess for PostBB. If QTB's only successor is
3039 // QFB, then QFB is a better PostBB.
3040 if (QTB->getSingleSuccessor() == QFB)
3041 PostBB = QFB;
3042
3043 // If we couldn't find a good PostBB, stop.
3044 if (!PostBB)
3045 return false;
3046
James Molloy4de84dd2015-11-04 15:28:04 +00003047 bool InvertPCond = false, InvertQCond = false;
3048 // Canonicalize fallthroughs to the true branches.
3049 if (PFB == QBI->getParent()) {
3050 std::swap(PFB, PTB);
3051 InvertPCond = true;
3052 }
3053 if (QFB == PostBB) {
3054 std::swap(QFB, QTB);
3055 InvertQCond = true;
3056 }
3057
3058 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3059 // and QFB may not. Model fallthroughs as a nullptr block.
3060 if (PTB == QBI->getParent())
3061 PTB = nullptr;
3062 if (QTB == PostBB)
3063 QTB = nullptr;
3064
3065 // Legality bailouts. We must have at least the non-fallthrough blocks and
3066 // the post-dominating block, and the non-fallthroughs must only have one
3067 // predecessor.
3068 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003069 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
James Molloy4de84dd2015-11-04 15:28:04 +00003070 };
Craig Topper7af07882017-04-21 15:53:42 +00003071 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
James Molloy4de84dd2015-11-04 15:28:04 +00003072 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3073 return false;
3074 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3075 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3076 return false;
Craig Topperc2280682017-04-17 22:13:00 +00003077 if (!PostBB->hasNUses(2) || !QBI->getParent()->hasNUses(2))
James Molloy4de84dd2015-11-04 15:28:04 +00003078 return false;
3079
3080 // OK, this is a sequence of two diamonds or triangles.
3081 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
Dehao Chenf6c00832016-05-18 19:44:21 +00003082 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
James Molloy4de84dd2015-11-04 15:28:04 +00003083 for (auto *BB : {PTB, PFB}) {
3084 if (!BB)
3085 continue;
3086 for (auto &I : *BB)
3087 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3088 PStoreAddresses.insert(SI->getPointerOperand());
3089 }
3090 for (auto *BB : {QTB, QFB}) {
3091 if (!BB)
3092 continue;
3093 for (auto &I : *BB)
3094 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3095 QStoreAddresses.insert(SI->getPointerOperand());
3096 }
Dehao Chenf6c00832016-05-18 19:44:21 +00003097
James Molloy4de84dd2015-11-04 15:28:04 +00003098 set_intersect(PStoreAddresses, QStoreAddresses);
3099 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3100 // clear what it contains.
3101 auto &CommonAddresses = PStoreAddresses;
3102
3103 bool Changed = false;
3104 for (auto *Address : CommonAddresses)
3105 Changed |= mergeConditionalStoreToAddress(
Alexey Bataev978e2e42017-08-29 20:06:24 +00003106 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
James Molloy4de84dd2015-11-04 15:28:04 +00003107 return Changed;
3108}
3109
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003110/// If we have a conditional branch as a predecessor of another block,
3111/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00003112/// that PBI and BI are both conditional branches, and BI is in one of the
3113/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00003114static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3115 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00003116 assert(PBI->isConditional() && BI->isConditional());
3117 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00003118
Chris Lattner9aada1d2008-07-13 21:53:26 +00003119 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00003120 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00003121 // this conditional branch redundant.
3122 if (PBI->getCondition() == BI->getCondition() &&
3123 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3124 // Okay, the outcome of this conditional branch is statically
3125 // knowable. If this block had a single pred, handle specially.
3126 if (BB->getSinglePredecessor()) {
3127 // Turn this into a branch on constant.
3128 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003129 BI->setCondition(
3130 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3131 return true; // Nuke the branch on constant.
Chris Lattner9aada1d2008-07-13 21:53:26 +00003132 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003133
Chris Lattner9aada1d2008-07-13 21:53:26 +00003134 // Otherwise, if there are multiple predecessors, insert a PHI that merges
3135 // in the constant and simplify the block result. Subsequent passes of
3136 // simplifycfg will thread the block.
3137 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00003138 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003139 PHINode *NewPN = PHINode::Create(
3140 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3141 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00003142 // Okay, we're going to insert the PHI node. Since PBI is not the only
3143 // predecessor, compute the PHI'd conditional value for all of the preds.
3144 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00003145 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00003146 BasicBlock *P = *PI;
Dehao Chenf6c00832016-05-18 19:44:21 +00003147 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3148 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00003149 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3150 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003151 NewPN->addIncoming(
3152 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3153 P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003154 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00003155 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003156 }
Gabor Greif8629f122010-07-12 10:59:23 +00003157 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003158
Chris Lattner9aada1d2008-07-13 21:53:26 +00003159 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003160 return true;
3161 }
3162 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003163
Philip Reamesb42db212015-10-14 22:46:19 +00003164 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3165 if (CE->canTrap())
3166 return false;
3167
James Molloy4de84dd2015-11-04 15:28:04 +00003168 // If both branches are conditional and both contain stores to the same
3169 // address, remove the stores from the conditionals and create a conditional
3170 // merged store at the end.
Alexey Bataev978e2e42017-08-29 20:06:24 +00003171 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
James Molloy4de84dd2015-11-04 15:28:04 +00003172 return true;
3173
Chris Lattner9aada1d2008-07-13 21:53:26 +00003174 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00003175 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00003176 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00003177 BasicBlock::iterator BBI = BB->begin();
3178 // Ignore dbg intrinsics.
3179 while (isa<DbgInfoIntrinsic>(BBI))
3180 ++BBI;
3181 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00003182 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00003183
Chris Lattner834ab4e2008-07-13 22:04:41 +00003184 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00003185 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3186 PBIOp = 0;
3187 BIOp = 0;
3188 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3189 PBIOp = 0;
3190 BIOp = 1;
3191 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3192 PBIOp = 1;
3193 BIOp = 0;
3194 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3195 PBIOp = 1;
3196 BIOp = 1;
3197 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003198 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00003199 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003200
Chris Lattner834ab4e2008-07-13 22:04:41 +00003201 // Check to make sure that the other destination of this branch
3202 // isn't BB itself. If so, this is an infinite loop that will
3203 // keep getting unwound.
3204 if (PBI->getSuccessor(PBIOp) == BB)
3205 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003206
3207 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00003208 // insertion of a large number of select instructions. For targets
3209 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003210
Sanjay Patela932da82014-07-07 21:19:00 +00003211 // Also do not perform this transformation if any phi node in the common
3212 // destination block can trap when reached by BB or PBB (PR17073). In that
3213 // case, it would be unsafe to hoist the operation into a select instruction.
3214
3215 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003216 unsigned NumPhis = 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00003217 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3218 ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003219 if (NumPhis > 2) // Disable this xform.
3220 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003221
Sanjay Patela932da82014-07-07 21:19:00 +00003222 PHINode *PN = cast<PHINode>(II);
3223 Value *BIV = PN->getIncomingValueForBlock(BB);
3224 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3225 if (CE->canTrap())
3226 return false;
3227
3228 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3229 Value *PBIV = PN->getIncomingValue(PBBIdx);
3230 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3231 if (CE->canTrap())
3232 return false;
3233 }
3234
Chris Lattner834ab4e2008-07-13 22:04:41 +00003235 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00003236 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003237
David Greene725c7c32010-01-05 01:26:52 +00003238 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00003239 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003240
Chris Lattner80b03a12008-07-13 22:23:11 +00003241 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3242 // branch in it, where one edge (OtherDest) goes back to itself but the other
3243 // exits. We don't *know* that the program avoids the infinite loop
3244 // (even though that seems likely). If we do this xform naively, we'll end up
3245 // recursively unpeeling the loop. Since we know that (after the xform is
3246 // done) that the block *is* infinite if reached, we just make it an obviously
3247 // infinite loop with no cond branch.
3248 if (OtherDest == BB) {
3249 // Insert it at the end of the function, because it's either code,
3250 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00003251 BasicBlock *InfLoopBlock =
3252 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00003253 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3254 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003255 }
3256
David Greene725c7c32010-01-05 01:26:52 +00003257 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00003258
Chris Lattner834ab4e2008-07-13 22:04:41 +00003259 // BI may have other predecessors. Because of this, we leave
3260 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003261
Chris Lattner834ab4e2008-07-13 22:04:41 +00003262 // Make sure we get to CommonDest on True&True directions.
3263 Value *PBICond = PBI->getCondition();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00003264 IRBuilder<NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003265 if (PBIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003266 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003267
Chris Lattner834ab4e2008-07-13 22:04:41 +00003268 Value *BICond = BI->getCondition();
3269 if (BIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003270 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003271
Chris Lattner834ab4e2008-07-13 22:04:41 +00003272 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00003273 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00003274
Chris Lattner834ab4e2008-07-13 22:04:41 +00003275 // Modify PBI to branch on the new condition to the new dests.
3276 PBI->setCondition(Cond);
3277 PBI->setSuccessor(0, CommonDest);
3278 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003279
Manman Ren2d4c10f2012-09-17 21:30:40 +00003280 // Update branch weight for PBI.
3281 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenb76e5d92016-05-10 23:07:19 +00003282 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
Dehao Chenf16376b2016-05-18 22:41:03 +00003283 bool HasWeights =
3284 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3285 SuccTrueWeight, SuccFalseWeight);
Dehao Chenb76e5d92016-05-10 23:07:19 +00003286 if (HasWeights) {
Dehao Chenb76e5d92016-05-10 23:07:19 +00003287 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3288 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3289 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3290 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
Manman Ren2d4c10f2012-09-17 21:30:40 +00003291 // The weight to CommonDest should be PredCommon * SuccTotal +
3292 // PredOther * SuccCommon.
3293 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00003294 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3295 PredOther * SuccCommon,
3296 PredOther * SuccOther};
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003297 // Halve the weights if any of them cannot fit in an uint32_t
Manman Ren2d4c10f2012-09-17 21:30:40 +00003298 FitWeights(NewWeights);
3299
Manman Ren2d4c10f2012-09-17 21:30:40 +00003300 PBI->setMetadata(LLVMContext::MD_prof,
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003301 MDBuilder(BI->getContext())
3302 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00003303 }
3304
Chris Lattner834ab4e2008-07-13 22:04:41 +00003305 // OtherDest may have phi nodes. If so, add an entry from PBI's
3306 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003307 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003308
Chris Lattner834ab4e2008-07-13 22:04:41 +00003309 // We know that the CommonDest already had an edge from PBI to
3310 // it. If it has PHIs though, the PHIs may have different
3311 // entries for BB and PBI's BB. If so, insert a select to make
3312 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003313 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00003314 for (BasicBlock::iterator II = CommonDest->begin();
3315 (PN = dyn_cast<PHINode>(II)); ++II) {
3316 Value *BIV = PN->getIncomingValueForBlock(BB);
3317 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3318 Value *PBIV = PN->getIncomingValue(PBBIdx);
3319 if (BIV != PBIV) {
3320 // Insert a select in PBI to pick the right value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003321 SelectInst *NV = cast<SelectInst>(
3322 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00003323 PN->setIncomingValue(PBBIdx, NV);
Sanjay Patel1cb62412016-05-06 18:07:46 +00003324 // Although the select has the same condition as PBI, the original branch
3325 // weights for PBI do not apply to the new select because the select's
3326 // 'logical' edges are incoming edges of the phi that is eliminated, not
3327 // the outgoing edges of PBI.
Dehao Chenf16376b2016-05-18 22:41:03 +00003328 if (HasWeights) {
Sanjay Patel1cb62412016-05-06 18:07:46 +00003329 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3330 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3331 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3332 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3333 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3334 // The weight to PredOtherDest should be PredOther * SuccCommon.
3335 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3336 PredOther * SuccCommon};
3337
3338 FitWeights(NewWeights);
3339
3340 NV->setMetadata(LLVMContext::MD_prof,
3341 MDBuilder(BI->getContext())
3342 .createBranchWeights(NewWeights[0], NewWeights[1]));
3343 }
Chris Lattner9aada1d2008-07-13 21:53:26 +00003344 }
3345 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003346
David Greene725c7c32010-01-05 01:26:52 +00003347 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3348 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003349
Chris Lattner834ab4e2008-07-13 22:04:41 +00003350 // This basic block is probably dead. We know it has at least
3351 // one fewer predecessor.
3352 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00003353}
3354
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003355// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3356// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00003357// Takes care of updating the successors and removing the old terminator.
3358// Also makes sure not to introduce new successors by assuming that edges to
3359// non-successor TrueBBs and FalseBBs aren't reachable.
3360static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00003361 BasicBlock *TrueBB, BasicBlock *FalseBB,
3362 uint32_t TrueWeight,
Dehao Chenf6c00832016-05-18 19:44:21 +00003363 uint32_t FalseWeight) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003364 // Remove any superfluous successor edges from the CFG.
3365 // First, figure out which successors to preserve.
3366 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3367 // successor.
3368 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00003369 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003370
3371 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00003372 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003373 // Make sure only to keep exactly one copy of each edge.
3374 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00003375 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003376 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00003377 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003378 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00003379 Succ->removePredecessor(OldTerm->getParent(),
3380 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00003381 }
3382
Devang Patel2c2ea222011-05-18 18:43:31 +00003383 IRBuilder<> Builder(OldTerm);
3384 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3385
Frits van Bommel8e158492011-01-11 12:52:11 +00003386 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00003387 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003388 if (TrueBB == FalseBB)
3389 // We were only looking for one successor, and it was present.
3390 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00003391 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00003392 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00003393 // We found both of the successors we were looking for.
3394 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00003395 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3396 if (TrueWeight != FalseWeight)
3397 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00003398 MDBuilder(OldTerm->getContext())
3399 .createBranchWeights(TrueWeight, FalseWeight));
Manman Ren774246a2012-09-17 22:28:55 +00003400 }
Frits van Bommel8e158492011-01-11 12:52:11 +00003401 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3402 // Neither of the selected blocks were successors, so this
3403 // terminator must be unreachable.
3404 new UnreachableInst(OldTerm->getContext(), OldTerm);
3405 } else {
3406 // One of the selected values was a successor, but the other wasn't.
3407 // Insert an unconditional branch to the one that was found;
3408 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00003409 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00003410 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003411 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003412 else
3413 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003414 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003415 }
3416
3417 EraseTerminatorInstAndDCECond(OldTerm);
3418 return true;
3419}
3420
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003421// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00003422// (switch (select cond, X, Y)) on constant X, Y
3423// with a branch - conditional if X and Y lead to distinct BBs,
3424// unconditional otherwise.
3425static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3426 // Check for constant integer values in the select.
3427 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3428 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3429 if (!TrueVal || !FalseVal)
3430 return false;
3431
3432 // Find the relevant condition and destinations.
3433 Value *Condition = Select->getCondition();
Chandler Carruth927d8e62017-04-12 07:27:28 +00003434 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3435 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00003436
Manman Ren774246a2012-09-17 22:28:55 +00003437 // Get weight for TrueBB and FalseBB.
3438 uint32_t TrueWeight = 0, FalseWeight = 0;
3439 SmallVector<uint64_t, 8> Weights;
3440 bool HasWeights = HasBranchWeights(SI);
3441 if (HasWeights) {
3442 GetBranchWeights(SI, Weights);
3443 if (Weights.size() == 1 + SI->getNumCases()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003444 TrueWeight =
Chandler Carruth927d8e62017-04-12 07:27:28 +00003445 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
Dehao Chenf6c00832016-05-18 19:44:21 +00003446 FalseWeight =
Chandler Carruth927d8e62017-04-12 07:27:28 +00003447 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
Manman Ren774246a2012-09-17 22:28:55 +00003448 }
3449 }
3450
Frits van Bommel8ae07992011-02-28 09:44:07 +00003451 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003452 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3453 FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003454}
3455
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003456// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003457// (indirectbr (select cond, blockaddress(@fn, BlockA),
3458// blockaddress(@fn, BlockB)))
3459// with
3460// (br cond, BlockA, BlockB).
3461static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3462 // Check that both operands of the select are block addresses.
3463 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3464 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3465 if (!TBA || !FBA)
3466 return false;
3467
3468 // Extract the actual blocks.
3469 BasicBlock *TrueBB = TBA->getBasicBlock();
3470 BasicBlock *FalseBB = FBA->getBasicBlock();
3471
Frits van Bommel8e158492011-01-11 12:52:11 +00003472 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003473 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3474 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003475}
3476
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003477/// This is called when we find an icmp instruction
3478/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003479/// block that ends with an uncond branch. We are looking for a very specific
3480/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3481/// this case, we merge the first two "or's of icmp" into a switch, but then the
3482/// default value goes to an uncond block with a seteq in it, we get something
3483/// like:
3484///
3485/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3486/// DEFAULT:
3487/// %tmp = icmp eq i8 %A, 92
3488/// br label %end
3489/// end:
3490/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003491///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003492/// We prefer to split the edge to 'end' so that there is a true/false entry to
3493/// the PHI, merging the third icmp into the switch.
Sanjay Patel4c33d522017-10-04 20:26:25 +00003494static bool tryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003495 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
Sanjay Patel4c33d522017-10-04 20:26:25 +00003496 const TargetTransformInfo &TTI, const SimplifyCFGOptions &Options) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003497 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003498
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003499 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3500 // complex.
Dehao Chenf6c00832016-05-18 19:44:21 +00003501 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3502 return false;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003503
3504 Value *V = ICI->getOperand(0);
3505 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003506
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003507 // The pattern we're looking for is where our only predecessor is a switch on
3508 // 'V' and this block is the default case for the switch. In this case we can
3509 // fold the compared value into the switch to simplify things.
3510 BasicBlock *Pred = BB->getSinglePredecessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00003511 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3512 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003513
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003514 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3515 if (SI->getCondition() != V)
3516 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003517
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003518 // If BB is reachable on a non-default case, then we simply know the value of
3519 // V in this block. Substitute it and constant fold the icmp instruction
3520 // away.
3521 if (SI->getDefaultDest() != BB) {
3522 ConstantInt *VVal = SI->findCaseDest(BB);
3523 assert(VVal && "Should have a unique destination value");
3524 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003525
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003526 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003527 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003528 ICI->eraseFromParent();
3529 }
3530 // BB is now empty, so it is likely to simplify away.
Sanjay Patel4c33d522017-10-04 20:26:25 +00003531 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003532 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003533
Chris Lattner62cc76e2010-12-13 03:43:57 +00003534 // Ok, the block is reachable from the default dest. If the constant we're
3535 // comparing exists in one of the other edges, then we can constant fold ICI
3536 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003537 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003538 Value *V;
3539 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3540 V = ConstantInt::getFalse(BB->getContext());
3541 else
3542 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003543
Chris Lattner62cc76e2010-12-13 03:43:57 +00003544 ICI->replaceAllUsesWith(V);
3545 ICI->eraseFromParent();
3546 // BB is now empty, so it is likely to simplify away.
Sanjay Patel4c33d522017-10-04 20:26:25 +00003547 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003548 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003549
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003550 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3551 // the block.
3552 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003553 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003554 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003555 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3556 return false;
3557
3558 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3559 // true in the PHI.
3560 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Dehao Chenf6c00832016-05-18 19:44:21 +00003561 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003562
3563 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3564 std::swap(DefaultCst, NewCst);
3565
3566 // Replace ICI (which is used by the PHI for the default value) with true or
3567 // false depending on if it is EQ or NE.
3568 ICI->replaceAllUsesWith(DefaultCst);
3569 ICI->eraseFromParent();
3570
3571 // Okay, the switch goes to this block on a default value. Add an edge from
3572 // the switch to the merge point on the compared value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003573 BasicBlock *NewBB =
3574 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003575 SmallVector<uint64_t, 8> Weights;
3576 bool HasWeights = HasBranchWeights(SI);
3577 if (HasWeights) {
3578 GetBranchWeights(SI, Weights);
3579 if (Weights.size() == 1 + SI->getNumCases()) {
3580 // Split weight for default case to case for "Cst".
Dehao Chenf6c00832016-05-18 19:44:21 +00003581 Weights[0] = (Weights[0] + 1) >> 1;
Manman Rence48ea72012-09-17 23:07:43 +00003582 Weights.push_back(Weights[0]);
3583
3584 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
Dehao Chenf6c00832016-05-18 19:44:21 +00003585 SI->setMetadata(
3586 LLVMContext::MD_prof,
3587 MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
Manman Rence48ea72012-09-17 23:07:43 +00003588 }
3589 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003590 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003591
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003592 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003593 Builder.SetInsertPoint(NewBB);
3594 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3595 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003596 PHIUse->addIncoming(NewCst, NewBB);
3597 return true;
3598}
3599
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003600/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003601/// Check to see if it is branching on an or/and chain of icmp instructions, and
3602/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003603static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3604 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003605 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +00003606 if (!Cond)
3607 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003608
Chris Lattnera69c4432010-12-13 05:03:41 +00003609 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3610 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3611 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003612
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003613 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003614 ConstantComparesGatherer ConstantCompare(Cond, DL);
3615 // Unpack the result
Dehao Chenf6c00832016-05-18 19:44:21 +00003616 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
Mehdi Aminiffd01002014-11-20 22:40:25 +00003617 Value *CompVal = ConstantCompare.CompValue;
3618 unsigned UsedICmps = ConstantCompare.UsedICmps;
3619 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003620
Chris Lattnera69c4432010-12-13 05:03:41 +00003621 // If we didn't have a multiply compared value, fail.
Dehao Chenf6c00832016-05-18 19:44:21 +00003622 if (!CompVal)
3623 return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003624
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003625 // Avoid turning single icmps into a switch.
3626 if (UsedICmps <= 1)
3627 return false;
3628
Mehdi Aminiffd01002014-11-20 22:40:25 +00003629 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3630
Chris Lattnera69c4432010-12-13 05:03:41 +00003631 // There might be duplicate constants in the list, which the switch
3632 // instruction can't handle, remove them now.
3633 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3634 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003635
Chris Lattnera69c4432010-12-13 05:03:41 +00003636 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003637 // transformation. A switch with one value is just a conditional branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00003638 if (ExtraCase && Values.size() < 2)
3639 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003640
Andrew Trick3051aa12012-08-29 21:46:38 +00003641 // TODO: Preserve branch weight metadata, similarly to how
3642 // FoldValueComparisonIntoPredecessors preserves it.
3643
Chris Lattnera69c4432010-12-13 05:03:41 +00003644 // Figure out which block is which destination.
3645 BasicBlock *DefaultBB = BI->getSuccessor(1);
Dehao Chenf6c00832016-05-18 19:44:21 +00003646 BasicBlock *EdgeBB = BI->getSuccessor(0);
3647 if (!TrueWhenEqual)
3648 std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003649
Chris Lattnera69c4432010-12-13 05:03:41 +00003650 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003651
Chris Lattnerd7beca32010-12-14 06:17:25 +00003652 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Dehao Chenf6c00832016-05-18 19:44:21 +00003653 << " cases into SWITCH. BB is:\n"
3654 << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003655
Chris Lattnera69c4432010-12-13 05:03:41 +00003656 // If there are any extra values that couldn't be folded into the switch
3657 // then we evaluate them with an explicit branch first. Split the block
3658 // right before the condbr to handle it.
3659 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003660 BasicBlock *NewBB =
3661 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003662 // Remove the uncond branch added to the old block.
3663 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003664 Builder.SetInsertPoint(OldTI);
3665
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003666 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003667 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003668 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003669 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003670
Chris Lattnera69c4432010-12-13 05:03:41 +00003671 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003672
Chris Lattnercb570f82010-12-13 05:34:18 +00003673 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3674 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003675 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003676
Chris Lattnerd7beca32010-12-14 06:17:25 +00003677 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
Dehao Chenf6c00832016-05-18 19:44:21 +00003678 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003679 BB = NewBB;
3680 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003681
3682 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003683 // Convert pointer to int before we switch.
3684 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003685 CompVal = Builder.CreatePtrToInt(
3686 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003687 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003688
Chris Lattnera69c4432010-12-13 05:03:41 +00003689 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003690 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003691
Chris Lattnera69c4432010-12-13 05:03:41 +00003692 // Add all of the 'cases' to the switch instruction.
3693 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3694 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003695
Chris Lattnera69c4432010-12-13 05:03:41 +00003696 // We added edges from PI to the EdgeBB. As such, if there were any
3697 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3698 // the number of edges added.
Dehao Chenf6c00832016-05-18 19:44:21 +00003699 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003700 PHINode *PN = cast<PHINode>(BBI);
3701 Value *InVal = PN->getIncomingValueForBlock(BB);
Dehao Chenf6c00832016-05-18 19:44:21 +00003702 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
Chris Lattnera69c4432010-12-13 05:03:41 +00003703 PN->addIncoming(InVal, BB);
3704 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003705
Chris Lattnera69c4432010-12-13 05:03:41 +00003706 // Erase the old branch instruction.
3707 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003708
Chris Lattnerd7beca32010-12-14 06:17:25 +00003709 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003710 return true;
3711}
3712
Duncan Sands29192d02011-09-05 12:57:57 +00003713bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003714 if (isa<PHINode>(RI->getValue()))
3715 return SimplifyCommonResume(RI);
3716 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3717 RI->getValue() == RI->getParent()->getFirstNonPHI())
3718 // The resume must unwind the exception that caused control to branch here.
3719 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003720
3721 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003722}
3723
3724// Simplify resume that is shared by several landing pads (phi of landing pad).
3725bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3726 BasicBlock *BB = RI->getParent();
3727
3728 // Check that there are no other instructions except for debug intrinsics
3729 // between the phi of landing pads (RI->getValue()) and resume instruction.
3730 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
Dehao Chenf6c00832016-05-18 19:44:21 +00003731 E = RI->getIterator();
Chen Li1689c2f2016-01-10 05:48:01 +00003732 while (++I != E)
3733 if (!isa<DbgInfoIntrinsic>(I))
3734 return false;
3735
Mandeep Singh Grang799a2ed2017-04-24 19:20:45 +00003736 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
Chen Li1689c2f2016-01-10 05:48:01 +00003737 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3738
3739 // Check incoming blocks to see if any of them are trivial.
Dehao Chenf6c00832016-05-18 19:44:21 +00003740 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3741 Idx++) {
Chen Li1689c2f2016-01-10 05:48:01 +00003742 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3743 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3744
3745 // If the block has other successors, we can not delete it because
3746 // it has other dependents.
3747 if (IncomingBB->getUniqueSuccessor() != BB)
3748 continue;
3749
Dehao Chenf6c00832016-05-18 19:44:21 +00003750 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003751 // Not the landing pad that caused the control to branch here.
3752 if (IncomingValue != LandingPad)
3753 continue;
3754
3755 bool isTrivial = true;
3756
3757 I = IncomingBB->getFirstNonPHI()->getIterator();
3758 E = IncomingBB->getTerminator()->getIterator();
3759 while (++I != E)
3760 if (!isa<DbgInfoIntrinsic>(I)) {
3761 isTrivial = false;
3762 break;
3763 }
3764
3765 if (isTrivial)
3766 TrivialUnwindBlocks.insert(IncomingBB);
3767 }
3768
3769 // If no trivial unwind blocks, don't do any simplifications.
Dehao Chenf6c00832016-05-18 19:44:21 +00003770 if (TrivialUnwindBlocks.empty())
3771 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003772
3773 // Turn all invokes that unwind here into calls.
3774 for (auto *TrivialBB : TrivialUnwindBlocks) {
3775 // Blocks that will be simplified should be removed from the phi node.
3776 // Note there could be multiple edges to the resume block, and we need
3777 // to remove them all.
3778 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3779 BB->removePredecessor(TrivialBB, true);
3780
3781 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3782 PI != PE;) {
3783 BasicBlock *Pred = *PI++;
3784 removeUnwindEdge(Pred);
3785 }
3786
3787 // In each SimplifyCFG run, only the current processed block can be erased.
3788 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3789 // of erasing TrivialBB, we only remove the branch to the common resume
3790 // block so that we can later erase the resume block since it has no
3791 // predecessors.
3792 TrivialBB->getTerminator()->eraseFromParent();
3793 new UnreachableInst(RI->getContext(), TrivialBB);
3794 }
3795
3796 // Delete the resume block if all its predecessors have been removed.
3797 if (pred_empty(BB))
3798 BB->eraseFromParent();
3799
3800 return !TrivialUnwindBlocks.empty();
3801}
3802
3803// Simplify resume that is only used by a single (non-phi) landing pad.
3804bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003805 BasicBlock *BB = RI->getParent();
3806 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Dehao Chenf6c00832016-05-18 19:44:21 +00003807 assert(RI->getValue() == LPInst &&
3808 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003809
Chen Li7009cd32015-10-23 21:13:01 +00003810 // Check that there are no other instructions except for debug intrinsics.
3811 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003812 while (++I != E)
3813 if (!isa<DbgInfoIntrinsic>(I))
3814 return false;
3815
Chen Lic6e28782015-10-22 20:48:38 +00003816 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003817 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3818 BasicBlock *Pred = *PI++;
3819 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003820 }
3821
Chen Li7009cd32015-10-23 21:13:01 +00003822 // The landingpad is now unreachable. Zap it.
3823 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003824 if (LoopHeaders)
3825 LoopHeaders->erase(BB);
Chen Li7009cd32015-10-23 21:13:01 +00003826 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003827}
3828
David Majnemer1efa23d2016-02-20 01:07:45 +00003829static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003830 // If this is a trivial cleanup pad that executes no instructions, it can be
3831 // eliminated. If the cleanup pad continues to the caller, any predecessor
3832 // that is an EH pad will be updated to continue to the caller and any
3833 // predecessor that terminates with an invoke instruction will have its invoke
3834 // instruction converted to a call instruction. If the cleanup pad being
3835 // simplified does not continue to the caller, each predecessor will be
3836 // updated to continue to the unwind destination of the cleanup pad being
3837 // simplified.
3838 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003839 CleanupPadInst *CPInst = RI->getCleanupPad();
3840 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003841 // This isn't an empty cleanup.
3842 return false;
3843
David Majnemer2482e1c2016-06-04 23:50:03 +00003844 // We cannot kill the pad if it has multiple uses. This typically arises
3845 // from unreachable basic blocks.
3846 if (!CPInst->hasOneUse())
3847 return false;
3848
David Majnemer9f92f4c2016-05-21 05:12:32 +00003849 // Check that there are no other instructions except for benign intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003850 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
David Majnemer9f92f4c2016-05-21 05:12:32 +00003851 while (++I != E) {
3852 auto *II = dyn_cast<IntrinsicInst>(I);
3853 if (!II)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003854 return false;
3855
David Majnemer9f92f4c2016-05-21 05:12:32 +00003856 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3857 switch (IntrinsicID) {
3858 case Intrinsic::dbg_declare:
3859 case Intrinsic::dbg_value:
3860 case Intrinsic::lifetime_end:
3861 break;
3862 default:
3863 return false;
3864 }
3865 }
3866
David Majnemer8a1c45d2015-12-12 05:38:55 +00003867 // If the cleanup return we are simplifying unwinds to the caller, this will
3868 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003869 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003870 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003871
3872 // We're about to remove BB from the control flow. Before we do, sink any
3873 // PHINodes into the unwind destination. Doing this before changing the
3874 // control flow avoids some potentially slow checks, since we can currently
3875 // be certain that UnwindDest and BB have no common predecessors (since they
3876 // are both EH pads).
3877 if (UnwindDest) {
3878 // First, go through the PHI nodes in UnwindDest and update any nodes that
3879 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003880 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003881 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003882 I != IE; ++I) {
3883 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003884
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003885 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003886 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003887 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003888 // This PHI node has an incoming value that corresponds to a control
3889 // path through the cleanup pad we are removing. If the incoming
3890 // value is in the cleanup pad, it must be a PHINode (because we
3891 // verified above that the block is otherwise empty). Otherwise, the
3892 // value is either a constant or a value that dominates the cleanup
3893 // pad being removed.
3894 //
3895 // Because BB and UnwindDest are both EH pads, all of their
3896 // predecessors must unwind to these blocks, and since no instruction
3897 // can have multiple unwind destinations, there will be no overlap in
3898 // incoming blocks between SrcPN and DestPN.
3899 Value *SrcVal = DestPN->getIncomingValue(Idx);
3900 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3901
3902 // Remove the entry for the block we are deleting.
3903 DestPN->removeIncomingValue(Idx, false);
3904
3905 if (SrcPN && SrcPN->getParent() == BB) {
3906 // If the incoming value was a PHI node in the cleanup pad we are
3907 // removing, we need to merge that PHI node's incoming values into
3908 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003909 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Dehao Chenf6c00832016-05-18 19:44:21 +00003910 SrcIdx != SrcE; ++SrcIdx) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003911 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3912 SrcPN->getIncomingBlock(SrcIdx));
3913 }
3914 } else {
3915 // Otherwise, the incoming value came from above BB and
3916 // so we can just reuse it. We must associate all of BB's
3917 // predecessors with this value.
3918 for (auto *pred : predecessors(BB)) {
3919 DestPN->addIncoming(SrcVal, pred);
3920 }
3921 }
3922 }
3923
3924 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003925 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003926 for (BasicBlock::iterator I = BB->begin(),
3927 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003928 I != IE;) {
3929 // The iterator must be incremented here because the instructions are
3930 // being moved to another block.
3931 PHINode *PN = cast<PHINode>(I++);
3932 if (PN->use_empty())
3933 // If the PHI node has no uses, just leave it. It will be erased
3934 // when we erase BB below.
3935 continue;
3936
3937 // Otherwise, sink this PHI node into UnwindDest.
3938 // Any predecessors to UnwindDest which are not already represented
3939 // must be back edges which inherit the value from the path through
3940 // BB. In this case, the PHI value must reference itself.
3941 for (auto *pred : predecessors(UnwindDest))
3942 if (pred != BB)
3943 PN->addIncoming(PN, pred);
3944 PN->moveBefore(InsertPt);
3945 }
3946 }
3947
3948 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3949 // The iterator must be updated here because we are removing this pred.
3950 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003951 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003952 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003953 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003954 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003955 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003956 }
3957 }
3958
3959 // The cleanup pad is now unreachable. Zap it.
3960 BB->eraseFromParent();
3961 return true;
3962}
3963
David Majnemer1efa23d2016-02-20 01:07:45 +00003964// Try to merge two cleanuppads together.
3965static bool mergeCleanupPad(CleanupReturnInst *RI) {
3966 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3967 // with.
3968 BasicBlock *UnwindDest = RI->getUnwindDest();
3969 if (!UnwindDest)
3970 return false;
3971
3972 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3973 // be safe to merge without code duplication.
3974 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3975 return false;
3976
3977 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3978 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3979 if (!SuccessorCleanupPad)
3980 return false;
3981
3982 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3983 // Replace any uses of the successor cleanupad with the predecessor pad
3984 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3985 // funclet bundle operands.
3986 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3987 // Remove the old cleanuppad.
3988 SuccessorCleanupPad->eraseFromParent();
3989 // Now, we simply replace the cleanupret with a branch to the unwind
3990 // destination.
3991 BranchInst::Create(UnwindDest, RI->getParent());
3992 RI->eraseFromParent();
3993
3994 return true;
3995}
3996
3997bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003998 // It is possible to transiantly have an undef cleanuppad operand because we
3999 // have deleted some, but not all, dead blocks.
4000 // Eventually, this block will be deleted.
4001 if (isa<UndefValue>(RI->getOperand(0)))
4002 return false;
4003
David Majnemer9f92f4c2016-05-21 05:12:32 +00004004 if (mergeCleanupPad(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00004005 return true;
4006
David Majnemer9f92f4c2016-05-21 05:12:32 +00004007 if (removeEmptyCleanup(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00004008 return true;
4009
4010 return false;
4011}
4012
Devang Pateldd14e0f2011-05-18 21:33:11 +00004013bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004014 BasicBlock *BB = RI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004015 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4016 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004017
Chris Lattner25c3af32010-12-13 06:25:44 +00004018 // Find predecessors that end with branches.
Dehao Chenf6c00832016-05-18 19:44:21 +00004019 SmallVector<BasicBlock *, 8> UncondBranchPreds;
4020 SmallVector<BranchInst *, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004021 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
4022 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00004023 TerminatorInst *PTI = P->getTerminator();
4024 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4025 if (BI->isUnconditional())
4026 UncondBranchPreds.push_back(P);
4027 else
4028 CondBranchPreds.push_back(BI);
4029 }
4030 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004031
Chris Lattner25c3af32010-12-13 06:25:44 +00004032 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00004033 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004034 while (!UncondBranchPreds.empty()) {
4035 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4036 DEBUG(dbgs() << "FOLDING: " << *BB
Dehao Chenf6c00832016-05-18 19:44:21 +00004037 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00004038 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00004039 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004040
Chris Lattner25c3af32010-12-13 06:25:44 +00004041 // If we eliminated all predecessors of the block, delete the block now.
Hyojin Sung4673f102016-03-29 04:08:57 +00004042 if (pred_empty(BB)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004043 // We know there are no successors, so just nuke the block.
4044 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004045 if (LoopHeaders)
4046 LoopHeaders->erase(BB);
Hyojin Sung4673f102016-03-29 04:08:57 +00004047 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004048
Chris Lattner25c3af32010-12-13 06:25:44 +00004049 return true;
4050 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004051
Chris Lattner25c3af32010-12-13 06:25:44 +00004052 // Check out all of the conditional branches going to this return
4053 // instruction. If any of them just select between returns, change the
4054 // branch itself into a select/return pair.
4055 while (!CondBranchPreds.empty()) {
4056 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004057
Chris Lattner25c3af32010-12-13 06:25:44 +00004058 // Check to see if the non-BB successor is also a return block.
4059 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4060 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00004061 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004062 return true;
4063 }
4064 return false;
4065}
4066
Chris Lattner25c3af32010-12-13 06:25:44 +00004067bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
4068 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004069
Chris Lattner25c3af32010-12-13 06:25:44 +00004070 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004071
Chris Lattner25c3af32010-12-13 06:25:44 +00004072 // If there are any instructions immediately before the unreachable that can
4073 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004074 while (UI->getIterator() != BB->begin()) {
4075 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004076 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004077 // Do not delete instructions that can have side effects which might cause
4078 // the unreachable to not be reachable; specifically, calls and volatile
4079 // operations may have this effect.
Dehao Chenf6c00832016-05-18 19:44:21 +00004080 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4081 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004082
4083 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004084 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004085 if (SI->isVolatile())
4086 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004087 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004088 if (LI->isVolatile())
4089 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004090 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004091 if (RMWI->isVolatile())
4092 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004093 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004094 if (CXI->isVolatile())
4095 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004096 } else if (isa<CatchPadInst>(BBI)) {
4097 // A catchpad may invoke exception object constructors and such, which
4098 // in some languages can be arbitrary code, so be conservative by
4099 // default.
4100 // For CoreCLR, it just involves a type test, so can be removed.
4101 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4102 EHPersonality::CoreCLR)
4103 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004104 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4105 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004106 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004107 }
Bill Wendling55d875f2011-08-16 20:41:17 +00004108 // Note that deleting LandingPad's here is in fact okay, although it
4109 // involves a bit of subtle reasoning. If this inst is a LandingPad,
4110 // all the predecessors of this block will be the unwind edges of Invokes,
4111 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004112 }
4113
Eli Friedmanaac35b32011-03-09 00:48:33 +00004114 // Delete this instruction (any uses are guaranteed to be dead)
4115 if (!BBI->use_empty())
4116 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00004117 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00004118 Changed = true;
4119 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004120
Chris Lattner25c3af32010-12-13 06:25:44 +00004121 // If the unreachable instruction is the first in the block, take a gander
4122 // at all of the predecessors of this instruction, and simplify them.
Dehao Chenf6c00832016-05-18 19:44:21 +00004123 if (&BB->front() != UI)
4124 return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004125
Dehao Chenf6c00832016-05-18 19:44:21 +00004126 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner25c3af32010-12-13 06:25:44 +00004127 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4128 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00004129 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004130 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004131 if (BI->isUnconditional()) {
4132 if (BI->getSuccessor(0) == BB) {
4133 new UnreachableInst(TI->getContext(), TI);
4134 TI->eraseFromParent();
4135 Changed = true;
4136 }
4137 } else {
4138 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004139 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00004140 EraseTerminatorInstAndDCECond(BI);
4141 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004142 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00004143 EraseTerminatorInstAndDCECond(BI);
4144 Changed = true;
4145 }
4146 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004147 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Chandler Carruth0d256c02017-03-26 02:49:23 +00004148 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004149 if (i->getCaseSuccessor() != BB) {
Chandler Carruth0d256c02017-03-26 02:49:23 +00004150 ++i;
4151 continue;
Chris Lattner25c3af32010-12-13 06:25:44 +00004152 }
Chandler Carruth0d256c02017-03-26 02:49:23 +00004153 BB->removePredecessor(SI->getParent());
4154 i = SI->removeCase(i);
4155 e = SI->case_end();
4156 Changed = true;
4157 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004158 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4159 if (II->getUnwindDest() == BB) {
4160 removeUnwindEdge(TI->getParent());
4161 Changed = true;
4162 }
4163 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4164 if (CSI->getUnwindDest() == BB) {
4165 removeUnwindEdge(TI->getParent());
4166 Changed = true;
4167 continue;
4168 }
4169
4170 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4171 E = CSI->handler_end();
4172 I != E; ++I) {
4173 if (*I == BB) {
4174 CSI->removeHandler(I);
4175 --I;
4176 --E;
4177 Changed = true;
4178 }
4179 }
4180 if (CSI->getNumHandlers() == 0) {
4181 BasicBlock *CatchSwitchBB = CSI->getParent();
4182 if (CSI->hasUnwindDest()) {
4183 // Redirect preds to the unwind dest
4184 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4185 } else {
4186 // Rewrite all preds to unwind to caller (or from invoke to call).
4187 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4188 for (BasicBlock *EHPred : EHPreds)
4189 removeUnwindEdge(EHPred);
4190 }
4191 // The catchswitch is no longer reachable.
4192 new UnreachableInst(CSI->getContext(), CSI);
4193 CSI->eraseFromParent();
4194 Changed = true;
4195 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004196 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00004197 new UnreachableInst(TI->getContext(), TI);
4198 TI->eraseFromParent();
4199 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004200 }
4201 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004202
Chris Lattner25c3af32010-12-13 06:25:44 +00004203 // If this block is now dead, remove it.
Dehao Chenf6c00832016-05-18 19:44:21 +00004204 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004205 // We know there are no successors, so just nuke the block.
4206 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004207 if (LoopHeaders)
4208 LoopHeaders->erase(BB);
Chris Lattner25c3af32010-12-13 06:25:44 +00004209 return true;
4210 }
4211
4212 return Changed;
4213}
4214
Hans Wennborg68000082015-01-26 19:52:32 +00004215static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4216 assert(Cases.size() >= 1);
4217
4218 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4219 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4220 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4221 return false;
4222 }
4223 return true;
4224}
4225
4226/// Turn a switch with two reachable destinations into an integer range
4227/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004228static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004229 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004230
Hans Wennborg68000082015-01-26 19:52:32 +00004231 bool HasDefault =
4232 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004233
Hans Wennborg68000082015-01-26 19:52:32 +00004234 // Partition the cases into two sets with different destinations.
4235 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4236 BasicBlock *DestB = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004237 SmallVector<ConstantInt *, 16> CasesA;
4238 SmallVector<ConstantInt *, 16> CasesB;
Hans Wennborg68000082015-01-26 19:52:32 +00004239
Chandler Carruth927d8e62017-04-12 07:27:28 +00004240 for (auto Case : SI->cases()) {
4241 BasicBlock *Dest = Case.getCaseSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00004242 if (!DestA)
4243 DestA = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004244 if (Dest == DestA) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004245 CasesA.push_back(Case.getCaseValue());
Hans Wennborg68000082015-01-26 19:52:32 +00004246 continue;
4247 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004248 if (!DestB)
4249 DestB = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004250 if (Dest == DestB) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004251 CasesB.push_back(Case.getCaseValue());
Hans Wennborg68000082015-01-26 19:52:32 +00004252 continue;
4253 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004254 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004255 }
4256
Dehao Chenf6c00832016-05-18 19:44:21 +00004257 assert(DestA && DestB &&
4258 "Single-destination switch should have been folded.");
Hans Wennborg68000082015-01-26 19:52:32 +00004259 assert(DestA != DestB);
4260 assert(DestB != SI->getDefaultDest());
4261 assert(!CasesB.empty() && "There must be non-default cases.");
4262 assert(!CasesA.empty() || HasDefault);
4263
4264 // Figure out if one of the sets of cases form a contiguous range.
4265 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4266 BasicBlock *ContiguousDest = nullptr;
4267 BasicBlock *OtherDest = nullptr;
4268 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4269 ContiguousCases = &CasesA;
4270 ContiguousDest = DestA;
4271 OtherDest = DestB;
4272 } else if (CasesAreContiguous(CasesB)) {
4273 ContiguousCases = &CasesB;
4274 ContiguousDest = DestB;
4275 OtherDest = DestA;
4276 } else
4277 return false;
4278
4279 // Start building the compare and branch.
4280
4281 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
Dehao Chenf6c00832016-05-18 19:44:21 +00004282 Constant *NumCases =
4283 ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004284
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00004285 Value *Sub = SI->getCondition();
4286 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00004287 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4288
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004289 Value *Cmp;
4290 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00004291 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004292 Cmp = ConstantInt::getTrue(SI->getContext());
4293 else
4294 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00004295 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004296
Manman Ren56575552012-09-18 00:47:33 +00004297 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00004298 if (HasBranchWeights(SI)) {
4299 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00004300 GetBranchWeights(SI, Weights);
4301 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00004302 uint64_t TrueWeight = 0;
4303 uint64_t FalseWeight = 0;
4304 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4305 if (SI->getSuccessor(I) == ContiguousDest)
4306 TrueWeight += Weights[I];
4307 else
4308 FalseWeight += Weights[I];
4309 }
4310 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4311 TrueWeight /= 2;
4312 FalseWeight /= 2;
4313 }
Manman Ren56575552012-09-18 00:47:33 +00004314 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004315 MDBuilder(SI->getContext())
4316 .createBranchWeights((uint32_t)TrueWeight,
4317 (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00004318 }
4319 }
4320
Hans Wennborg68000082015-01-26 19:52:32 +00004321 // Prune obsolete incoming values off the successors' PHI nodes.
4322 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4323 unsigned PreviousEdges = ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004324 if (ContiguousDest == SI->getDefaultDest())
4325 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004326 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004327 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4328 }
Hans Wennborg68000082015-01-26 19:52:32 +00004329 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4330 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004331 if (OtherDest == SI->getDefaultDest())
4332 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004333 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4334 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4335 }
4336
4337 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004338 SI->eraseFromParent();
4339
4340 return true;
4341}
Chris Lattner25c3af32010-12-13 06:25:44 +00004342
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004343/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004344/// and use it to remove dead cases.
Sanjay Patel4c33d522017-10-04 20:26:25 +00004345static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004346 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004347 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00004348 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Craig Topper8205a1a2017-05-24 16:53:07 +00004349 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004350
Sanjay Patel75892a12016-05-20 14:53:09 +00004351 // We can also eliminate cases by determining that their values are outside of
4352 // the limited range of the condition based on how many significant (non-sign)
4353 // bits are in the condition value.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004354 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
Sanjay Patel75892a12016-05-20 14:53:09 +00004355 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4356
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004357 // Gather dead cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00004358 SmallVector<ConstantInt *, 8> DeadCases;
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004359 for (auto &Case : SI->cases()) {
Craig Toppere777fed2017-05-22 00:49:35 +00004360 const APInt &CaseVal = Case.getCaseValue()->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00004361 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
Sanjay Patel75892a12016-05-20 14:53:09 +00004362 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004363 DeadCases.push_back(Case.getCaseValue());
Sanjay Patel75892a12016-05-20 14:53:09 +00004364 DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004365 }
4366 }
4367
Dehao Chenf6c00832016-05-18 19:44:21 +00004368 // If we can prove that the cases must cover all possible values, the
4369 // default destination becomes dead and we can remove it. If we know some
Philip Reames05370132015-09-10 17:44:47 +00004370 // of the bits in the value, we can use that to more precisely compute the
4371 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00004372 bool HasDefault =
Dehao Chenf6c00832016-05-18 19:44:21 +00004373 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4374 const unsigned NumUnknownBits =
Craig Topperb45eabc2017-04-26 16:39:58 +00004375 Bits - (Known.Zero | Known.One).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00004376 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00004377 if (HasDefault && DeadCases.empty() &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004378 NumUnknownBits < 64 /* avoid overflow */ &&
Philip Reames05370132015-09-10 17:44:47 +00004379 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00004380 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
Dehao Chenf6c00832016-05-18 19:44:21 +00004381 BasicBlock *NewDefault =
4382 SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004383 SI->setDefaultDest(&*NewDefault);
4384 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00004385 auto *OldTI = NewDefault->getTerminator();
4386 new UnreachableInst(SI->getContext(), OldTI);
4387 EraseTerminatorInstAndDCECond(OldTI);
4388 return true;
4389 }
4390
Manman Ren56575552012-09-18 00:47:33 +00004391 SmallVector<uint64_t, 8> Weights;
4392 bool HasWeight = HasBranchWeights(SI);
4393 if (HasWeight) {
4394 GetBranchWeights(SI, Weights);
4395 HasWeight = (Weights.size() == 1 + SI->getNumCases());
4396 }
4397
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004398 // Remove dead cases from the switch.
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004399 for (ConstantInt *DeadCase : DeadCases) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004400 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4401 assert(CaseI != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004402 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00004403 if (HasWeight) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004404 std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.back());
Manman Ren56575552012-09-18 00:47:33 +00004405 Weights.pop_back();
4406 }
4407
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004408 // Prune unused values from PHI nodes.
Chandler Carruth927d8e62017-04-12 07:27:28 +00004409 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4410 SI->removeCase(CaseI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004411 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00004412 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00004413 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4414 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004415 MDBuilder(SI->getParent()->getContext())
4416 .createBranchWeights(MDWeights));
Manman Ren56575552012-09-18 00:47:33 +00004417 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004418
4419 return !DeadCases.empty();
4420}
4421
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004422/// If BB would be eligible for simplification by
4423/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004424/// by an unconditional branch), look at the phi node for BB in the successor
4425/// block and see if the incoming value is equal to CaseValue. If so, return
4426/// the phi node, and set PhiIndex to BB's index in the phi node.
4427static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
Dehao Chenf6c00832016-05-18 19:44:21 +00004428 BasicBlock *BB, int *PhiIndex) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004429 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00004430 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004431 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00004432 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004433
4434 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4435 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00004436 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004437
4438 BasicBlock *Succ = Branch->getSuccessor(0);
4439
4440 BasicBlock::iterator I = Succ->begin();
4441 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4442 int Idx = PHI->getBasicBlockIndex(BB);
4443 assert(Idx >= 0 && "PHI has no entry for predecessor?");
4444
4445 Value *InValue = PHI->getIncomingValue(Idx);
Dehao Chenf6c00832016-05-18 19:44:21 +00004446 if (InValue != CaseValue)
4447 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004448
4449 *PhiIndex = Idx;
4450 return PHI;
4451 }
4452
Craig Topperf40110f2014-04-25 05:29:35 +00004453 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004454}
4455
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004456/// Try to forward the condition of a switch instruction to a phi node
4457/// dominated by the switch, if that would mean that some of the destination
Sanjay Patel30f30d32017-10-15 14:43:39 +00004458/// blocks of the switch can be folded away. Return true if a change is made.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004459static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00004460 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
4461
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004462 ForwardingNodesMap ForwardingNodes;
Sanjay Patel24226502017-10-22 16:51:03 +00004463 BasicBlock *SwitchBlock = SI->getParent();
4464 bool Changed = false;
Sanjay Patel30f30d32017-10-15 14:43:39 +00004465 for (auto &Case : SI->cases()) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004466 ConstantInt *CaseValue = Case.getCaseValue();
4467 BasicBlock *CaseDest = Case.getCaseSuccessor();
Sanjay Patel24226502017-10-22 16:51:03 +00004468
4469 // Replace phi operands in successor blocks that are using the constant case
4470 // value rather than the switch condition variable:
4471 // switchbb:
4472 // switch i32 %x, label %default [
4473 // i32 17, label %succ
4474 // ...
4475 // succ:
4476 // %r = phi i32 ... [ 17, %switchbb ] ...
4477 // -->
4478 // %r = phi i32 ... [ %x, %switchbb ] ...
4479
4480 for (Instruction &InstInCaseDest : *CaseDest) {
4481 auto *Phi = dyn_cast<PHINode>(&InstInCaseDest);
4482 if (!Phi) break;
4483
4484 // This only works if there is exactly 1 incoming edge from the switch to
4485 // a phi. If there is >1, that means multiple cases of the switch map to 1
4486 // value in the phi, and that phi value is not the switch condition. Thus,
4487 // this transform would not make sense (the phi would be invalid because
4488 // a phi can't have different incoming values from the same block).
4489 int SwitchBBIdx = Phi->getBasicBlockIndex(SwitchBlock);
4490 if (Phi->getIncomingValue(SwitchBBIdx) == CaseValue &&
4491 count(Phi->blocks(), SwitchBlock) == 1) {
4492 Phi->setIncomingValue(SwitchBBIdx, SI->getCondition());
4493 Changed = true;
4494 }
4495 }
4496
4497 // Collect phi nodes that are indirectly using this switch's case constants.
Sanjay Patel30f30d32017-10-15 14:43:39 +00004498 int PhiIdx;
4499 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
4500 ForwardingNodes[Phi].push_back(PhiIdx);
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004501 }
4502
Sanjay Patel30f30d32017-10-15 14:43:39 +00004503 for (auto &ForwardingNode : ForwardingNodes) {
4504 PHINode *Phi = ForwardingNode.first;
4505 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
Dehao Chenf6c00832016-05-18 19:44:21 +00004506 if (Indexes.size() < 2)
4507 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004508
Sanjay Patel30f30d32017-10-15 14:43:39 +00004509 for (int Index : Indexes)
4510 Phi->setIncomingValue(Index, SI->getCondition());
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004511 Changed = true;
4512 }
4513
4514 return Changed;
4515}
4516
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004517/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004518/// initializing an array of constants like C.
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004519static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00004520 if (C->isThreadDependent())
4521 return false;
4522 if (C->isDLLImportDependent())
4523 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004524
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004525 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4526 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4527 !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4528 return false;
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004529
Oliver Stannardfe4432b2016-10-17 12:00:24 +00004530 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004531 if (!CE->isGEPWithNoNotionalOverIndexing())
4532 return false;
Oliver Stannardfe4432b2016-10-17 12:00:24 +00004533 if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4534 return false;
4535 }
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004536
4537 if (!TTI.shouldBuildLookupTablesForConstant(C))
4538 return false;
4539
4540 return true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004541}
4542
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004543/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004544/// its constant value in ConstantPool, returning 0 if it's not there.
Dehao Chenf6c00832016-05-18 19:44:21 +00004545static Constant *
4546LookupConstant(Value *V,
4547 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004548 if (Constant *C = dyn_cast<Constant>(V))
4549 return C;
4550 return ConstantPool.lookup(V);
4551}
4552
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004553/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004554/// simple instructions such as binary operations where both operands are
4555/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004556/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004557static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004558ConstantFold(Instruction *I, const DataLayout &DL,
4559 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004560 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004561 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4562 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004563 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004564 if (A->isAllOnesValue())
4565 return LookupConstant(Select->getTrueValue(), ConstantPool);
4566 if (A->isNullValue())
4567 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004568 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004569 }
4570
Benjamin Kramer7c302602013-11-12 12:24:36 +00004571 SmallVector<Constant *, 4> COps;
4572 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4573 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4574 COps.push_back(A);
4575 else
Craig Topperf40110f2014-04-25 05:29:35 +00004576 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004577 }
4578
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004579 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004580 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4581 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004582 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004583
Manuel Jacobe9024592016-01-21 06:33:22 +00004584 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004585}
4586
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004587/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004588/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004589/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004590/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004591static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004592GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004593 BasicBlock **CommonDest,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004594 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004595 const DataLayout &DL, const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004596 // The block from which we enter the common destination.
4597 BasicBlock *Pred = SI->getParent();
4598
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004599 // If CaseDest is empty except for some side-effect free instructions through
4600 // which we can constant-propagate the CaseVal, continue to its successor.
Dehao Chenf6c00832016-05-18 19:44:21 +00004601 SmallDenseMap<Value *, Constant *> ConstantPool;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004602 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4603 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4604 ++I) {
4605 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4606 // If the terminator is a simple branch, continue to the next block.
David Majnemer8c03c1b2016-10-07 01:38:35 +00004607 if (T->getNumSuccessors() != 1 || T->isExceptional())
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004608 return false;
4609 Pred = CaseDest;
4610 CaseDest = T->getSuccessor(0);
4611 } else if (isa<DbgInfoIntrinsic>(I)) {
4612 // Skip debug intrinsic.
4613 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004614 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004615 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004616
4617 // If the instruction has uses outside this block or a phi node slot for
4618 // the block, it is not safe to bypass the instruction since it would then
4619 // no longer dominate all its uses.
4620 for (auto &Use : I->uses()) {
4621 User *User = Use.getUser();
4622 if (Instruction *I = dyn_cast<Instruction>(User))
4623 if (I->getParent() == CaseDest)
4624 continue;
4625 if (PHINode *Phi = dyn_cast<PHINode>(User))
4626 if (Phi->getIncomingBlock(Use) == CaseDest)
4627 continue;
4628 return false;
4629 }
4630
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004631 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004632 } else {
4633 break;
4634 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004635 }
4636
4637 // If we did not have a CommonDest before, use the current one.
4638 if (!*CommonDest)
4639 *CommonDest = CaseDest;
4640 // If the destination isn't the common one, abort.
4641 if (CaseDest != *CommonDest)
4642 return false;
4643
4644 // Get the values for this case from phi nodes in the destination block.
4645 BasicBlock::iterator I = (*CommonDest)->begin();
4646 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4647 int Idx = PHI->getBasicBlockIndex(Pred);
4648 if (Idx == -1)
4649 continue;
4650
Dehao Chenf6c00832016-05-18 19:44:21 +00004651 Constant *ConstVal =
4652 LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004653 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004654 return false;
4655
4656 // Be conservative about which kinds of constants we support.
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004657 if (!ValidLookupTableConstant(ConstVal, TTI))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004658 return false;
4659
4660 Res.push_back(std::make_pair(PHI, ConstVal));
4661 }
4662
Hans Wennborgac114a32014-01-12 00:44:41 +00004663 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004664}
4665
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004666// Helper function used to add CaseVal to the list of cases that generate
4667// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004668static void MapCaseToResult(ConstantInt *CaseVal,
Dehao Chenf6c00832016-05-18 19:44:21 +00004669 SwitchCaseResultVectorTy &UniqueResults,
4670 Constant *Result) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004671 for (auto &I : UniqueResults) {
4672 if (I.first == Result) {
4673 I.second.push_back(CaseVal);
4674 return;
4675 }
4676 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004677 UniqueResults.push_back(
4678 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004679}
4680
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004681// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004682// results for the PHI node of the common destination block for a switch
4683// instruction. Returns false if multiple PHI nodes have been found or if
4684// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004685static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4686 BasicBlock *&CommonDest,
4687 SwitchCaseResultVectorTy &UniqueResults,
4688 Constant *&DefaultResult,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004689 const DataLayout &DL,
4690 const TargetTransformInfo &TTI) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004691 for (auto &I : SI->cases()) {
4692 ConstantInt *CaseVal = I.getCaseValue();
4693
4694 // Resulting value at phi nodes for this case value.
4695 SwitchCaseResultsTy Results;
4696 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004697 DL, TTI))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004698 return false;
4699
4700 // Only one value per case is permitted
4701 if (Results.size() > 1)
4702 return false;
4703 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4704
4705 // Check the PHI consistency.
4706 if (!PHI)
4707 PHI = Results[0].first;
4708 else if (PHI != Results[0].first)
4709 return false;
4710 }
4711 // Find the default result value.
4712 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4713 BasicBlock *DefaultDest = SI->getDefaultDest();
4714 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004715 DL, TTI);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004716 // If the default value is not found abort unless the default destination
4717 // is unreachable.
4718 DefaultResult =
4719 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4720 if ((!DefaultResult &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004721 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004722 return false;
4723
4724 return true;
4725}
4726
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004727// Helper function that checks if it is possible to transform a switch with only
4728// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004729// Example:
4730// switch (a) {
4731// case 10: %0 = icmp eq i32 %a, 10
4732// return 10; %1 = select i1 %0, i32 10, i32 4
4733// case 20: ----> %2 = icmp eq i32 %a, 20
4734// return 2; %3 = select i1 %2, i32 2, i32 %1
4735// default:
4736// return 4;
4737// }
Dehao Chenf6c00832016-05-18 19:44:21 +00004738static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4739 Constant *DefaultResult, Value *Condition,
4740 IRBuilder<> &Builder) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004741 assert(ResultVector.size() == 2 &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004742 "We should have exactly two unique results at this point");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004743 // If we are selecting between only two cases transform into a simple
4744 // select or a two-way select if default is possible.
4745 if (ResultVector[0].second.size() == 1 &&
4746 ResultVector[1].second.size() == 1) {
4747 ConstantInt *const FirstCase = ResultVector[0].second[0];
4748 ConstantInt *const SecondCase = ResultVector[1].second[0];
4749
4750 bool DefaultCanTrigger = DefaultResult;
4751 Value *SelectValue = ResultVector[1].first;
4752 if (DefaultCanTrigger) {
4753 Value *const ValueCompare =
4754 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4755 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4756 DefaultResult, "switch.select");
4757 }
4758 Value *const ValueCompare =
4759 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
Dehao Chenf6c00832016-05-18 19:44:21 +00004760 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4761 SelectValue, "switch.select");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004762 }
4763
4764 return nullptr;
4765}
4766
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004767// Helper function to cleanup a switch instruction that has been converted into
4768// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004769static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4770 Value *SelectValue,
4771 IRBuilder<> &Builder) {
4772 BasicBlock *SelectBB = SI->getParent();
4773 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4774 PHI->removeIncomingValue(SelectBB);
4775 PHI->addIncoming(SelectValue, SelectBB);
4776
4777 Builder.CreateBr(PHI->getParent());
4778
4779 // Remove the switch.
4780 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4781 BasicBlock *Succ = SI->getSuccessor(i);
4782
4783 if (Succ == PHI->getParent())
4784 continue;
4785 Succ->removePredecessor(SelectBB);
4786 }
4787 SI->eraseFromParent();
4788}
4789
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004790/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004791/// phi nodes in a common successor block with only two different
4792/// constant values, replace the switch with select.
Sanjay Patel4c33d522017-10-04 20:26:25 +00004793static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4794 const DataLayout &DL,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004795 const TargetTransformInfo &TTI) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004796 Value *const Cond = SI->getCondition();
4797 PHINode *PHI = nullptr;
4798 BasicBlock *CommonDest = nullptr;
4799 Constant *DefaultResult;
4800 SwitchCaseResultVectorTy UniqueResults;
4801 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004802 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004803 DL, TTI))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004804 return false;
4805 // Selects choose between maximum two values.
4806 if (UniqueResults.size() != 2)
4807 return false;
4808 assert(PHI != nullptr && "PHI for value select not found");
4809
4810 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00004811 Value *SelectValue =
4812 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004813 if (SelectValue) {
4814 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4815 return true;
4816 }
4817 // The switch couldn't be converted into a select.
4818 return false;
4819}
4820
Hans Wennborg776d7122012-09-26 09:34:53 +00004821namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004822
Dehao Chenf6c00832016-05-18 19:44:21 +00004823/// This class represents a lookup table that can be used to replace a switch.
4824class SwitchLookupTable {
4825public:
4826 /// Create a lookup table to use as a switch replacement with the contents
4827 /// of Values, using DefaultValue to fill any holes in the table.
4828 SwitchLookupTable(
4829 Module &M, uint64_t TableSize, ConstantInt *Offset,
4830 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00004831 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
Hans Wennborg776d7122012-09-26 09:34:53 +00004832
Dehao Chenf6c00832016-05-18 19:44:21 +00004833 /// Build instructions with Builder to retrieve the value at
4834 /// the position given by Index in the lookup table.
4835 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004836
Dehao Chenf6c00832016-05-18 19:44:21 +00004837 /// Return true if a table with TableSize elements of
4838 /// type ElementType would fit in a target-legal register.
4839 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4840 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004841
Dehao Chenf6c00832016-05-18 19:44:21 +00004842private:
4843 // Depending on the contents of the table, it can be represented in
4844 // different ways.
4845 enum {
4846 // For tables where each element contains the same value, we just have to
4847 // store that single value and return it for each lookup.
4848 SingleValueKind,
Hans Wennborg776d7122012-09-26 09:34:53 +00004849
Dehao Chenf6c00832016-05-18 19:44:21 +00004850 // For tables where there is a linear relationship between table index
4851 // and values. We calculate the result with a simple multiplication
4852 // and addition instead of a table lookup.
4853 LinearMapKind,
Erik Eckstein105374f2014-11-17 09:13:57 +00004854
Dehao Chenf6c00832016-05-18 19:44:21 +00004855 // For small tables with integer elements, we can pack them into a bitmap
4856 // that fits into a target-legal register. Values are retrieved by
4857 // shift and mask operations.
4858 BitMapKind,
Hans Wennborg39583b82012-09-26 09:44:49 +00004859
Dehao Chenf6c00832016-05-18 19:44:21 +00004860 // The table is stored as an array of values. Values are retrieved by load
4861 // instructions from the table.
4862 ArrayKind
4863 } Kind;
Hans Wennborg776d7122012-09-26 09:34:53 +00004864
Dehao Chenf6c00832016-05-18 19:44:21 +00004865 // For SingleValueKind, this is the single value.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00004866 Constant *SingleValue = nullptr;
Hans Wennborg776d7122012-09-26 09:34:53 +00004867
Dehao Chenf6c00832016-05-18 19:44:21 +00004868 // For BitMapKind, this is the bitmap.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00004869 ConstantInt *BitMap = nullptr;
4870 IntegerType *BitMapElementTy = nullptr;
Hans Wennborg39583b82012-09-26 09:44:49 +00004871
Dehao Chenf6c00832016-05-18 19:44:21 +00004872 // For LinearMapKind, these are the constants used to derive the value.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00004873 ConstantInt *LinearOffset = nullptr;
4874 ConstantInt *LinearMultiplier = nullptr;
Erik Eckstein105374f2014-11-17 09:13:57 +00004875
Dehao Chenf6c00832016-05-18 19:44:21 +00004876 // For ArrayKind, this is the array.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00004877 GlobalVariable *Array = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004878};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004879
4880} // end anonymous namespace
Hans Wennborg776d7122012-09-26 09:34:53 +00004881
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004882SwitchLookupTable::SwitchLookupTable(
4883 Module &M, uint64_t TableSize, ConstantInt *Offset,
4884 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00004885 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004886 assert(Values.size() && "Can't build lookup table without values!");
4887 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004888
4889 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004890 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004891
Hans Wennborgac114a32014-01-12 00:44:41 +00004892 Type *ValueType = Values.begin()->second->getType();
4893
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004894 // Build up the table contents.
Dehao Chenf6c00832016-05-18 19:44:21 +00004895 SmallVector<Constant *, 64> TableContents(TableSize);
Hans Wennborg776d7122012-09-26 09:34:53 +00004896 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4897 ConstantInt *CaseVal = Values[I].first;
4898 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004899 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004900
Dehao Chenf6c00832016-05-18 19:44:21 +00004901 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004902 TableContents[Idx] = CaseRes;
4903
Hans Wennborg776d7122012-09-26 09:34:53 +00004904 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004905 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004906 }
4907
4908 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004909 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004910 assert(DefaultValue &&
4911 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004912 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004913 for (uint64_t I = 0; I < TableSize; ++I) {
4914 if (!TableContents[I])
4915 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004916 }
4917
Hans Wennborg776d7122012-09-26 09:34:53 +00004918 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004919 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004920 }
4921
Hans Wennborg776d7122012-09-26 09:34:53 +00004922 // If each element in the table contains the same value, we only need to store
4923 // that single value.
4924 if (SingleValue) {
4925 Kind = SingleValueKind;
4926 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004927 }
4928
Erik Eckstein105374f2014-11-17 09:13:57 +00004929 // Check if we can derive the value with a linear transformation from the
4930 // table index.
4931 if (isa<IntegerType>(ValueType)) {
4932 bool LinearMappingPossible = true;
4933 APInt PrevVal;
4934 APInt DistToPrev;
4935 assert(TableSize >= 2 && "Should be a SingleValue table.");
4936 // Check if there is the same distance between two consecutive values.
4937 for (uint64_t I = 0; I < TableSize; ++I) {
4938 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4939 if (!ConstVal) {
4940 // This is an undef. We could deal with it, but undefs in lookup tables
4941 // are very seldom. It's probably not worth the additional complexity.
4942 LinearMappingPossible = false;
4943 break;
4944 }
Craig Toppere777fed2017-05-22 00:49:35 +00004945 const APInt &Val = ConstVal->getValue();
Erik Eckstein105374f2014-11-17 09:13:57 +00004946 if (I != 0) {
4947 APInt Dist = Val - PrevVal;
4948 if (I == 1) {
4949 DistToPrev = Dist;
4950 } else if (Dist != DistToPrev) {
4951 LinearMappingPossible = false;
4952 break;
4953 }
4954 }
4955 PrevVal = Val;
4956 }
4957 if (LinearMappingPossible) {
4958 LinearOffset = cast<ConstantInt>(TableContents[0]);
4959 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4960 Kind = LinearMapKind;
4961 ++NumLinearMaps;
4962 return;
4963 }
4964 }
4965
Hans Wennborg39583b82012-09-26 09:44:49 +00004966 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004967 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004968 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004969 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4970 for (uint64_t I = TableSize; I > 0; --I) {
4971 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004972 // Insert values into the bitmap. Undef values are set to zero.
4973 if (!isa<UndefValue>(TableContents[I - 1])) {
4974 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4975 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4976 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004977 }
4978 BitMap = ConstantInt::get(M.getContext(), TableInt);
4979 BitMapElementTy = IT;
4980 Kind = BitMapKind;
4981 ++NumBitMaps;
4982 return;
4983 }
4984
Hans Wennborg776d7122012-09-26 09:34:53 +00004985 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004986 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004987 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4988
Dehao Chenf6c00832016-05-18 19:44:21 +00004989 Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
4990 GlobalVariable::PrivateLinkage, Initializer,
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00004991 "switch.table." + FuncName);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004992 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Hans Wennborg776d7122012-09-26 09:34:53 +00004993 Kind = ArrayKind;
4994}
4995
Manman Ren4d189fb2014-07-24 21:13:20 +00004996Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004997 switch (Kind) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004998 case SingleValueKind:
4999 return SingleValue;
5000 case LinearMapKind: {
5001 // Derive the result value from the input value.
5002 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5003 false, "switch.idx.cast");
5004 if (!LinearMultiplier->isOne())
5005 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5006 if (!LinearOffset->isZero())
5007 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5008 return Result;
5009 }
5010 case BitMapKind: {
5011 // Type of the bitmap (e.g. i59).
5012 IntegerType *MapTy = BitMap->getType();
Hans Wennborg39583b82012-09-26 09:44:49 +00005013
Dehao Chenf6c00832016-05-18 19:44:21 +00005014 // Cast Index to the same type as the bitmap.
5015 // Note: The Index is <= the number of elements in the table, so
5016 // truncating it to the width of the bitmask is safe.
5017 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00005018
Dehao Chenf6c00832016-05-18 19:44:21 +00005019 // Multiply the shift amount by the element width.
5020 ShiftAmt = Builder.CreateMul(
5021 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5022 "switch.shiftamt");
Hans Wennborg39583b82012-09-26 09:44:49 +00005023
Dehao Chenf6c00832016-05-18 19:44:21 +00005024 // Shift down.
5025 Value *DownShifted =
5026 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5027 // Mask off.
5028 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5029 }
5030 case ArrayKind: {
5031 // Make sure the table index will not overflow when treated as signed.
5032 IntegerType *IT = cast<IntegerType>(Index->getType());
5033 uint64_t TableSize =
5034 Array->getInitializer()->getType()->getArrayNumElements();
5035 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5036 Index = Builder.CreateZExt(
5037 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5038 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00005039
Dehao Chenf6c00832016-05-18 19:44:21 +00005040 Value *GEPIndices[] = {Builder.getInt32(0), Index};
5041 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5042 GEPIndices, "switch.gep");
5043 return Builder.CreateLoad(GEP, "switch.load");
5044 }
Hans Wennborg776d7122012-09-26 09:34:53 +00005045 }
5046 llvm_unreachable("Unknown lookup table kind!");
5047}
5048
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005049bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00005050 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00005051 Type *ElementType) {
5052 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00005053 if (!IT)
5054 return false;
5055 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5056 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00005057
5058 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
Dehao Chenf6c00832016-05-18 19:44:21 +00005059 if (TableSize >= UINT_MAX / IT->getBitWidth())
Benjamin Kramerc2081d12012-09-27 18:29:58 +00005060 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005061 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00005062}
5063
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005064/// Determine whether a lookup table should be built for this switch, based on
5065/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005066static bool
5067ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5068 const TargetTransformInfo &TTI, const DataLayout &DL,
5069 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00005070 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5071 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00005072
Chandler Carruth77d433d2012-11-30 09:26:25 +00005073 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00005074 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00005075 for (const auto &I : ResultTypes) {
5076 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005077
5078 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005079 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005080
5081 // Saturate this flag to false.
Dehao Chenf6c00832016-05-18 19:44:21 +00005082 AllTablesFitInRegister =
5083 AllTablesFitInRegister &&
5084 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005085
5086 // If both flags saturate, we're done. NOTE: This *only* works with
5087 // saturating flags, and all flags have to saturate first due to the
5088 // non-deterministic behavior of iterating over a dense map.
5089 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00005090 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00005091 }
Evan Cheng65df8082012-11-30 02:02:42 +00005092
Chandler Carruth77d433d2012-11-30 09:26:25 +00005093 // If each table would fit in a register, we should build it anyway.
5094 if (AllTablesFitInRegister)
5095 return true;
5096
5097 // Don't build a table that doesn't fit in-register if it has illegal types.
5098 if (HasIllegalType)
5099 return false;
5100
5101 // The table density should be at least 40%. This is the same criterion as for
5102 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5103 // FIXME: Find the best cut-off.
5104 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005105}
5106
Erik Eckstein0d86c762014-11-27 15:13:14 +00005107/// Try to reuse the switch table index compare. Following pattern:
5108/// \code
5109/// if (idx < tablesize)
5110/// r = table[idx]; // table does not contain default_value
5111/// else
5112/// r = default_value;
5113/// if (r != default_value)
5114/// ...
5115/// \endcode
5116/// Is optimized to:
5117/// \code
5118/// cond = idx < tablesize;
5119/// if (cond)
5120/// r = table[idx];
5121/// else
5122/// r = default_value;
5123/// if (cond)
5124/// ...
5125/// \endcode
5126/// Jump threading will then eliminate the second if(cond).
Dehao Chenf6c00832016-05-18 19:44:21 +00005127static void reuseTableCompare(
5128 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5129 Constant *DefaultValue,
5130 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
Erik Eckstein0d86c762014-11-27 15:13:14 +00005131 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5132 if (!CmpInst)
5133 return;
5134
5135 // We require that the compare is in the same block as the phi so that jump
5136 // threading can do its work afterwards.
5137 if (CmpInst->getParent() != PhiBlock)
5138 return;
5139
5140 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5141 if (!CmpOp1)
5142 return;
5143
5144 Value *RangeCmp = RangeCheckBranch->getCondition();
5145 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5146 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5147
5148 // Check if the compare with the default value is constant true or false.
5149 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5150 DefaultValue, CmpOp1, true);
5151 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5152 return;
5153
5154 // Check if the compare with the case values is distinct from the default
5155 // compare result.
5156 for (auto ValuePair : Values) {
5157 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
Dehao Chenf6c00832016-05-18 19:44:21 +00005158 ValuePair.second, CmpOp1, true);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005159 if (!CaseConst || CaseConst == DefaultConst)
5160 return;
5161 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5162 "Expect true or false as compare result.");
5163 }
Dehao Chenf6c00832016-05-18 19:44:21 +00005164
Erik Eckstein0d86c762014-11-27 15:13:14 +00005165 // Check if the branch instruction dominates the phi node. It's a simple
5166 // dominance check, but sufficient for our needs.
5167 // Although this check is invariant in the calling loops, it's better to do it
5168 // at this late stage. Practically we do it at most once for a switch.
5169 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5170 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5171 BasicBlock *Pred = *PI;
5172 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5173 return;
5174 }
5175
5176 if (DefaultConst == FalseConst) {
5177 // The compare yields the same result. We can replace it.
5178 CmpInst->replaceAllUsesWith(RangeCmp);
5179 ++NumTableCmpReuses;
5180 } else {
5181 // The compare yields the same result, just inverted. We can replace it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005182 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5183 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5184 RangeCheckBranch);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005185 CmpInst->replaceAllUsesWith(InvertedTableCmp);
5186 ++NumTableCmpReuses;
5187 }
5188}
5189
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005190/// If the switch is only used to initialize one or more phi nodes in a common
5191/// successor block with different constant values, replace the switch with
5192/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005193static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5194 const DataLayout &DL,
5195 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005196 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00005197
Sumanth Gundapaneni8d50a502017-07-28 22:25:40 +00005198 Function *Fn = SI->getParent()->getParent();
5199 // Only build lookup table when we have a target that supports it or the
5200 // attribute is not set.
5201 if (!TTI.shouldBuildLookupTables() ||
5202 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
Hans Wennborgf3254832012-10-30 11:23:25 +00005203 return false;
5204
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005205 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5206 // split off a dense part and build a lookup table for that.
5207
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005208 // FIXME: This creates arrays of GEPs to constant strings, which means each
5209 // GEP needs a runtime relocation in PIC code. We should just build one big
5210 // string and lookup indices into that.
5211
Dehao Chenf6c00832016-05-18 19:44:21 +00005212 // Ignore switches with less than three cases. Lookup tables will not make
Sanjay Patelca146972017-09-19 20:58:14 +00005213 // them faster, so we don't analyze them.
Hans Wennborg4744ac12014-01-15 05:00:27 +00005214 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005215 return false;
5216
5217 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00005218 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005219 assert(SI->case_begin() != SI->case_end());
5220 SwitchInst::CaseIt CI = SI->case_begin();
Chandler Carruth927d8e62017-04-12 07:27:28 +00005221 ConstantInt *MinCaseVal = CI->getCaseValue();
5222 ConstantInt *MaxCaseVal = CI->getCaseValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005223
Craig Topperf40110f2014-04-25 05:29:35 +00005224 BasicBlock *CommonDest = nullptr;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00005225
5226 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
Dehao Chenf6c00832016-05-18 19:44:21 +00005227 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00005228
Dehao Chenf6c00832016-05-18 19:44:21 +00005229 SmallDenseMap<PHINode *, Constant *> DefaultResults;
5230 SmallDenseMap<PHINode *, Type *> ResultTypes;
5231 SmallVector<PHINode *, 4> PHIs;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005232
5233 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00005234 ConstantInt *CaseVal = CI->getCaseValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005235 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5236 MinCaseVal = CaseVal;
5237 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5238 MaxCaseVal = CaseVal;
5239
5240 // Resulting value at phi nodes for this case value.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00005241 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005242 ResultsTy Results;
Chandler Carruth927d8e62017-04-12 07:27:28 +00005243 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00005244 Results, DL, TTI))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005245 return false;
5246
5247 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005248 for (const auto &I : Results) {
5249 PHINode *PHI = I.first;
5250 Constant *Value = I.second;
5251 if (!ResultLists.count(PHI))
5252 PHIs.push_back(PHI);
5253 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005254 }
5255 }
5256
Hans Wennborgac114a32014-01-12 00:44:41 +00005257 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005258 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00005259 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5260 }
5261
5262 uint64_t NumResults = ResultLists[PHIs[0]].size();
5263 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5264 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5265 bool TableHasHoles = (NumResults < TableSize);
5266
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005267 // If the table has holes, we need a constant result for the default case
5268 // or a bitmask that fits in a register.
Dehao Chenf6c00832016-05-18 19:44:21 +00005269 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
Oliver Stannard4df1cc02016-10-07 08:48:24 +00005270 bool HasDefaultResults =
5271 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5272 DefaultResultsList, DL, TTI);
Hans Wennborga6a11a92014-11-18 02:37:11 +00005273
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005274 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5275 if (NeedMask) {
5276 // As an extra penalty for the validity test we require more cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00005277 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005278 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005279 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005280 return false;
5281 }
Hans Wennborgac114a32014-01-12 00:44:41 +00005282
Hans Wennborga6a11a92014-11-18 02:37:11 +00005283 for (const auto &I : DefaultResultsList) {
5284 PHINode *PHI = I.first;
5285 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00005286 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005287 }
5288
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005289 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005290 return false;
5291
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005292 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00005293 Module &Mod = *CommonDest->getParent()->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00005294 BasicBlock *LookupBB = BasicBlock::Create(
5295 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005296
Michael Gottesmanc024f322013-10-20 07:04:37 +00005297 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005298 Builder.SetInsertPoint(SI);
Sanjay Patel73811a12017-09-20 22:31:35 +00005299 Value *TableIndex;
5300 if (MinCaseVal->isNullValue())
5301 TableIndex = SI->getCondition();
5302 else
5303 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5304 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00005305
5306 // Compute the maximum table size representable by the integer type we are
5307 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005308 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00005309 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00005310 assert(MaxTableSize >= TableSize &&
5311 "It is impossible for a switch to have more entries than the max "
5312 "representable value of its input integer type's size.");
5313
Hans Wennborgb64cb272015-01-26 19:52:34 +00005314 // If the default destination is unreachable, or if the lookup table covers
5315 // all values of the conditional variable, branch directly to the lookup table
5316 // BB. Otherwise, check that the condition is within the case range.
5317 const bool DefaultIsReachable =
5318 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5319 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005320 BranchInst *RangeCheckBranch = nullptr;
5321
Hans Wennborgb64cb272015-01-26 19:52:34 +00005322 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00005323 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00005324 // Note: We call removeProdecessor later since we need to be able to get the
5325 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00005326 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005327 Value *Cmp = Builder.CreateICmpULT(
5328 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5329 RangeCheckBranch =
5330 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00005331 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005332
5333 // Populate the BB that does the lookups.
5334 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005335
5336 if (NeedMask) {
Sanjay Patelca146972017-09-19 20:58:14 +00005337 // Before doing the lookup, we do the hole check. The LookupBB is therefore
5338 // re-purposed to do the hole check, and we create a new LookupBB.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005339 BasicBlock *MaskBB = LookupBB;
5340 MaskBB->setName("switch.hole_check");
Dehao Chenf6c00832016-05-18 19:44:21 +00005341 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5342 CommonDest->getParent(), CommonDest);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005343
Sanjay Patelca146972017-09-19 20:58:14 +00005344 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
Juergen Ributzkac9591e92014-11-17 19:39:56 +00005345 // unnecessary illegal types.
5346 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5347 APInt MaskInt(TableSizePowOf2, 0);
5348 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005349 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005350 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5351 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005352 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5353 .getLimitedValue();
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005354 MaskInt |= One << Idx;
5355 }
5356 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5357
5358 // Get the TableIndex'th bit of the bitmask.
5359 // If this bit is 0 (meaning hole) jump to the default destination,
5360 // else continue with table lookup.
5361 IntegerType *MapTy = TableMask->getType();
Dehao Chenf6c00832016-05-18 19:44:21 +00005362 Value *MaskIndex =
5363 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5364 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5365 Value *LoBit = Builder.CreateTrunc(
5366 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005367 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5368
5369 Builder.SetInsertPoint(LookupBB);
5370 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5371 }
5372
Hans Wennborg86ac6302015-04-24 20:57:56 +00005373 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Sanjay Patelca146972017-09-19 20:58:14 +00005374 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
Hans Wennborg86ac6302015-04-24 20:57:56 +00005375 // do not delete PHINodes here.
5376 SI->getDefaultDest()->removePredecessor(SI->getParent(),
5377 /*DontDeleteUselessPHIs=*/true);
5378 }
5379
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005380 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00005381 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5382 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005383 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005384
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005385 // If using a bitmask, use any value to fill the lookup table holes.
5386 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Sumanth Gundapaneni8d50a502017-07-28 22:25:40 +00005387 StringRef FuncName = Fn->getName();
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00005388 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5389 FuncName);
Hans Wennborg776d7122012-09-26 09:34:53 +00005390
Manman Ren4d189fb2014-07-24 21:13:20 +00005391 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005392
Hans Wennborgf744fa92012-09-19 14:24:21 +00005393 // If the result is used to return immediately from the function, we want to
5394 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005395 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5396 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00005397 Builder.CreateRet(Result);
5398 ReturnedEarly = true;
5399 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005400 }
5401
Erik Eckstein0d86c762014-11-27 15:13:14 +00005402 // Do a small peephole optimization: re-use the switch table compare if
5403 // possible.
5404 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5405 BasicBlock *PhiBlock = PHI->getParent();
5406 // Search for compare instructions which use the phi.
5407 for (auto *User : PHI->users()) {
5408 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5409 }
5410 }
5411
Hans Wennborgf744fa92012-09-19 14:24:21 +00005412 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005413 }
5414
5415 if (!ReturnedEarly)
5416 Builder.CreateBr(CommonDest);
5417
5418 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005419 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005420 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00005421
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005422 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00005423 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005424 Succ->removePredecessor(SI->getParent());
5425 }
5426 SI->eraseFromParent();
5427
5428 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005429 if (NeedMask)
5430 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005431 return true;
5432}
5433
James Molloyb2e436d2016-08-01 07:45:11 +00005434static bool isSwitchDense(ArrayRef<int64_t> Values) {
5435 // See also SelectionDAGBuilder::isDense(), which this function was based on.
5436 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5437 uint64_t Range = Diff + 1;
5438 uint64_t NumCases = Values.size();
5439 // 40% is the default density for building a jump table in optsize/minsize mode.
5440 uint64_t MinDensity = 40;
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005441
James Molloyb2e436d2016-08-01 07:45:11 +00005442 return NumCases * 100 >= Range * MinDensity;
5443}
5444
Sanjay Patelca146972017-09-19 20:58:14 +00005445/// Try to transform a switch that has "holes" in it to a contiguous sequence
5446/// of cases.
5447///
5448/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5449/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5450///
5451/// This converts a sparse switch into a dense switch which allows better
5452/// lowering and could also allow transforming into a lookup table.
James Molloyb2e436d2016-08-01 07:45:11 +00005453static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5454 const DataLayout &DL,
5455 const TargetTransformInfo &TTI) {
5456 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5457 if (CondTy->getIntegerBitWidth() > 64 ||
5458 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5459 return false;
5460 // Only bother with this optimization if there are more than 3 switch cases;
5461 // SDAG will only bother creating jump tables for 4 or more cases.
5462 if (SI->getNumCases() < 4)
5463 return false;
5464
5465 // This transform is agnostic to the signedness of the input or case values. We
5466 // can treat the case values as signed or unsigned. We can optimize more common
5467 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5468 // as signed.
5469 SmallVector<int64_t,4> Values;
5470 for (auto &C : SI->cases())
5471 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5472 std::sort(Values.begin(), Values.end());
5473
5474 // If the switch is already dense, there's nothing useful to do here.
5475 if (isSwitchDense(Values))
5476 return false;
5477
5478 // First, transform the values such that they start at zero and ascend.
5479 int64_t Base = Values[0];
5480 for (auto &V : Values)
Vitaly Buka524c0a62017-10-17 18:33:15 +00005481 V -= (uint64_t)(Base);
James Molloyb2e436d2016-08-01 07:45:11 +00005482
5483 // Now we have signed numbers that have been shifted so that, given enough
5484 // precision, there are no negative values. Since the rest of the transform
5485 // is bitwise only, we switch now to an unsigned representation.
5486 uint64_t GCD = 0;
5487 for (auto &V : Values)
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005488 GCD = GreatestCommonDivisor64(GCD, (uint64_t)V);
James Molloyb2e436d2016-08-01 07:45:11 +00005489
5490 // This transform can be done speculatively because it is so cheap - it results
5491 // in a single rotate operation being inserted. This can only happen if the
5492 // factor extracted is a power of 2.
5493 // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5494 // inverse of GCD and then perform this transform.
5495 // FIXME: It's possible that optimizing a switch on powers of two might also
5496 // be beneficial - flag values are often powers of two and we could use a CLZ
5497 // as the key function.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005498 if (GCD <= 1 || !isPowerOf2_64(GCD))
James Molloyb2e436d2016-08-01 07:45:11 +00005499 // No common divisor found or too expensive to compute key function.
5500 return false;
5501
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005502 unsigned Shift = Log2_64(GCD);
James Molloyb2e436d2016-08-01 07:45:11 +00005503 for (auto &V : Values)
5504 V = (int64_t)((uint64_t)V >> Shift);
5505
5506 if (!isSwitchDense(Values))
5507 // Transform didn't create a dense switch.
5508 return false;
5509
5510 // The obvious transform is to shift the switch condition right and emit a
5511 // check that the condition actually cleanly divided by GCD, i.e.
5512 // C & (1 << Shift - 1) == 0
5513 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5514 //
5515 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5516 // shift and puts the shifted-off bits in the uppermost bits. If any of these
5517 // are nonzero then the switch condition will be very large and will hit the
5518 // default case.
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005519
James Molloyb2e436d2016-08-01 07:45:11 +00005520 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5521 Builder.SetInsertPoint(SI);
5522 auto *ShiftC = ConstantInt::get(Ty, Shift);
5523 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
Benjamin Krameraa160c22016-08-05 14:55:02 +00005524 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5525 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5526 auto *Rot = Builder.CreateOr(LShr, Shl);
James Molloyb2e436d2016-08-01 07:45:11 +00005527 SI->replaceUsesOfWith(SI->getCondition(), Rot);
5528
Chandler Carruth927d8e62017-04-12 07:27:28 +00005529 for (auto Case : SI->cases()) {
5530 auto *Orig = Case.getCaseValue();
James Molloyb2e436d2016-08-01 07:45:11 +00005531 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005532 Case.setValue(
James Molloybade86c2016-08-01 09:34:48 +00005533 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
James Molloyb2e436d2016-08-01 07:45:11 +00005534 }
5535 return true;
5536}
5537
Devang Patela7ec47d2011-05-18 20:35:38 +00005538bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005539 BasicBlock *BB = SI->getParent();
5540
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005541 if (isValueEqualityComparison(SI)) {
5542 // If we only have one predecessor, and if it is a branch on this value,
5543 // see if that predecessor totally determines the outcome of this switch.
5544 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5545 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005546 return simplifyCFG(BB, TTI, Options) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005547
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005548 Value *Cond = SI->getCondition();
5549 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5550 if (SimplifySwitchOnSelect(SI, Select))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005551 return simplifyCFG(BB, TTI, Options) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005552
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005553 // If the block only contains the switch, see if we can fold the block
5554 // away into any preds.
5555 BasicBlock::iterator BBI = BB->begin();
5556 // Ignore dbg intrinsics.
5557 while (isa<DbgInfoIntrinsic>(BBI))
5558 ++BBI;
5559 if (SI == &*BBI)
5560 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005561 return simplifyCFG(BB, TTI, Options) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005562 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00005563
5564 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00005565 if (TurnSwitchRangeIntoICmp(SI, Builder))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005566 return simplifyCFG(BB, TTI, Options) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005567
5568 // Remove unreachable cases.
Sanjay Patel4c33d522017-10-04 20:26:25 +00005569 if (eliminateDeadSwitchCases(SI, Options.AC, DL))
5570 return simplifyCFG(BB, TTI, Options) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005571
Sanjay Patel4c33d522017-10-04 20:26:25 +00005572 if (switchToSelect(SI, Builder, DL, TTI))
5573 return simplifyCFG(BB, TTI, Options) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00005574
Sanjay Patelb80daf02017-10-22 19:10:07 +00005575 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005576 return simplifyCFG(BB, TTI, Options) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005577
Sanjay Patelca146972017-09-19 20:58:14 +00005578 // The conversion from switch to lookup tables results in difficult-to-analyze
5579 // code and makes pruning branches much harder. This is a problem if the
5580 // switch expression itself can still be restricted as a result of inlining or
5581 // CVP. Therefore, only apply this transformation during late stages of the
5582 // optimisation pipeline.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005583 if (Options.ConvertSwitchToLookupTable &&
5584 SwitchToLookupTable(SI, Builder, DL, TTI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005585 return simplifyCFG(BB, TTI, Options) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005586
James Molloyb2e436d2016-08-01 07:45:11 +00005587 if (ReduceSwitchRange(SI, Builder, DL, TTI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005588 return simplifyCFG(BB, TTI, Options) | true;
James Molloyb2e436d2016-08-01 07:45:11 +00005589
Chris Lattner25c3af32010-12-13 06:25:44 +00005590 return false;
5591}
5592
5593bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5594 BasicBlock *BB = IBI->getParent();
5595 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005596
Chris Lattner25c3af32010-12-13 06:25:44 +00005597 // Eliminate redundant destinations.
5598 SmallPtrSet<Value *, 8> Succs;
5599 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5600 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00005601 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005602 Dest->removePredecessor(BB);
5603 IBI->removeDestination(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00005604 --i;
5605 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00005606 Changed = true;
5607 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005608 }
Chris Lattner25c3af32010-12-13 06:25:44 +00005609
5610 if (IBI->getNumDestinations() == 0) {
5611 // If the indirectbr has no successors, change it to unreachable.
5612 new UnreachableInst(IBI->getContext(), IBI);
5613 EraseTerminatorInstAndDCECond(IBI);
5614 return true;
5615 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005616
Chris Lattner25c3af32010-12-13 06:25:44 +00005617 if (IBI->getNumDestinations() == 1) {
5618 // If the indirectbr has one successor, change it to a direct branch.
5619 BranchInst::Create(IBI->getDestination(0), IBI);
5620 EraseTerminatorInstAndDCECond(IBI);
5621 return true;
5622 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005623
Chris Lattner25c3af32010-12-13 06:25:44 +00005624 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5625 if (SimplifyIndirectBrOnSelect(IBI, SI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005626 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005627 }
5628 return Changed;
5629}
5630
Philip Reames2b969d72015-03-24 22:28:45 +00005631/// Given an block with only a single landing pad and a unconditional branch
5632/// try to find another basic block which this one can be merged with. This
5633/// handles cases where we have multiple invokes with unique landing pads, but
5634/// a shared handler.
5635///
5636/// We specifically choose to not worry about merging non-empty blocks
5637/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
5638/// practice, the optimizer produces empty landing pad blocks quite frequently
5639/// when dealing with exception dense code. (see: instcombine, gvn, if-else
5640/// sinking in this file)
5641///
5642/// This is primarily a code size optimization. We need to avoid performing
5643/// any transform which might inhibit optimization (such as our ability to
5644/// specialize a particular handler via tail commoning). We do this by not
5645/// merging any blocks which require us to introduce a phi. Since the same
5646/// values are flowing through both blocks, we don't loose any ability to
5647/// specialize. If anything, we make such specialization more likely.
5648///
5649/// TODO - This transformation could remove entries from a phi in the target
5650/// block when the inputs in the phi are the same for the two blocks being
5651/// merged. In some cases, this could result in removal of the PHI entirely.
5652static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5653 BasicBlock *BB) {
5654 auto Succ = BB->getUniqueSuccessor();
5655 assert(Succ);
5656 // If there's a phi in the successor block, we'd likely have to introduce
5657 // a phi into the merged landing pad block.
5658 if (isa<PHINode>(*Succ->begin()))
5659 return false;
5660
5661 for (BasicBlock *OtherPred : predecessors(Succ)) {
5662 if (BB == OtherPred)
5663 continue;
5664 BasicBlock::iterator I = OtherPred->begin();
5665 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5666 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5667 continue;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00005668 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5669 ;
Philip Reames2b969d72015-03-24 22:28:45 +00005670 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5671 if (!BI2 || !BI2->isIdenticalTo(BI))
5672 continue;
5673
David Majnemer1efa23d2016-02-20 01:07:45 +00005674 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005675 // path instead and make ourselves dead.
5676 SmallSet<BasicBlock *, 16> Preds;
5677 Preds.insert(pred_begin(BB), pred_end(BB));
5678 for (BasicBlock *Pred : Preds) {
5679 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +00005680 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5681 "unexpected successor");
Philip Reames2b969d72015-03-24 22:28:45 +00005682 II->setUnwindDest(OtherPred);
5683 }
5684
5685 // The debug info in OtherPred doesn't cover the merged control flow that
5686 // used to go through BB. We need to delete it or update it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005687 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5688 Instruction &Inst = *I;
5689 I++;
Philip Reames2b969d72015-03-24 22:28:45 +00005690 if (isa<DbgInfoIntrinsic>(Inst))
5691 Inst.eraseFromParent();
5692 }
5693
5694 SmallSet<BasicBlock *, 16> Succs;
5695 Succs.insert(succ_begin(BB), succ_end(BB));
5696 for (BasicBlock *Succ : Succs) {
5697 Succ->removePredecessor(BB);
5698 }
5699
5700 IRBuilder<> Builder(BI);
5701 Builder.CreateUnreachable();
5702 BI->eraseFromParent();
5703 return true;
5704 }
5705 return false;
5706}
5707
Dehao Chenf6c00832016-05-18 19:44:21 +00005708bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5709 IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005710 BasicBlock *BB = BI->getParent();
Balaram Makamb05a5572017-07-19 08:53:34 +00005711 BasicBlock *Succ = BI->getSuccessor(0);
Andrew Trickf3cf1932012-08-29 21:46:36 +00005712
Manman Ren93ab6492012-09-20 22:37:36 +00005713 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5714 return true;
Reid Klecknerbca59d22016-05-02 19:43:22 +00005715
5716 // If the Terminator is the only non-phi instruction, simplify the block.
Sanjay Patelca146972017-09-19 20:58:14 +00005717 // If LoopHeader is provided, check if the block or its successor is a loop
5718 // header. (This is for early invocations before loop simplify and
Balaram Makamb05a5572017-07-19 08:53:34 +00005719 // vectorization to keep canonical loop forms for nested loops. These blocks
5720 // can be eliminated when the pass is invoked later in the back-end.)
5721 bool NeedCanonicalLoop =
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005722 Options.NeedCanonicalLoop &&
Balaram Makamb05a5572017-07-19 08:53:34 +00005723 (LoopHeaders && (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
Reid Klecknerbca59d22016-05-02 19:43:22 +00005724 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005725 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
Balaram Makamb05a5572017-07-19 08:53:34 +00005726 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00005727 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005728
Sanjay Patelca146972017-09-19 20:58:14 +00005729 // If the only instruction in the block is a seteq/setne comparison against a
5730 // constant, try to simplify the block.
Chris Lattner25c3af32010-12-13 06:25:44 +00005731 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5732 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5733 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5734 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005735 if (I->isTerminator() &&
Sanjay Patel4c33d522017-10-04 20:26:25 +00005736 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, Options))
Chris Lattner25c3af32010-12-13 06:25:44 +00005737 return true;
5738 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005739
Philip Reames2b969d72015-03-24 22:28:45 +00005740 // See if we can merge an empty landing pad block with another which is
5741 // equivalent.
5742 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00005743 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5744 ;
Dehao Chenf6c00832016-05-18 19:44:21 +00005745 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
Philip Reames2b969d72015-03-24 22:28:45 +00005746 return true;
5747 }
5748
Manman Rend33f4ef2012-06-13 05:43:29 +00005749 // If this basic block is ONLY a compare and a branch, and if a predecessor
5750 // branches to us and our successor, fold the comparison into the
5751 // predecessor and use logical operations to update the incoming value
5752 // for PHI nodes in common successor.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005753 if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005754 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005755 return false;
5756}
5757
James Molloy4de84dd2015-11-04 15:28:04 +00005758static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5759 BasicBlock *PredPred = nullptr;
5760 for (auto *P : predecessors(BB)) {
5761 BasicBlock *PPred = P->getSinglePredecessor();
5762 if (!PPred || (PredPred && PredPred != PPred))
5763 return nullptr;
5764 PredPred = PPred;
5765 }
5766 return PredPred;
5767}
Chris Lattner25c3af32010-12-13 06:25:44 +00005768
Devang Patela7ec47d2011-05-18 20:35:38 +00005769bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005770 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005771
Chris Lattner25c3af32010-12-13 06:25:44 +00005772 // Conditional branch
5773 if (isValueEqualityComparison(BI)) {
5774 // If we only have one predecessor, and if it is a branch on this value,
5775 // see if that predecessor totally determines the outcome of this
5776 // switch.
5777 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005778 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005779 return simplifyCFG(BB, TTI, Options) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005780
Chris Lattner25c3af32010-12-13 06:25:44 +00005781 // This block must be empty, except for the setcond inst, if it exists.
5782 // Ignore dbg intrinsics.
5783 BasicBlock::iterator I = BB->begin();
5784 // Ignore dbg intrinsics.
5785 while (isa<DbgInfoIntrinsic>(I))
5786 ++I;
5787 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005788 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005789 return simplifyCFG(BB, TTI, Options) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005790 } else if (&*I == cast<Instruction>(BI->getCondition())) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005791 ++I;
5792 // Ignore dbg intrinsics.
5793 while (isa<DbgInfoIntrinsic>(I))
5794 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005795 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005796 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005797 }
5798 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005799
Chris Lattner25c3af32010-12-13 06:25:44 +00005800 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005801 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005802 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005803
Chad Rosier4ab37c02016-05-06 14:25:14 +00005804 // If this basic block has a single dominating predecessor block and the
5805 // dominating block's condition implies BI's condition, we know the direction
5806 // of the BI branch.
5807 if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5808 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5809 if (PBI && PBI->isConditional() &&
Craig Topperdfd01ea2017-07-06 16:29:43 +00005810 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
5811 assert(PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB);
Chad Rosierdfd1de62017-08-01 20:18:54 +00005812 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Chad Rosier4ab37c02016-05-06 14:25:14 +00005813 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00005814 PBI->getCondition(), BI->getCondition(), DL, CondIsTrue);
Chad Rosier4ab37c02016-05-06 14:25:14 +00005815 if (Implication) {
5816 // Turn this into a branch on constant.
5817 auto *OldCond = BI->getCondition();
5818 ConstantInt *CI = *Implication
5819 ? ConstantInt::getTrue(BB->getContext())
5820 : ConstantInt::getFalse(BB->getContext());
5821 BI->setCondition(CI);
5822 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Sanjay Patel4c33d522017-10-04 20:26:25 +00005823 return simplifyCFG(BB, TTI, Options) | true;
Chad Rosier4ab37c02016-05-06 14:25:14 +00005824 }
5825 }
5826 }
5827
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005828 // If this basic block is ONLY a compare and a branch, and if a predecessor
5829 // branches to us and one of our successors, fold the comparison into the
5830 // predecessor and use logical operations to pick the right destination.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005831 if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005832 return simplifyCFG(BB, TTI, Options) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005833
Chris Lattner25c3af32010-12-13 06:25:44 +00005834 // We have a conditional branch to two blocks that are only reachable
5835 // from BI. We know that the condbr dominates the two blocks, so see if
5836 // there is any identical code in the "then" and "else" blocks. If so, we
5837 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005838 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5839 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005840 if (HoistThenElseCodeToIf(BI, TTI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005841 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005842 } else {
5843 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005844 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005845 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5846 if (Succ0TI->getNumSuccessors() == 1 &&
5847 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005848 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005849 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005850 }
Craig Topperf40110f2014-04-25 05:29:35 +00005851 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005852 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005853 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005854 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5855 if (Succ1TI->getNumSuccessors() == 1 &&
5856 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005857 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005858 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005859 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005860
Chris Lattner25c3af32010-12-13 06:25:44 +00005861 // If this is a branch on a phi node in the current block, thread control
5862 // through this block if any PHI node entries are constants.
5863 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5864 if (PN->getParent() == BI->getParent())
Sanjay Patel4c33d522017-10-04 20:26:25 +00005865 if (FoldCondBranchOnPHI(BI, DL, Options.AC))
5866 return simplifyCFG(BB, TTI, Options) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005867
Chris Lattner25c3af32010-12-13 06:25:44 +00005868 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005869 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5870 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005871 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005872 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005873 return simplifyCFG(BB, TTI, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005874
James Molloy4de84dd2015-11-04 15:28:04 +00005875 // Look for diamond patterns.
5876 if (MergeCondStores)
5877 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5878 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5879 if (PBI != BI && PBI->isConditional())
Alexey Bataev978e2e42017-08-29 20:06:24 +00005880 if (mergeConditionalStores(PBI, BI, DL))
Sanjay Patel4c33d522017-10-04 20:26:25 +00005881 return simplifyCFG(BB, TTI, Options) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005882
Chris Lattner25c3af32010-12-13 06:25:44 +00005883 return false;
5884}
5885
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005886/// Check if passing a value to an instruction will cause undefined behavior.
5887static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5888 Constant *C = dyn_cast<Constant>(V);
5889 if (!C)
5890 return false;
5891
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005892 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005893 return false;
5894
David Majnemer1fea77c2016-06-25 07:37:27 +00005895 if (C->isNullValue() || isa<UndefValue>(C)) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005896 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005897 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005898
5899 // Now make sure that there are no instructions in between that can alter
5900 // control flow (eg. calls)
Duncan P. N. Exon Smith0a12729f2016-08-16 23:57:56 +00005901 for (BasicBlock::iterator
5902 i = ++BasicBlock::iterator(I),
5903 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5904 i != UI; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005905 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005906 return false;
5907
5908 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5909 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5910 if (GEP->getPointerOperand() == I)
5911 return passingValueIsAlwaysUndefined(V, GEP);
5912
5913 // Look through bitcasts.
5914 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5915 return passingValueIsAlwaysUndefined(V, BC);
5916
Benjamin Kramer0655b782011-08-26 02:25:55 +00005917 // Load from null is undefined.
5918 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005919 if (!LI->isVolatile())
5920 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005921
Benjamin Kramer0655b782011-08-26 02:25:55 +00005922 // Store to null is undefined.
5923 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005924 if (!SI->isVolatile())
Dehao Chenf6c00832016-05-18 19:44:21 +00005925 return SI->getPointerAddressSpace() == 0 &&
5926 SI->getPointerOperand() == I;
David Majnemer1fea77c2016-06-25 07:37:27 +00005927
5928 // A call to null is undefined.
5929 if (auto CS = CallSite(Use))
5930 return CS.getCalledValue() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005931 }
5932 return false;
5933}
5934
5935/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005936/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005937static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5938 for (BasicBlock::iterator i = BB->begin();
5939 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5940 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5941 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5942 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5943 IRBuilder<> Builder(T);
5944 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5945 BB->removePredecessor(PHI->getIncomingBlock(i));
5946 // Turn uncoditional branches into unreachables and remove the dead
5947 // destination from conditional branches.
5948 if (BI->isUnconditional())
5949 Builder.CreateUnreachable();
5950 else
Dehao Chenf6c00832016-05-18 19:44:21 +00005951 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5952 : BI->getSuccessor(0));
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005953 BI->eraseFromParent();
5954 return true;
5955 }
5956 // TODO: SwitchInst.
5957 }
5958
5959 return false;
5960}
5961
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005962bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005963 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005964
Chris Lattnerd7beca32010-12-14 06:17:25 +00005965 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005966 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005967
Dan Gohman4a63fad2010-08-14 00:29:42 +00005968 // Remove basic blocks that have no predecessors (except the entry block)...
5969 // or that just have themself as a predecessor. These are unreachable.
Dehao Chenf6c00832016-05-18 19:44:21 +00005970 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005971 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005972 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5973 DeleteDeadBlock(BB);
5974 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005975 }
5976
Chris Lattner031340a2003-08-17 19:41:53 +00005977 // Check to see if we can constant propagate this terminator instruction
5978 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005979 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005980
Dan Gohman1a951062009-10-30 22:39:04 +00005981 // Check for and eliminate duplicate PHI nodes in this block.
5982 Changed |= EliminateDuplicatePHINodes(BB);
5983
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005984 // Check for and remove branches that will always cause undefined behavior.
5985 Changed |= removeUndefIntroducingPredecessor(BB);
5986
Chris Lattner2e3832d2010-12-13 05:10:48 +00005987 // Merge basic blocks into their predecessor if there is only one distinct
5988 // pred, and if there is only one distinct successor of the predecessor, and
5989 // if there are no PHI nodes.
Chris Lattner2e3832d2010-12-13 05:10:48 +00005990 if (MergeBlockIntoPredecessor(BB))
5991 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005992
Devang Patel15ad6762011-05-18 18:01:27 +00005993 IRBuilder<> Builder(BB);
5994
Dan Gohman20af5a02008-03-11 21:53:06 +00005995 // If there is a trivial two-entry PHI node in this basic block, and we can
5996 // eliminate it, do so now.
5997 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5998 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005999 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00006000
Devang Patela7ec47d2011-05-18 20:35:38 +00006001 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00006002 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00006003 if (BI->isUnconditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00006004 if (SimplifyUncondBranch(BI, Builder))
6005 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006006 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00006007 if (SimplifyCondBranch(BI, Builder))
6008 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006009 }
6010 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00006011 if (SimplifyReturn(RI, Builder))
6012 return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00006013 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00006014 if (SimplifyResume(RI, Builder))
6015 return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00006016 } else if (CleanupReturnInst *RI =
Dehao Chenf6c00832016-05-18 19:44:21 +00006017 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
6018 if (SimplifyCleanupReturn(RI))
6019 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006020 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00006021 if (SimplifySwitch(SI, Builder))
6022 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006023 } else if (UnreachableInst *UI =
Dehao Chenf6c00832016-05-18 19:44:21 +00006024 dyn_cast<UnreachableInst>(BB->getTerminator())) {
6025 if (SimplifyUnreachable(UI))
6026 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006027 } else if (IndirectBrInst *IBI =
Dehao Chenf6c00832016-05-18 19:44:21 +00006028 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
6029 if (SimplifyIndirectBr(IBI))
6030 return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00006031 }
6032
Chris Lattner031340a2003-08-17 19:41:53 +00006033 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00006034}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00006035
Sanjay Patel4c33d522017-10-04 20:26:25 +00006036bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6037 const SimplifyCFGOptions &Options,
Sanjay Patel0f9b4772017-09-27 14:54:16 +00006038 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
Sanjay Patel4c33d522017-10-04 20:26:25 +00006039 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
Sanjay Patel0f9b4772017-09-27 14:54:16 +00006040 Options)
Dehao Chenf6c00832016-05-18 19:44:21 +00006041 .run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00006042}