blob: 91a30088fa076cbb40bfb3c710ff62882ed24370 [file] [log] [blame]
Eugene Zelenkofa6434b2017-08-31 21:56:16 +00001//===- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop -------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-04-19 18:07:02 +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//
Chris Lattnerf48f7772004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
Xin Tongb7b08122017-04-23 17:36:25 +000011// to multiple loops. For example, it turns the left into the right code:
Chris Lattnerf48f7772004-04-19 18:07:02 +000012//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000029#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000031#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000034#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/CodeMetrics.h"
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +000036#include "llvm/Analysis/DivergenceAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Analysis/InstructionSimplify.h"
38#include "llvm/Analysis/LoopInfo.h"
39#include "llvm/Analysis/LoopPass.h"
40#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000041#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000042#include "llvm/Analysis/Utils/Local.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000043#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/CallSite.h"
46#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
48#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000049#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Function.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000051#include "llvm/IR/IRBuilder.h"
Xin Tongec6f90b2017-02-23 23:42:19 +000052#include "llvm/IR/InstrTypes.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000053#include "llvm/IR/Instruction.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/IR/Instructions.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000055#include "llvm/IR/IntrinsicInst.h"
56#include "llvm/IR/Intrinsics.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000057#include "llvm/IR/Module.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000058#include "llvm/IR/Type.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/IR/ValueHandle.h"
62#include "llvm/Pass.h"
63#include "llvm/Support/Casting.h"
Chris Lattner89762192006-02-09 20:15:48 +000064#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000065#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000066#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000067#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000068#include "llvm/Transforms/Utils/BasicBlockUtils.h"
69#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000070#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000071#include "llvm/Transforms/Utils/ValueMapper.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000072#include <algorithm>
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000073#include <cassert>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000074#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000075#include <set>
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000076#include <tuple>
77#include <utility>
78#include <vector>
79
Chris Lattnerf48f7772004-04-19 18:07:02 +000080using namespace llvm;
81
Chandler Carruth964daaa2014-04-22 02:55:47 +000082#define DEBUG_TYPE "loop-unswitch"
83
Chris Lattner79a42ac2006-12-19 21:40:18 +000084STATISTIC(NumBranches, "Number of branches unswitched");
85STATISTIC(NumSwitches, "Number of switches unswitched");
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +000086STATISTIC(NumGuards, "Number of guards unswitched");
Chris Lattner79a42ac2006-12-19 21:40:18 +000087STATISTIC(NumSelects , "Number of selects unswitched");
88STATISTIC(NumTrivial , "Number of unswitches that are trivial");
89STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000090STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000091
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000092// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000093// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000094static cl::opt<unsigned>
95Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000096 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000097
Dan Gohmand78c4002008-05-13 00:00:25 +000098namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000099
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000100 class LUAnalysisCache {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000101 using UnswitchedValsMap =
102 DenseMap<const SwitchInst *, SmallPtrSet<const Value *, 8>>;
103 using UnswitchedValsIt = UnswitchedValsMap::iterator;
Andrew Trick4104ed92012-04-10 05:14:37 +0000104
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000105 struct LoopProperties {
106 unsigned CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000107 unsigned WasUnswitchedCount;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000108 unsigned SizeEstimation;
109 UnswitchedValsMap UnswitchedVals;
110 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000111
112 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000113 // LoopProperties pointer for current loop for better performance.
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000114 using LoopPropsMap = std::map<const Loop *, LoopProperties>;
115 using LoopPropsMapIt = LoopPropsMap::iterator;
Andrew Trick4104ed92012-04-10 05:14:37 +0000116
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000117 LoopPropsMap LoopsProperties;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000118 UnswitchedValsMap *CurLoopInstructions = nullptr;
119 LoopProperties *CurrentLoopProperties = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000120
Mark Heffernan9b536a62015-06-23 18:26:50 +0000121 // A loop unswitching with an estimated cost above this threshold
122 // is not performed. MaxSize is turned into unswitching quota for
123 // the current loop, and reduced correspondingly, though note that
124 // the quota is returned by releaseMemory() when the loop has been
125 // processed, so that MaxSize will return to its previous
126 // value. So in most cases MaxSize will equal the Threshold flag
127 // when a new loop is processed. An exception to that is that
128 // MaxSize will have a smaller value while processing nested loops
129 // that were introduced due to loop unswitching of an outer loop.
130 //
131 // FIXME: The way that MaxSize works is subtle and depends on the
132 // pass manager processing loops and calling releaseMemory() in a
133 // specific order. It would be good to find a more straightforward
134 // way of doing what MaxSize does.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000135 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +0000136
Mark Heffernan9b536a62015-06-23 18:26:50 +0000137 public:
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000138 LUAnalysisCache() : MaxSize(Threshold) {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000139
Mark Heffernan9b536a62015-06-23 18:26:50 +0000140 // Analyze loop. Check its size, calculate is it possible to unswitch
141 // it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000142 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
143 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000144
Mark Heffernan9b536a62015-06-23 18:26:50 +0000145 // Clean all data related to given loop.
146 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000147
Mark Heffernan9b536a62015-06-23 18:26:50 +0000148 // Mark case value as unswitched.
149 // Since SI instruction can be partly unswitched, in order to avoid
150 // extra unswitching in cloned loops keep track all unswitched values.
151 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000152
Mark Heffernan9b536a62015-06-23 18:26:50 +0000153 // Check was this case value unswitched before or not.
154 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000155
Mark Heffernan9b536a62015-06-23 18:26:50 +0000156 // Returns true if another unswitching could be done within the cost
157 // threshold.
158 bool CostAllowsUnswitching();
Andrew Trick4104ed92012-04-10 05:14:37 +0000159
Mark Heffernan9b536a62015-06-23 18:26:50 +0000160 // Clone all loop-unswitch related loop properties.
161 // Redistribute unswitching quotas.
162 // Note, that new loop data is stored inside the VMap.
163 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
164 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000165 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000166
Chris Lattner2dd09db2009-09-02 06:11:42 +0000167 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000168 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000169 LPPassManager *LPM;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000170 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000171
Sanjay Patel956e29c2015-08-11 21:24:04 +0000172 // Used to check if second loop needs processing after
173 // RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000174 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000175
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000176 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000177
Devang Patel506310d2007-06-06 00:21:03 +0000178 bool OptimizeForSize;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000179 bool redoLoop = false;
Devang Patela69f9872007-10-05 22:29:34 +0000180
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000181 Loop *currentLoop = nullptr;
182 DominatorTree *DT = nullptr;
183 BasicBlock *loopHeader = nullptr;
184 BasicBlock *loopPreheader = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000185
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000186 bool SanitizeMemory;
187 LoopSafetyInfo SafetyInfo;
188
Devang Pateled50fb52008-07-02 01:44:29 +0000189 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000190 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000191 // loop, in that order.
192 std::vector<BasicBlock*> LoopBlocks;
193 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
194 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000195
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000196 bool hasBranchDivergence;
197
Chris Lattnerf48f7772004-04-19 18:07:02 +0000198 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000199 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000200
201 explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false)
202 : LoopPass(ID), OptimizeForSize(Os),
203 hasBranchDivergence(hasBranchDivergence) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000204 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000205 }
Devang Patel09f162c2007-05-01 21:15:47 +0000206
Craig Topper3e4c6972014-03-05 09:10:37 +0000207 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000208 bool processCurrentLoop();
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000209 bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000210
Chris Lattnerf48f7772004-04-19 18:07:02 +0000211 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000212 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000213 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000214 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000215 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000216 AU.addRequired<TargetTransformInfoWrapperPass>();
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000217 if (hasBranchDivergence)
218 AU.addRequired<DivergenceAnalysis>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000219 getLoopAnalysisUsage(AU);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000220 }
221
222 private:
Craig Topper3e4c6972014-03-05 09:10:37 +0000223 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000224 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000225 }
226
Devang Patele149d4e2008-07-02 01:18:13 +0000227 void initLoopData() {
228 loopHeader = currentLoop->getHeader();
229 loopPreheader = currentLoop->getLoopPreheader();
230 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000231
Chris Lattner559c8672008-04-21 00:25:49 +0000232 /// Split all of the edges from inside the loop to their exit blocks.
233 /// Update the appropriate Phi nodes as we do so.
Sanjay Patel41f3d952015-08-11 21:11:56 +0000234 void SplitExitEdges(Loop *L,
235 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000236
Chen Lic0f3a152015-07-22 05:26:29 +0000237 bool TryTrivialLoopUnswitch(bool &Changed);
238
Weiming Zhaof1abad52015-06-23 05:31:09 +0000239 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
240 TerminatorInst *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000241 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000242 BasicBlock *ExitBlock, TerminatorInst *TI);
243 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
244 TerminatorInst *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000245
246 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
247 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000248
249 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000250 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000251 BasicBlock *FalseDest,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000252 BranchInst *OldBranch,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000253 TerminatorInst *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000254
Devang Pateld4911982007-07-31 08:03:26 +0000255 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Xin Tongec6f90b2017-02-23 23:42:19 +0000256
257 /// Given that the Invariant is not equal to Val. Simplify instructions
258 /// in the loop.
259 Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
260 Constant *Val);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000261 };
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000262
263} // end anonymous namespace
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000264
265// Analyze loop. Check its size, calculate is it possible to unswitch
266// it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000267bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
268 AssumptionCache *AC) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000269 LoopPropsMapIt PropsIt;
270 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000271 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000272 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000273
Jakub Staszak27da1232013-08-06 17:03:42 +0000274 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000275
Jakub Staszak27da1232013-08-06 17:03:42 +0000276 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000277 // New loop.
278
279 // Limit the number of instructions to avoid causing significant code
280 // expansion, and the number of basic blocks, to avoid loops with
281 // large numbers of branches which cause loop unswitching to go crazy.
282 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000283
Hal Finkel57f03dd2014-09-07 13:49:57 +0000284 SmallPtrSet<const Value *, 32> EphValues;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000285 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000286
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000287 // FIXME: This is overly conservative because it does not take into
288 // consideration code simplification opportunities and code that can
289 // be shared by the resultant unswitched loops.
290 CodeMetrics Metrics;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000291 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
292 ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000293 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000294
Mark Heffernan9b536a62015-06-23 18:26:50 +0000295 Props.SizeEstimation = Metrics.NumInsts;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000296 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
Mark Heffernan9b536a62015-06-23 18:26:50 +0000297 Props.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000298 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000299
300 if (Metrics.notDuplicatable) {
301 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000302 << L->getHeader()->getName() << ", contents cannot be "
303 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000304 return false;
305 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000306 }
307
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000308 // Be careful. This links are good only before new loop addition.
309 CurrentLoopProperties = &Props;
310 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000311
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000312 return true;
313}
314
315// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000316void LUAnalysisCache::forgetLoop(const Loop *L) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000317 LoopPropsMapIt LIt = LoopsProperties.find(L);
318
319 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000320 LoopProperties &Props = LIt->second;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000321 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
322 Props.SizeEstimation;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000323 LoopsProperties.erase(LIt);
324 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000325
Craig Topperf40110f2014-04-25 05:29:35 +0000326 CurrentLoopProperties = nullptr;
327 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000328}
329
330// Mark case value as unswitched.
331// Since SI instruction can be partly unswitched, in order to avoid
332// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000333void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000334 (*CurLoopInstructions)[SI].insert(V);
335}
336
337// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000338bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000339 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000340}
341
Mark Heffernan9b536a62015-06-23 18:26:50 +0000342bool LUAnalysisCache::CostAllowsUnswitching() {
343 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
344}
345
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000346// Clone all loop-unswitch related loop properties.
347// Redistribute unswitching quotas.
348// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000349void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
350 const ValueToValueMapTy &VMap) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000351 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
352 LoopProperties &OldLoopProps = *CurrentLoopProperties;
353 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000354
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000355 // Reallocate "can-be-unswitched quota"
356
357 --OldLoopProps.CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000358 ++OldLoopProps.WasUnswitchedCount;
359 NewLoopProps.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000360 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
361 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
362 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000363
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000364 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000365
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000366 // Clone unswitched values info:
367 // for new loop switches we clone info about values that was
368 // already unswitched and has redundant successors.
369 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000370 const SwitchInst *OldInst = I->first;
371 Value *NewI = VMap.lookup(OldInst);
372 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000373 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000374
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000375 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
376 }
377}
378
Dan Gohmand78c4002008-05-13 00:00:25 +0000379char LoopUnswitch::ID = 0;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000380
Owen Anderson8ac477f2010-10-12 19:48:12 +0000381INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
382 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000383INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000384INITIALIZE_PASS_DEPENDENCY(LoopPass)
385INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000386INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000387INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
388 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000389
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000390Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
391 return new LoopUnswitch(Os, hasBranchDivergence);
Devang Patel506310d2007-06-06 00:21:03 +0000392}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000393
Xin Tong16b85a62017-02-27 18:00:13 +0000394/// Operator chain lattice.
395enum OperatorChain {
396 OC_OpChainNone, ///< There is no operator.
397 OC_OpChainOr, ///< There are only ORs.
398 OC_OpChainAnd, ///< There are only ANDs.
399 OC_OpChainMixed ///< There are ANDs and ORs.
400};
401
Sanjay Patel956e29c2015-08-11 21:24:04 +0000402/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
403/// an invariant piece, return the invariant. Otherwise, return null.
Xin Tong16b85a62017-02-27 18:00:13 +0000404//
405/// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
406/// mixed operator chain, as we can not reliably find a value which will simplify
407/// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
408/// to simplify the chain.
409///
410/// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
411/// simplify the condition itself to a loop variant condition, but at the
412/// cost of creating an entirely new loop.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000413static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
Xin Tong16b85a62017-02-27 18:00:13 +0000414 OperatorChain &ParentChain,
Sanjoy Dasd8500682016-06-25 01:14:19 +0000415 DenseMap<Value *, Value *> &Cache) {
416 auto CacheIt = Cache.find(Cond);
417 if (CacheIt != Cache.end())
418 return CacheIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000419
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000420 // We started analyze new instruction, increment scanned instructions counter.
421 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000422
Chris Lattner302240d2010-02-02 02:26:54 +0000423 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000424 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000425 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000426
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000427 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000428 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000429
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000430 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000431
Dan Gohman4d6149f2009-07-14 01:37:59 +0000432 // Hoist simple values out.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000433 if (L->makeLoopInvariant(Cond, Changed)) {
434 Cache[Cond] = Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000435 return Cond;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000436 }
Dan Gohman4d6149f2009-07-14 01:37:59 +0000437
Xin Tong16b85a62017-02-27 18:00:13 +0000438 // Walk up the operator chain to find partial invariant conditions.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000439 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
440 if (BO->getOpcode() == Instruction::And ||
441 BO->getOpcode() == Instruction::Or) {
Xin Tong16b85a62017-02-27 18:00:13 +0000442 // Given the previous operator, compute the current operator chain status.
443 OperatorChain NewChain;
444 switch (ParentChain) {
445 case OC_OpChainNone:
446 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
447 OC_OpChainOr;
448 break;
449 case OC_OpChainOr:
450 NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
451 OC_OpChainMixed;
452 break;
453 case OC_OpChainAnd:
454 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
455 OC_OpChainMixed;
456 break;
457 case OC_OpChainMixed:
458 NewChain = OC_OpChainMixed;
459 break;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000460 }
Xin Tong16b85a62017-02-27 18:00:13 +0000461
462 // If we reach a Mixed state, we do not want to keep walking up as we can not
463 // reliably find a value that will simplify the chain. With this check, we
464 // will return null on the first sight of mixed chain and the caller will
465 // either backtrack to find partial LIV in other operand or return null.
466 if (NewChain != OC_OpChainMixed) {
467 // Update the current operator chain type before we search up the chain.
468 ParentChain = NewChain;
469 // If either the left or right side is invariant, we can unswitch on this,
470 // which will cause the branch to go away in one loop and the condition to
471 // simplify in the other one.
472 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
473 ParentChain, Cache)) {
474 Cache[Cond] = LHS;
475 return LHS;
476 }
477 // We did not manage to find a partial LIV in operand(0). Backtrack and try
478 // operand(1).
479 ParentChain = NewChain;
480 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
481 ParentChain, Cache)) {
482 Cache[Cond] = RHS;
483 return RHS;
484 }
Sanjoy Dasd8500682016-06-25 01:14:19 +0000485 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000486 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000487
Sanjoy Dasd8500682016-06-25 01:14:19 +0000488 Cache[Cond] = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000489 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000490}
491
Xin Tong16b85a62017-02-27 18:00:13 +0000492/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
493/// an invariant piece, return the invariant along with the operator chain type.
494/// Otherwise, return null.
495static std::pair<Value *, OperatorChain> FindLIVLoopCondition(Value *Cond,
496 Loop *L,
497 bool &Changed) {
Sanjoy Dasd8500682016-06-25 01:14:19 +0000498 DenseMap<Value *, Value *> Cache;
Xin Tong16b85a62017-02-27 18:00:13 +0000499 OperatorChain OpChain = OC_OpChainNone;
500 Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache);
501
502 // In case we do find a LIV, it can not be obtained by walking up a mixed
503 // operator chain.
504 assert((!FCond || OpChain != OC_OpChainMixed) &&
505 "Do not expect a partial LIV with mixed operator chain");
506 return {FCond, OpChain};
Sanjoy Dasd8500682016-06-25 01:14:19 +0000507}
508
Devang Patel901a27d2007-03-07 00:26:10 +0000509bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000510 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000511 return false;
512
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000513 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
514 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000515 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000516 LPM = &LPM_Ref;
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000517 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Devang Patele149d4e2008-07-02 01:18:13 +0000518 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000519 Function *F = currentLoop->getHeader()->getParent();
Chen Li9f27fc02015-09-29 05:03:32 +0000520
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000521 SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
522 if (SanitizeMemory)
523 computeLoopSafetyInfo(&SafetyInfo, L);
524
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000525 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000526 do {
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000527 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000528 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000529 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000530 } while(redoLoop);
531
532 return Changed;
533}
534
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000535// Return true if the BasicBlock BB is unreachable from the loop header.
536// Return false, otherwise.
537bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
538 auto *Node = DT->getNode(BB)->getIDom();
539 BasicBlock *DomBB = Node->getBlock();
540 while (currentLoop->contains(DomBB)) {
541 BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
542
543 Node = DT->getNode(DomBB)->getIDom();
544 DomBB = Node->getBlock();
545
546 if (!BInst || !BInst->isConditional())
547 continue;
548
549 Value *Cond = BInst->getCondition();
550 if (!isa<ConstantInt>(Cond))
551 continue;
552
553 BasicBlock *UnreachableSucc =
554 Cond == ConstantInt::getTrue(Cond->getContext())
555 ? BInst->getSuccessor(1)
556 : BInst->getSuccessor(0);
557
558 if (DT->dominates(UnreachableSucc, BB))
559 return true;
560 }
561 return false;
562}
563
Wei Mifc0e2452017-07-25 23:37:17 +0000564/// FIXME: Remove this workaround when freeze related patches are done.
565/// LoopUnswitch and Equality propagation in GVN have discrepancy about
566/// whether branch on undef/poison has undefine behavior. Here it is to
567/// rule out some common cases that we found such discrepancy already
568/// causing problems. Detail could be found in PR31652. Note if the
569/// func returns true, it is unsafe. But if it is false, it doesn't mean
570/// it is necessarily safe.
571static bool EqualityPropUnSafe(Value &LoopCond) {
572 ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
573 if (!CI || !CI->isEquality())
574 return false;
575
576 Value *LHS = CI->getOperand(0);
577 Value *RHS = CI->getOperand(1);
578 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
579 return true;
580
581 auto hasUndefInPHI = [](PHINode &PN) {
582 for (Value *Opd : PN.incoming_values()) {
583 if (isa<UndefValue>(Opd))
584 return true;
585 }
586 return false;
587 };
588 PHINode *LPHI = dyn_cast<PHINode>(LHS);
589 PHINode *RPHI = dyn_cast<PHINode>(RHS);
590 if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
591 return true;
592
593 auto hasUndefInSelect = [](SelectInst &SI) {
594 if (isa<UndefValue>(SI.getTrueValue()) ||
595 isa<UndefValue>(SI.getFalseValue()))
596 return true;
597 return false;
598 };
599 SelectInst *LSI = dyn_cast<SelectInst>(LHS);
600 SelectInst *RSI = dyn_cast<SelectInst>(RHS);
601 if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
602 return true;
603 return false;
604}
605
Sanjay Patel956e29c2015-08-11 21:24:04 +0000606/// Do actual work and unswitch loop if possible and profitable.
Devang Patele149d4e2008-07-02 01:18:13 +0000607bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000608 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000609
610 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000611
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000612 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
613 if (!loopPreheader)
614 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000615
Andrew Trick4442bfe2012-04-10 05:14:42 +0000616 // Loops with indirectbr cannot be cloned.
617 if (!currentLoop->isSafeToClone())
618 return false;
619
620 // Without dedicated exits, splitting the exit edge may fail.
621 if (!currentLoop->hasDedicatedExits())
622 return false;
623
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000624 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000625
Chen Li567aa7a2015-10-14 19:47:43 +0000626 // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
Chandler Carruth705b1852015-01-31 03:43:40 +0000627 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000628 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000629 *currentLoop->getHeader()->getParent()),
630 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000631 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000632
Chen Lic0f3a152015-07-22 05:26:29 +0000633 // Try trivial unswitch first before loop over other basic blocks in the loop.
634 if (TryTrivialLoopUnswitch(Changed)) {
635 return true;
636 }
637
Philip Reames5c14ed82018-03-29 20:32:15 +0000638 // Do not do non-trivial unswitch while optimizing for size.
639 // FIXME: Use Function::optForSize().
640 if (OptimizeForSize ||
641 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
642 return false;
643
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000644 // Run through the instructions in the loop, keeping track of three things:
645 //
646 // - That we do not unswitch loops containing convergent operations, as we
647 // might be making them control dependent on the unswitch value when they
648 // were not before.
649 // FIXME: This could be refined to only bail if the convergent operation is
650 // not already control-dependent on the unswitch value.
651 //
652 // - That basic blocks in the loop contain invokes whose predecessor edges we
653 // cannot split.
654 //
655 // - The set of guard intrinsics encountered (these are non terminator
656 // instructions that are also profitable to be unswitched).
657
658 SmallVector<IntrinsicInst *, 4> Guards;
659
Owen Anderson2c9978b2015-10-09 18:40:20 +0000660 for (const auto BB : currentLoop->blocks()) {
Owen Anderson97ca0f32015-10-09 20:17:46 +0000661 for (auto &I : *BB) {
662 auto CS = CallSite(&I);
663 if (!CS) continue;
664 if (CS.hasFnAttr(Attribute::Convergent))
Owen Anderson2c9978b2015-10-09 18:40:20 +0000665 return false;
David Majnemer3d90bb72016-05-03 03:57:40 +0000666 if (auto *II = dyn_cast<InvokeInst>(&I))
667 if (!II->getUnwindDest()->canSplitPredecessors())
668 return false;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000669 if (auto *II = dyn_cast<IntrinsicInst>(&I))
670 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
671 Guards.push_back(II);
Owen Anderson2c9978b2015-10-09 18:40:20 +0000672 }
673 }
674
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000675 for (IntrinsicInst *Guard : Guards) {
676 Value *LoopCond =
Xin Tong16b85a62017-02-27 18:00:13 +0000677 FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed).first;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000678 if (LoopCond &&
679 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
680 // NB! Unswitching (if successful) could have erased some of the
681 // instructions in Guards leaving dangling pointers there. This is fine
682 // because we're returning now, and won't look at Guards again.
683 ++NumGuards;
684 return true;
685 }
686 }
687
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000688 // Loop over all of the basic blocks in the loop. If we find an interior
689 // block that is branching on a loop-invariant condition, we can unswitch this
690 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000691 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000692 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000693 TerminatorInst *TI = (*I)->getTerminator();
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000694
695 // Unswitching on a potentially uninitialized predicate is not
696 // MSan-friendly. Limit this to the cases when the original predicate is
697 // guaranteed to execute, to avoid creating a use-of-uninitialized-value
698 // in the code that did not have one.
699 // This is a workaround for the discrepancy between LLVM IR and MSan
700 // semantics. See PR28054 for more details.
701 if (SanitizeMemory &&
702 !isGuaranteedToExecute(*TI, DT, currentLoop, &SafetyInfo))
703 continue;
704
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000705 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000706 // Some branches may be rendered unreachable because of previous
707 // unswitching.
708 // Unswitch only those branches that are reachable.
709 if (isUnreachableDueToPreviousUnswitching(*I))
710 continue;
711
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000712 // If this isn't branching on an invariant condition, we can't unswitch
713 // it.
714 if (BI->isConditional()) {
715 // See if this, or some part of it, is loop invariant. If so, we can
716 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000717 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +0000718 currentLoop, Changed).first;
Wei Miebb93272017-08-29 21:45:11 +0000719 if (LoopCond && !EqualityPropUnSafe(*LoopCond) &&
720 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000721 ++NumBranches;
722 return true;
723 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000724 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000725 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Xin Tong16b85a62017-02-27 18:00:13 +0000726 Value *SC = SI->getCondition();
727 Value *LoopCond;
728 OperatorChain OpChain;
729 std::tie(LoopCond, OpChain) =
730 FindLIVLoopCondition(SC, currentLoop, Changed);
731
Andrew Trick4104ed92012-04-10 05:14:37 +0000732 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000733 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000734 // Find a value to unswitch on:
735 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000736 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000737 Constant *UnswitchVal = nullptr;
Xin Tong16b85a62017-02-27 18:00:13 +0000738 // Find a case value such that at least one case value is unswitched
739 // out.
740 if (OpChain == OC_OpChainAnd) {
741 // If the chain only has ANDs and the switch has a case value of 0.
742 // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
743 auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
744 if (BranchesInfo.isUnswitched(SI, AllZero))
745 continue;
746 // We are unswitching 0 out.
747 UnswitchVal = AllZero;
748 } else if (OpChain == OC_OpChainOr) {
749 // If the chain only has ORs and the switch has a case value of ~0.
750 // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
751 auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
752 if (BranchesInfo.isUnswitched(SI, AllOne))
753 continue;
754 // We are unswitching ~0 out.
755 UnswitchVal = AllOne;
756 } else {
757 assert(OpChain == OC_OpChainNone &&
758 "Expect to unswitch on trivial chain");
759 // Do not process same value again and again.
760 // At this point we have some cases already unswitched and
761 // some not yet unswitched. Let's find the first not yet unswitched one.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000762 for (auto Case : SI->cases()) {
763 Constant *UnswitchValCandidate = Case.getCaseValue();
Xin Tong16b85a62017-02-27 18:00:13 +0000764 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
765 UnswitchVal = UnswitchValCandidate;
766 break;
767 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000768 }
769 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000770
Chad Rosier3ba90a12011-12-22 21:10:46 +0000771 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000772 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000773
Devang Patele149d4e2008-07-02 01:18:13 +0000774 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000775 ++NumSwitches;
Xin Tong16b85a62017-02-27 18:00:13 +0000776 // In case of a full LIV, UnswitchVal is the value we unswitched out.
777 // In case of a partial LIV, we only unswitch when its an AND-chain
778 // or OR-chain. In both cases switch input value simplifies to
779 // UnswitchVal.
780 BranchesInfo.setUnswitched(SI, UnswitchVal);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000781 return true;
782 }
783 }
784 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000785
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000786 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000787 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000788 BBI != E; ++BBI)
789 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000790 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +0000791 currentLoop, Changed).first;
Andrew Trick4104ed92012-04-10 05:14:37 +0000792 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000793 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000794 ++NumSelects;
795 return true;
796 }
797 }
798 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000799 return Changed;
800}
801
Sanjay Patel956e29c2015-08-11 21:24:04 +0000802/// Check to see if all paths from BB exit the loop with no side effects
803/// (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000804///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000805/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000806/// exit through.
807///
808static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
809 BasicBlock *&ExitBB,
810 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000811 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000812 // Already visited. Without more analysis, this could indicate an infinite
813 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000814 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000815 }
816 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000817 // Otherwise, this is a loop exit, this is fine so long as this is the
818 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000819 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000820 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000821 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000822 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000823
Chris Lattnerbaddba42006-02-17 06:39:56 +0000824 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000825 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000826 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000827 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000828 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000829 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000830
831 // Okay, everything after this looks good, check to make sure that this block
832 // doesn't include any side effects.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000833 for (Instruction &I : *BB)
834 if (I.mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000835 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000836
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000837 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000838}
839
Sanjay Patel956e29c2015-08-11 21:24:04 +0000840/// Return true if the specified block unconditionally leads to an exit from
841/// the specified loop, and has no side-effects in the process. If so, return
842/// the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000843static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
844 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000845 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000846 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000847 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
848 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000849 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000850}
Chris Lattner6e263152006-02-10 02:30:37 +0000851
Sanjay Patel956e29c2015-08-11 21:24:04 +0000852/// We have found that we can unswitch currentLoop when LoopCond == Val to
853/// simplify the loop. If we decide that this is profitable,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000854/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000855bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
856 TerminatorInst *TI) {
Evan Chenged66db32010-04-03 02:23:43 +0000857 // Check to see if it would be profitable to unswitch current loop.
Mark Heffernan9b536a62015-06-23 18:26:50 +0000858 if (!BranchesInfo.CostAllowsUnswitching()) {
859 DEBUG(dbgs() << "NOT unswitching loop %"
860 << currentLoop->getHeader()->getName()
861 << " at non-trivial condition '" << *Val
862 << "' == " << *LoopCond << "\n"
863 << ". Cost too high.\n");
864 return false;
865 }
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000866 if (hasBranchDivergence &&
867 getAnalysis<DivergenceAnalysis>().isDivergent(LoopCond)) {
868 DEBUG(dbgs() << "NOT unswitching loop %"
869 << currentLoop->getHeader()->getName()
870 << " at non-trivial condition '" << *Val
871 << "' == " << *LoopCond << "\n"
872 << ". Condition is divergent.\n");
873 return false;
874 }
Evan Chenged66db32010-04-03 02:23:43 +0000875
Weiming Zhaof1abad52015-06-23 05:31:09 +0000876 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000877 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000878}
879
Sanjay Patel956e29c2015-08-11 21:24:04 +0000880/// Recursively clone the specified loop and all of its children,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000881/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000882static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000883 LoopInfo *LI, LPPassManager *LPM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +0000884 Loop &New = *LI->AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +0000885 if (PL)
886 PL->addChildLoop(&New);
887 else
888 LI->addTopLevelLoop(&New);
889 LPM->addLoop(New);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000890
891 // Add all of the blocks in L to the new loop.
892 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
893 I != E; ++I)
894 if (LI->getLoopFor(*I) == L)
Justin Bogner35e46cd2015-10-22 21:21:32 +0000895 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000896
897 // Add all of the subloops to the new loop.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000898 for (Loop *I : *L)
899 CloneLoop(I, &New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000900
Justin Bogner35e46cd2015-10-22 21:21:32 +0000901 return &New;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000902}
903
Sanjay Patel956e29c2015-08-11 21:24:04 +0000904/// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000905/// otherwise branch to FalseDest. Insert the code immediately before OldBranch
906/// and remove (but not erase!) it from the function.
Devang Patel3304e462007-06-28 00:49:00 +0000907void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
908 BasicBlock *TrueDest,
909 BasicBlock *FalseDest,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000910 BranchInst *OldBranch,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000911 TerminatorInst *TI) {
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000912 assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000913 // Insert a conditional branch on LIC to the two preheaders. The original
914 // code is the true version and the new code is the false version.
915 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000916 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000917 if (!isa<ConstantInt>(Val) ||
918 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000919 BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000920 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000921 // We want to enter the new loop when the condition is true.
922 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000923 Swapped = true;
924 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000925
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000926 // Old branch will be removed, so save its parent and successor to update the
927 // DomTree.
928 auto *OldBranchSucc = OldBranch->getSuccessor(0);
929 auto *OldBranchParent = OldBranch->getParent();
930
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000931 // Insert the new branch.
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000932 BranchInst *BI =
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000933 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000934 if (Swapped)
935 BI->swapProfMetadata();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000936
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000937 // Remove the old branch so there is only one branch at the end. This is
938 // needed to perform DomTree's internal DFS walk on the function's CFG.
939 OldBranch->removeFromParent();
940
941 // Inform the DT about the new branch.
942 if (DT) {
943 // First, add both successors.
944 SmallVector<DominatorTree::UpdateType, 3> Updates;
945 if (TrueDest != OldBranchParent)
946 Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
947 if (FalseDest != OldBranchParent)
948 Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
949 // If both of the new successors are different from the old one, inform the
950 // DT that the edge was deleted.
951 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
952 Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
953 }
954
955 DT->applyUpdates(Updates);
956 }
957
Dan Gohman3ddbc242009-09-08 15:45:00 +0000958 // If either edge is critical, split it. This helps preserve LoopSimplify
959 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000960 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000961 SplitCriticalEdge(BI, 0, Options);
962 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000963}
964
Sanjay Patel956e29c2015-08-11 21:24:04 +0000965/// Given a loop that has a trivial unswitchable condition in it (a cond branch
966/// from its header block to its latch block, where the path through the loop
967/// that doesn't execute its body has no side-effects), unswitch it. This
968/// doesn't involve any code duplication, just moving the conditional branch
969/// outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000970void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
971 BasicBlock *ExitBlock,
972 TerminatorInst *TI) {
David Greened9c355d2010-01-05 01:27:04 +0000973 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Weiming Zhaof1abad52015-06-23 05:31:09 +0000974 << loopHeader->getName() << " [" << L->getBlocks().size()
975 << " blocks] in Function "
976 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
977 << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000978
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000979 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000980 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000981 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000982 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000983
984 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000985 // to branch to: this is the exit block out of the loop that we should
986 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000987
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000988 // Split this block now, so that the loop maintains its exit block, and so
989 // that the jump from the preheader can execute the contents of the exit block
990 // without actually branching to it (the exit block should be dominated by the
991 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000992 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000993 BasicBlock *NewExit = SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000994
995 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000996 // insert the new conditional branch.
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000997 auto *OldBranch = dyn_cast<BranchInst>(loopPreheader->getTerminator());
998 assert(OldBranch && "Failed to split the preheader");
999 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1000 LPM->deleteSimpleAnalysisValue(OldBranch, L);
1001
1002 // EmitPreheaderBranchOnCondition removed the OldBranch from the function.
1003 // Delete it, as it is no longer needed.
1004 delete OldBranch;
Chris Lattnered7a67b2006-02-10 01:24:09 +00001005
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001006 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +00001007 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +00001008
Chris Lattnered7a67b2006-02-10 01:24:09 +00001009 // Now that we know that the loop is never entered when this condition is a
1010 // particular value, rewrite the loop with this info. We know that this will
1011 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001012 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +00001013 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +00001014}
1015
Sanjay Patel41f3d952015-08-11 21:11:56 +00001016/// Check if the first non-constant condition starting from the loop header is
1017/// a trivial unswitch condition: that is, a condition controls whether or not
1018/// the loop does anything at all. If it is a trivial condition, unswitching
1019/// produces no code duplications (equivalently, it produces a simpler loop and
1020/// a new empty loop, which gets deleted). Therefore always unswitch trivial
1021/// condition.
Chen Lic0f3a152015-07-22 05:26:29 +00001022bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
Chen Li145c2f52015-07-25 03:21:06 +00001023 BasicBlock *CurrentBB = currentLoop->getHeader();
1024 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
1025 LLVMContext &Context = CurrentBB->getContext();
Chen Lic0f3a152015-07-22 05:26:29 +00001026
Chen Li145c2f52015-07-25 03:21:06 +00001027 // If loop header has only one reachable successor (currently via an
1028 // unconditional branch or constant foldable conditional branch, but
1029 // should also consider adding constant foldable switch instruction in
1030 // future), we should keep looking for trivial condition candidates in
1031 // the successor as well. An alternative is to constant fold conditions
1032 // and merge successors into loop header (then we only need to check header's
1033 // terminator). The reason for not doing this in LoopUnswitch pass is that
1034 // it could potentially break LoopPassManager's invariants. Folding dead
1035 // branches could either eliminate the current loop or make other loops
Sanjay Patel41f3d952015-08-11 21:11:56 +00001036 // unreachable. LCSSA form might also not be preserved after deleting
1037 // branches. The following code keeps traversing loop header's successors
1038 // until it finds the trivial condition candidate (condition that is not a
1039 // constant). Since unswitching generates branches with constant conditions,
1040 // this scenario could be very common in practice.
Chen Li145c2f52015-07-25 03:21:06 +00001041 SmallSet<BasicBlock*, 8> Visited;
1042
1043 while (true) {
1044 // If we exit loop or reach a previous visited block, then
1045 // we can not reach any trivial condition candidates (unfoldable
1046 // branch instructions or switch instructions) and no unswitch
1047 // can happen. Exit and return false.
1048 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
Chen Lic0f3a152015-07-22 05:26:29 +00001049 return false;
1050
Chen Li145c2f52015-07-25 03:21:06 +00001051 // Check if this loop will execute any side-effecting instructions (e.g.
1052 // stores, calls, volatile loads) in the part of the loop that the code
1053 // *would* execute. Check the header first.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001054 for (Instruction &I : *CurrentBB)
1055 if (I.mayHaveSideEffects())
Chen Li145c2f52015-07-25 03:21:06 +00001056 return false;
1057
Chen Li145c2f52015-07-25 03:21:06 +00001058 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1059 if (BI->isUnconditional()) {
1060 CurrentBB = BI->getSuccessor(0);
1061 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
1062 CurrentBB = BI->getSuccessor(0);
1063 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
1064 CurrentBB = BI->getSuccessor(1);
1065 } else {
Sanjay Patel41f3d952015-08-11 21:11:56 +00001066 // Found a trivial condition candidate: non-foldable conditional branch.
Chen Li145c2f52015-07-25 03:21:06 +00001067 break;
1068 }
Xin Tonge5f8d642017-01-27 01:42:20 +00001069 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1070 // At this point, any constant-foldable instructions should have probably
1071 // been folded.
1072 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
1073 if (!Cond)
1074 break;
1075 // Find the target block we are definitely going to.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001076 CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
Karl-Johan Karlsson38cbf582017-02-14 07:31:36 +00001077 } else {
Xin Tonge5f8d642017-01-27 01:42:20 +00001078 // We do not understand these terminator instructions.
Chen Li145c2f52015-07-25 03:21:06 +00001079 break;
1080 }
1081
1082 CurrentTerm = CurrentBB->getTerminator();
1083 }
1084
Chen Lic0f3a152015-07-22 05:26:29 +00001085 // CondVal is the condition that controls the trivial condition.
1086 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1087 Constant *CondVal = nullptr;
1088 BasicBlock *LoopExitBB = nullptr;
1089
Chen Li145c2f52015-07-25 03:21:06 +00001090 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +00001091 // If this isn't branching on an invariant condition, we can't unswitch it.
1092 if (!BI->isConditional())
1093 return false;
1094
1095 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +00001096 currentLoop, Changed).first;
Chen Lic0f3a152015-07-22 05:26:29 +00001097
1098 // Unswitch only if the trivial condition itself is an LIV (not
1099 // partial LIV which could occur in and/or)
1100 if (!LoopCond || LoopCond != BI->getCondition())
1101 return false;
1102
1103 // Check to see if a successor of the branch is guaranteed to
1104 // exit through a unique exit block without having any
1105 // side-effects. If so, determine the value of Cond that causes
1106 // it to do this.
1107 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1108 BI->getSuccessor(0)))) {
1109 CondVal = ConstantInt::getTrue(Context);
1110 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1111 BI->getSuccessor(1)))) {
1112 CondVal = ConstantInt::getFalse(Context);
1113 }
1114
Sanjay Patel41f3d952015-08-11 21:11:56 +00001115 // If we didn't find a single unique LoopExit block, or if the loop exit
1116 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +00001117 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1118 return false; // Can't handle this.
1119
Wei Mifc0e2452017-07-25 23:37:17 +00001120 if (EqualityPropUnSafe(*LoopCond))
1121 return false;
1122
Sanjay Patel41f3d952015-08-11 21:11:56 +00001123 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1124 CurrentTerm);
Chen Lic0f3a152015-07-22 05:26:29 +00001125 ++NumBranches;
1126 return true;
Chen Li145c2f52015-07-25 03:21:06 +00001127 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +00001128 // If this isn't switching on an invariant condition, we can't unswitch it.
1129 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +00001130 currentLoop, Changed).first;
Chen Lic0f3a152015-07-22 05:26:29 +00001131
1132 // Unswitch only if the trivial condition itself is an LIV (not
1133 // partial LIV which could occur in and/or)
1134 if (!LoopCond || LoopCond != SI->getCondition())
1135 return false;
1136
1137 // Check to see if a successor of the switch is guaranteed to go to the
1138 // latch block or exit through a one exit block without having any
1139 // side-effects. If so, determine the value of Cond that causes it to do
1140 // this.
1141 // Note that we can't trivially unswitch on the default case or
1142 // on already unswitched cases.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001143 for (auto Case : SI->cases()) {
Chen Lic0f3a152015-07-22 05:26:29 +00001144 BasicBlock *LoopExitCandidate;
Chandler Carruth927d8e62017-04-12 07:27:28 +00001145 if ((LoopExitCandidate =
1146 isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
Chen Lic0f3a152015-07-22 05:26:29 +00001147 // Okay, we found a trivial case, remember the value that is trivial.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001148 ConstantInt *CaseVal = Case.getCaseValue();
Chen Lic0f3a152015-07-22 05:26:29 +00001149
1150 // Check that it was not unswitched before, since already unswitched
1151 // trivial vals are looks trivial too.
1152 if (BranchesInfo.isUnswitched(SI, CaseVal))
1153 continue;
1154 LoopExitBB = LoopExitCandidate;
1155 CondVal = CaseVal;
1156 break;
1157 }
1158 }
1159
Sanjay Patel41f3d952015-08-11 21:11:56 +00001160 // If we didn't find a single unique LoopExit block, or if the loop exit
1161 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +00001162 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1163 return false; // Can't handle this.
1164
Sanjay Patel41f3d952015-08-11 21:11:56 +00001165 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1166 nullptr);
Xin Tong16b85a62017-02-27 18:00:13 +00001167
1168 // We are only unswitching full LIV.
1169 BranchesInfo.setUnswitched(SI, CondVal);
Chen Lic0f3a152015-07-22 05:26:29 +00001170 ++NumSwitches;
1171 return true;
1172 }
1173 return false;
1174}
1175
Sanjay Patel956e29c2015-08-11 21:24:04 +00001176/// Split all of the edges from inside the loop to their exit blocks.
1177/// Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +00001178void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +00001179 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +00001180
Chris Lattnered7a67b2006-02-10 01:24:09 +00001181 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001182 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +00001183 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1184 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +00001185
Nick Lewycky61158242011-06-03 06:27:15 +00001186 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1187 // general, if we call it on all predecessors of all exits then it does.
Chandler Carruth96ada252015-07-22 09:52:54 +00001188 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
Philip Reames9198b332015-01-28 23:06:47 +00001189 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +00001190 }
Devang Patele192e3252007-10-03 21:16:08 +00001191}
1192
Sanjay Patel956e29c2015-08-11 21:24:04 +00001193/// We determined that the loop is profitable to unswitch when LIC equal Val.
1194/// Split it into loop versions and test the condition outside of either loop.
1195/// Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +00001196void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +00001197 Loop *L, TerminatorInst *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +00001198 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +00001199 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001200 << loopHeader->getName() << " [" << L->getBlocks().size()
1201 << " blocks] in Function " << F->getName()
1202 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +00001203
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001204 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1205 SEWP->getSE().forgetLoop(L);
Cameron Zwarich99de19b2011-02-11 06:08:28 +00001206
Devang Pateled50fb52008-07-02 01:44:29 +00001207 LoopBlocks.clear();
1208 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +00001209
1210 // First step, split the preheader and exit blocks, and add these blocks to
1211 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +00001212 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +00001213 LoopBlocks.push_back(NewPreheader);
1214
1215 // We want the loop to come after the preheader, but before the exit blocks.
1216 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1217
1218 SmallVector<BasicBlock*, 8> ExitBlocks;
1219 L->getUniqueExitBlocks(ExitBlocks);
1220
1221 // Split all of the edges from inside the loop to their exit blocks. Update
1222 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +00001223 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +00001224
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001225 // The exit blocks may have been changed due to edge splitting, recompute.
1226 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +00001227 L->getUniqueExitBlocks(ExitBlocks);
1228
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001229 // Add exit blocks to the loop blocks.
1230 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001231
1232 // Next step, clone all of the basic blocks that make up the loop (including
1233 // the loop preheader and exit blocks), keeping track of the mapping between
1234 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001235 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +00001236 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001237 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001238 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +00001239
Evan Chengba930442010-04-05 21:16:25 +00001240 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001241 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +00001242 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001243 }
1244
1245 // Splice the newly inserted blocks into the function right before the
1246 // original preheader.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001247 F->getBasicBlockList().splice(NewPreheader->getIterator(),
1248 F->getBasicBlockList(),
1249 NewBlocks[0]->getIterator(), F->end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001250
1251 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001252 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001253
1254 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1255 // Probably clone more loop-unswitch related loop properties.
1256 BranchesInfo.cloneData(NewLoop, L, VMap);
1257
Chris Lattnerf1b15162006-02-10 23:26:14 +00001258 Loop *ParentLoop = L->getParentLoop();
1259 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +00001260 // Make sure to add the cloned preheader and exit blocks to the parent loop
1261 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +00001262 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001263 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001264
Chris Lattnerf1b15162006-02-10 23:26:14 +00001265 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001266 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +00001267 // The new exit block should be in the same loop as the old one.
1268 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +00001269 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +00001270
Chris Lattnerf1b15162006-02-10 23:26:14 +00001271 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1272 "Exit block should have been split to have one successor!");
1273 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +00001274
Chris Lattnerf1b15162006-02-10 23:26:14 +00001275 // If the successor of the exit block had PHI nodes, add an entry for
1276 // NewExit.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001277 for (PHINode &PN : ExitSucc->phis()) {
1278 Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +00001279 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001280 if (It != VMap.end()) V = It->second;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001281 PN.addIncoming(V, NewExit);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001282 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001283
1284 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +00001285 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001286 &*ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +00001287
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001288 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1289 I != E; ++I) {
1290 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +00001291 LandingPadInst *LPI = BB->getLandingPadInst();
1292 LPI->replaceAllUsesWith(PN);
1293 PN->addIncoming(LPI, BB);
1294 }
1295 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001296 }
1297
1298 // Rewrite the code to refer to itself.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001299 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1300 for (Instruction &I : *NewBlocks[i]) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001301 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001302 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001303 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1304 if (II->getIntrinsicID() == Intrinsic::assume)
1305 AC->registerAssumption(II);
1306 }
1307 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001308
Chris Lattnerf48f7772004-04-19 18:07:02 +00001309 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +00001310 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001311 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +00001312 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +00001313
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001314 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +00001315 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1316 TI);
Devang Pateld4911982007-07-31 08:03:26 +00001317 LPM->deleteSimpleAnalysisValue(OldBR, L);
Jakub Kuderskie35a4492017-08-17 16:45:35 +00001318
1319 // The OldBr was replaced by a new one and removed (but not erased) by
1320 // EmitPreheaderBranchOnCondition. It is no longer needed, so delete it.
1321 delete OldBR;
Devang Patela8823282007-08-02 15:25:57 +00001322
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001323 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +00001324 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001325
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001326 // Keep a WeakTrackingVH holding onto LIC. If the first call to
1327 // RewriteLoopBody
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001328 // deletes the instruction (for example by simplifying a PHI that feeds into
1329 // the condition that we're unswitching on), we don't rewrite the second
1330 // iteration.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001331 WeakTrackingVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +00001332
Chris Lattnerf48f7772004-04-19 18:07:02 +00001333 // Now we rewrite the original code to know that the condition is true and the
1334 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +00001335 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +00001336
Chris Lattner5814d9d92010-04-20 05:09:16 +00001337 // It's possible that simplifying one loop could cause the other to be
1338 // changed to another value or a constant. If its a constant, don't simplify
1339 // it.
1340 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1341 LICHandle && !isa<Constant>(LICHandle))
1342 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001343}
1344
Sanjay Patel956e29c2015-08-11 21:24:04 +00001345/// Remove all instances of I from the worklist vector specified.
Andrew Trick4104ed92012-04-10 05:14:37 +00001346static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +00001347 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +00001348
1349 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1350 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001351}
1352
Sanjay Patel956e29c2015-08-11 21:24:04 +00001353/// When we find that I really equals V, remove I from the
Chris Lattner6fd13622006-02-17 00:31:07 +00001354/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +00001355static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +00001356 std::vector<Instruction*> &Worklist,
1357 Loop *L, LPPassManager *LPM) {
Davide Italianoe27cb872017-04-28 21:30:50 +00001358 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
Chris Lattner6fd13622006-02-17 00:31:07 +00001359
1360 // Add uses to the worklist, which may be dead now.
1361 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1362 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1363 Worklist.push_back(Use);
1364
1365 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001366 for (User *U : I->users())
1367 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +00001368 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001369 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001370 I->replaceAllUsesWith(V);
Davide Italiano534e3142017-04-29 00:12:18 +00001371 if (!I->mayHaveSideEffects())
1372 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001373 ++NumSimplify;
1374}
1375
Sanjay Patel956e29c2015-08-11 21:24:04 +00001376/// We know either that the value LIC has the value specified by Val in the
1377/// specified loop, or we know it does NOT have that value.
1378/// Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001379void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001380 Constant *Val,
1381 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001382 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001383
Chris Lattnerf48f7772004-04-19 18:07:02 +00001384 // FIXME: Support correlated properties, like:
1385 // for (...)
1386 // if (li1 < li2)
1387 // ...
1388 // if (li1 > li2)
1389 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001390
Chris Lattner6e263152006-02-10 02:30:37 +00001391 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1392 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001393 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001394 LLVMContext &Context = Val->getContext();
1395
Chris Lattner6fd13622006-02-17 00:31:07 +00001396 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1397 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001398 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001399 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001400 Value *Replacement;
1401 if (IsEqual)
1402 Replacement = Val;
1403 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001404 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001405 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001406
Chandler Carruthcdf47882014-03-09 03:16:01 +00001407 for (User *U : LIC->users()) {
1408 Instruction *UI = dyn_cast<Instruction>(U);
1409 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001410 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001411 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001412 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001413
Benjamin Kramer135f7352016-06-26 12:28:59 +00001414 for (Instruction *UI : Worklist)
1415 UI->replaceUsesOfWith(LIC, Replacement);
Andrew Trick4104ed92012-04-10 05:14:37 +00001416
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001417 SimplifyCode(Worklist, L);
1418 return;
1419 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001420
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001421 // Otherwise, we don't know the precise value of LIC, but we do know that it
1422 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1423 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001424 for (User *U : LIC->users()) {
1425 Instruction *UI = dyn_cast<Instruction>(U);
1426 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001427 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001428
Xin Tongec6f90b2017-02-23 23:42:19 +00001429 // At this point, we know LIC is definitely not Val. Try to use some simple
1430 // logic to simplify the user w.r.t. to the context.
1431 if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1432 if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1433 // This in-loop instruction has been simplified w.r.t. its context,
1434 // i.e. LIC != Val, make sure we propagate its replacement value to
1435 // all its users.
Xin Tongf51d8042017-02-24 01:43:36 +00001436 //
1437 // We can not yet delete UI, the LIC user, yet, because that would invalidate
1438 // the LIC->users() iterator !. However, we can make this instruction
1439 // dead by replacing all its users and push it onto the worklist so that
1440 // it can be properly deleted and its operands simplified.
1441 UI->replaceAllUsesWith(Replacement);
Xin Tongec6f90b2017-02-23 23:42:19 +00001442 }
1443 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001444
Xin Tong01feb292017-02-28 03:32:41 +00001445 // This is a LIC user, push it into the worklist so that SimplifyCode can
1446 // attempt to simplify it.
Xin Tongec6f90b2017-02-23 23:42:19 +00001447 Worklist.push_back(UI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001448
1449 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001450 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001451 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001452
Xin Tong16b85a62017-02-27 18:00:13 +00001453 // NOTE: if a case value for the switch is unswitched out, we record it
1454 // after the unswitch finishes. We can not record it here as the switch
1455 // is not a direct user of the partial LIV.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001456 SwitchInst::CaseHandle DeadCase =
1457 *SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001458 // Default case is live for multiple values.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001459 if (DeadCase == *SI->case_default())
1460 continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001461
1462 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001463 // successor if they become single-entry, those PHI nodes may
1464 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001465
Evan Cheng1b55f562011-05-24 23:12:57 +00001466 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001467 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001468 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001469
Nick Lewycky61158242011-06-03 06:27:15 +00001470 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001471 // If the DeadCase successor dominates the loop latch, then the
1472 // transformation isn't safe since it will delete the sole predecessor edge
1473 // to the latch.
1474 if (Latch && DT->dominates(SISucc, Latch))
1475 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001476
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001477 // FIXME: This is a hack. We need to keep the successor around
1478 // and hooked up so as to preserve the loop structure, because
1479 // trying to update it is complicated. So instead we preserve the
1480 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001481 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001482 // Compute the successors instead of relying on the return value
1483 // of SplitEdge, since it may have split the switch successor
1484 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001485 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001486 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1487 // Create an "unreachable" destination.
1488 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1489 Switch->getParent(),
1490 OldSISucc);
1491 new UnreachableInst(Context, Abort);
1492 // Force the new case destination to branch to the "unreachable"
1493 // block while maintaining a (dead) CFG edge to the old block.
1494 NewSISucc->getTerminator()->eraseFromParent();
1495 BranchInst::Create(Abort, OldSISucc,
1496 ConstantInt::getTrue(Context), NewSISucc);
1497 // Release the PHI operands for this edge.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001498 for (PHINode &PN : NewSISucc->phis())
1499 PN.setIncomingValue(PN.getBasicBlockIndex(Switch),
1500 UndefValue::get(PN.getType()));
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001501 // Tell the domtree about the new block. We don't fully update the
1502 // domtree here -- instead we force it to do a full recomputation
1503 // after the pass is complete -- but we do need to inform it of
1504 // new blocks.
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +00001505 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001506 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001507
Devang Pateld4911982007-07-31 08:03:26 +00001508 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001509}
1510
Sanjay Patel956e29c2015-08-11 21:24:04 +00001511/// Now that we have simplified some instructions in the loop, walk over it and
1512/// constant prop, dce, and fold control flow where possible. Note that this is
1513/// effectively a very simple loop-structure-aware optimizer. During processing
1514/// of this loop, L could very well be deleted, so it must not be used.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001515///
1516/// FIXME: When the loop optimizer is more mature, separate this out to a new
1517/// pass.
1518///
Devang Pateld4911982007-07-31 08:03:26 +00001519void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001520 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001521 while (!Worklist.empty()) {
1522 Instruction *I = Worklist.back();
1523 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001524
Chris Lattner6fd13622006-02-17 00:31:07 +00001525 // Simple DCE.
1526 if (isInstructionTriviallyDead(I)) {
Davide Italiano0aaa96a2017-04-29 00:18:26 +00001527 DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001528
Chris Lattner6fd13622006-02-17 00:31:07 +00001529 // Add uses to the worklist, which may be dead now.
1530 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1531 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1532 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001533 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001534 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001535 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001536 ++NumSimplify;
1537 continue;
1538 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001539
Chris Lattner66e809a2010-04-20 05:33:18 +00001540 // See if instruction simplification can hack this up. This is common for
1541 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001542 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001543 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001544 if (LI->replacementPreservesLCSSAForm(I, V)) {
1545 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1546 continue;
1547 }
1548
Chris Lattner6fd13622006-02-17 00:31:07 +00001549 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001550 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001551 if (BI->isUnconditional()) {
1552 // If BI's parent is the only pred of the successor, fold the two blocks
1553 // together.
1554 BasicBlock *Pred = BI->getParent();
1555 BasicBlock *Succ = BI->getSuccessor(0);
1556 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1557 if (!SinglePred) continue; // Nothing to do.
1558 assert(SinglePred == Pred && "CFG broken");
1559
Andrew Trick4104ed92012-04-10 05:14:37 +00001560 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001561 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001562
Chris Lattner6fd13622006-02-17 00:31:07 +00001563 // Resolve any single entry PHI nodes in Succ.
1564 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001565 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001566
Jay Foad61ea0e42011-06-23 09:09:15 +00001567 // If Succ has any successors with PHI nodes, update them to have
1568 // entries coming from Pred instead of Succ.
1569 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001570
Chris Lattner6fd13622006-02-17 00:31:07 +00001571 // Move all of the successor contents from Succ to Pred.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001572 Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
1573 Succ->begin(), Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001574 LPM->deleteSimpleAnalysisValue(BI, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001575 RemoveFromWorklist(BI, Worklist);
Xin Tong3caaa362017-01-06 21:49:08 +00001576 BI->eraseFromParent();
Andrew Trick4104ed92012-04-10 05:14:37 +00001577
Chris Lattner6fd13622006-02-17 00:31:07 +00001578 // Remove Succ from the loop tree.
1579 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001580 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001581 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001582 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001583 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001584 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001585
Chris Lattner66e809a2010-04-20 05:33:18 +00001586 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001587 }
1588 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001589}
Xin Tongec6f90b2017-02-23 23:42:19 +00001590
1591/// Simple simplifications we can do given the information that Cond is
1592/// definitely not equal to Val.
1593Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
1594 Value *Invariant,
1595 Constant *Val) {
1596 // icmp eq cond, val -> false
1597 ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1598 if (CI && CI->isEquality()) {
1599 Value *Op0 = CI->getOperand(0);
1600 Value *Op1 = CI->getOperand(1);
1601 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1602 LLVMContext &Ctx = Inst->getContext();
1603 if (CI->getPredicate() == CmpInst::ICMP_EQ)
1604 return ConstantInt::getFalse(Ctx);
1605 else
1606 return ConstantInt::getTrue(Ctx);
1607 }
1608 }
1609
1610 // FIXME: there may be other opportunities, e.g. comparison with floating
1611 // point, or Invariant - Val != 0, etc.
1612 return nullptr;
1613}