blob: cd49f51283fa8f4a85f3e7be9d65125108c51406 [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/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000033#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/InstructionSimplify.h"
Alina Sbirleaa4961432018-09-11 19:19:21 +000036#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Analysis/LoopInfo.h"
Alina Sbirleaa4961432018-09-11 19:19:21 +000038#include "llvm/Analysis/LoopIterator.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Analysis/LoopPass.h"
Alina Sbirleaa4961432018-09-11 19:19:21 +000040#include "llvm/Analysis/MemorySSA.h"
41#include "llvm/Analysis/MemorySSAUpdater.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000043#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000044#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/CallSite.h"
47#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000052#include "llvm/IR/IRBuilder.h"
Xin Tongec6f90b2017-02-23 23:42:19 +000053#include "llvm/IR/InstrTypes.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000054#include "llvm/IR/Instruction.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000055#include "llvm/IR/Instructions.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000056#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/Intrinsics.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000058#include "llvm/IR/Module.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000059#include "llvm/IR/Type.h"
60#include "llvm/IR/User.h"
61#include "llvm/IR/Value.h"
62#include "llvm/IR/ValueHandle.h"
63#include "llvm/Pass.h"
64#include "llvm/Support/Casting.h"
Chris Lattner89762192006-02-09 20:15:48 +000065#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000066#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000067#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000068#include "llvm/Transforms/Scalar.h"
Alina Sbirleaa4961432018-09-11 19:19:21 +000069#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Transforms/Utils/BasicBlockUtils.h"
71#include "llvm/Transforms/Utils/Cloning.h"
Alina Sbirleaa4961432018-09-11 19:19:21 +000072#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000073#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000074#include "llvm/Transforms/Utils/ValueMapper.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000075#include <algorithm>
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000076#include <cassert>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000077#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000078#include <set>
Eugene Zelenkofa6434b2017-08-31 21:56:16 +000079#include <tuple>
80#include <utility>
81#include <vector>
82
Chris Lattnerf48f7772004-04-19 18:07:02 +000083using namespace llvm;
84
Chandler Carruth964daaa2014-04-22 02:55:47 +000085#define DEBUG_TYPE "loop-unswitch"
86
Chris Lattner79a42ac2006-12-19 21:40:18 +000087STATISTIC(NumBranches, "Number of branches unswitched");
88STATISTIC(NumSwitches, "Number of switches unswitched");
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +000089STATISTIC(NumGuards, "Number of guards unswitched");
Chris Lattner79a42ac2006-12-19 21:40:18 +000090STATISTIC(NumSelects , "Number of selects unswitched");
91STATISTIC(NumTrivial , "Number of unswitches that are trivial");
92STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000093STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000094
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000095// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000096// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000097static cl::opt<unsigned>
98Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000099 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +0000100
Dan Gohmand78c4002008-05-13 00:00:25 +0000101namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +0000102
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000103 class LUAnalysisCache {
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000104 using UnswitchedValsMap =
105 DenseMap<const SwitchInst *, SmallPtrSet<const Value *, 8>>;
106 using UnswitchedValsIt = UnswitchedValsMap::iterator;
Andrew Trick4104ed92012-04-10 05:14:37 +0000107
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000108 struct LoopProperties {
109 unsigned CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000110 unsigned WasUnswitchedCount;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000111 unsigned SizeEstimation;
112 UnswitchedValsMap UnswitchedVals;
113 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000114
115 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000116 // LoopProperties pointer for current loop for better performance.
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000117 using LoopPropsMap = std::map<const Loop *, LoopProperties>;
118 using LoopPropsMapIt = LoopPropsMap::iterator;
Andrew Trick4104ed92012-04-10 05:14:37 +0000119
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000120 LoopPropsMap LoopsProperties;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000121 UnswitchedValsMap *CurLoopInstructions = nullptr;
122 LoopProperties *CurrentLoopProperties = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000123
Mark Heffernan9b536a62015-06-23 18:26:50 +0000124 // A loop unswitching with an estimated cost above this threshold
125 // is not performed. MaxSize is turned into unswitching quota for
126 // the current loop, and reduced correspondingly, though note that
127 // the quota is returned by releaseMemory() when the loop has been
128 // processed, so that MaxSize will return to its previous
129 // value. So in most cases MaxSize will equal the Threshold flag
130 // when a new loop is processed. An exception to that is that
131 // MaxSize will have a smaller value while processing nested loops
132 // that were introduced due to loop unswitching of an outer loop.
133 //
134 // FIXME: The way that MaxSize works is subtle and depends on the
135 // pass manager processing loops and calling releaseMemory() in a
136 // specific order. It would be good to find a more straightforward
137 // way of doing what MaxSize does.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000138 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +0000139
Mark Heffernan9b536a62015-06-23 18:26:50 +0000140 public:
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000141 LUAnalysisCache() : MaxSize(Threshold) {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000142
Mark Heffernan9b536a62015-06-23 18:26:50 +0000143 // Analyze loop. Check its size, calculate is it possible to unswitch
144 // it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000145 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
146 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000147
Mark Heffernan9b536a62015-06-23 18:26:50 +0000148 // Clean all data related to given loop.
149 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000150
Mark Heffernan9b536a62015-06-23 18:26:50 +0000151 // Mark case value as unswitched.
152 // Since SI instruction can be partly unswitched, in order to avoid
153 // extra unswitching in cloned loops keep track all unswitched values.
154 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000155
Mark Heffernan9b536a62015-06-23 18:26:50 +0000156 // Check was this case value unswitched before or not.
157 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000158
Mark Heffernan9b536a62015-06-23 18:26:50 +0000159 // Returns true if another unswitching could be done within the cost
160 // threshold.
161 bool CostAllowsUnswitching();
Andrew Trick4104ed92012-04-10 05:14:37 +0000162
Mark Heffernan9b536a62015-06-23 18:26:50 +0000163 // Clone all loop-unswitch related loop properties.
164 // Redistribute unswitching quotas.
165 // Note, that new loop data is stored inside the VMap.
166 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
167 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000168 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000169
Chris Lattner2dd09db2009-09-02 06:11:42 +0000170 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000171 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000172 LPPassManager *LPM;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000173 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000174
Sanjay Patel956e29c2015-08-11 21:24:04 +0000175 // Used to check if second loop needs processing after
176 // RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000177 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000178
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000179 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000180
Devang Patel506310d2007-06-06 00:21:03 +0000181 bool OptimizeForSize;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000182 bool redoLoop = false;
Devang Patela69f9872007-10-05 22:29:34 +0000183
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000184 Loop *currentLoop = nullptr;
185 DominatorTree *DT = nullptr;
Alina Sbirleaa4961432018-09-11 19:19:21 +0000186 MemorySSA *MSSA = nullptr;
187 std::unique_ptr<MemorySSAUpdater> MSSAU;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000188 BasicBlock *loopHeader = nullptr;
189 BasicBlock *loopPreheader = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000190
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000191 bool SanitizeMemory;
192 LoopSafetyInfo SafetyInfo;
193
Devang Pateled50fb52008-07-02 01:44:29 +0000194 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000195 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000196 // loop, in that order.
197 std::vector<BasicBlock*> LoopBlocks;
198 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
199 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000200
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000201 bool hasBranchDivergence;
202
Chris Lattnerf48f7772004-04-19 18:07:02 +0000203 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000204 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000205
206 explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false)
207 : LoopPass(ID), OptimizeForSize(Os),
208 hasBranchDivergence(hasBranchDivergence) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000209 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000210 }
Devang Patel09f162c2007-05-01 21:15:47 +0000211
Craig Topper3e4c6972014-03-05 09:10:37 +0000212 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000213 bool processCurrentLoop();
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000214 bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000215
Chris Lattnerf48f7772004-04-19 18:07:02 +0000216 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000217 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000218 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000219 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000220 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000221 AU.addRequired<TargetTransformInfoWrapperPass>();
Alina Sbirleaa4961432018-09-11 19:19:21 +0000222 if (EnableMSSALoopDependency) {
223 AU.addRequired<MemorySSAWrapperPass>();
224 AU.addPreserved<MemorySSAWrapperPass>();
225 }
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000226 if (hasBranchDivergence)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000227 AU.addRequired<LegacyDivergenceAnalysis>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000228 getLoopAnalysisUsage(AU);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000229 }
230
231 private:
Craig Topper3e4c6972014-03-05 09:10:37 +0000232 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000233 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000234 }
235
Devang Patele149d4e2008-07-02 01:18:13 +0000236 void initLoopData() {
237 loopHeader = currentLoop->getHeader();
238 loopPreheader = currentLoop->getLoopPreheader();
239 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000240
Chris Lattner559c8672008-04-21 00:25:49 +0000241 /// Split all of the edges from inside the loop to their exit blocks.
242 /// Update the appropriate Phi nodes as we do so.
Sanjay Patel41f3d952015-08-11 21:11:56 +0000243 void SplitExitEdges(Loop *L,
244 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000245
Chen Lic0f3a152015-07-22 05:26:29 +0000246 bool TryTrivialLoopUnswitch(bool &Changed);
247
Weiming Zhaof1abad52015-06-23 05:31:09 +0000248 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000249 Instruction *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000250 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000251 BasicBlock *ExitBlock, Instruction *TI);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000252 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000253 Instruction *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000254
255 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
256 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000257
258 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000259 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000260 BasicBlock *FalseDest,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000261 BranchInst *OldBranch, Instruction *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000262
Devang Pateld4911982007-07-31 08:03:26 +0000263 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Xin Tongec6f90b2017-02-23 23:42:19 +0000264
265 /// Given that the Invariant is not equal to Val. Simplify instructions
266 /// in the loop.
267 Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
268 Constant *Val);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000269 };
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000270
271} // end anonymous namespace
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000272
273// Analyze loop. Check its size, calculate is it possible to unswitch
274// it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000275bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
276 AssumptionCache *AC) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000277 LoopPropsMapIt PropsIt;
278 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000279 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000280 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000281
Jakub Staszak27da1232013-08-06 17:03:42 +0000282 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000283
Jakub Staszak27da1232013-08-06 17:03:42 +0000284 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000285 // New loop.
286
287 // Limit the number of instructions to avoid causing significant code
288 // expansion, and the number of basic blocks, to avoid loops with
289 // large numbers of branches which cause loop unswitching to go crazy.
290 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000291
Hal Finkel57f03dd2014-09-07 13:49:57 +0000292 SmallPtrSet<const Value *, 32> EphValues;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000293 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000294
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000295 // FIXME: This is overly conservative because it does not take into
296 // consideration code simplification opportunities and code that can
297 // be shared by the resultant unswitched loops.
298 CodeMetrics Metrics;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000299 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
300 ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000301 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000302
Mark Heffernan9b536a62015-06-23 18:26:50 +0000303 Props.SizeEstimation = Metrics.NumInsts;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000304 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
Mark Heffernan9b536a62015-06-23 18:26:50 +0000305 Props.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000306 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000307
308 if (Metrics.notDuplicatable) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000309 LLVM_DEBUG(dbgs() << "NOT unswitching loop %" << L->getHeader()->getName()
310 << ", contents cannot be "
311 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000312 return false;
313 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000314 }
315
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000316 // Be careful. This links are good only before new loop addition.
317 CurrentLoopProperties = &Props;
318 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000319
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000320 return true;
321}
322
323// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000324void LUAnalysisCache::forgetLoop(const Loop *L) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000325 LoopPropsMapIt LIt = LoopsProperties.find(L);
326
327 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000328 LoopProperties &Props = LIt->second;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000329 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
330 Props.SizeEstimation;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000331 LoopsProperties.erase(LIt);
332 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000333
Craig Topperf40110f2014-04-25 05:29:35 +0000334 CurrentLoopProperties = nullptr;
335 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000336}
337
338// Mark case value as unswitched.
339// Since SI instruction can be partly unswitched, in order to avoid
340// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000341void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000342 (*CurLoopInstructions)[SI].insert(V);
343}
344
345// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000346bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000347 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000348}
349
Mark Heffernan9b536a62015-06-23 18:26:50 +0000350bool LUAnalysisCache::CostAllowsUnswitching() {
351 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
352}
353
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000354// Clone all loop-unswitch related loop properties.
355// Redistribute unswitching quotas.
356// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000357void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
358 const ValueToValueMapTy &VMap) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000359 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
360 LoopProperties &OldLoopProps = *CurrentLoopProperties;
361 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000362
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000363 // Reallocate "can-be-unswitched quota"
364
365 --OldLoopProps.CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000366 ++OldLoopProps.WasUnswitchedCount;
367 NewLoopProps.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000368 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
369 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
370 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000371
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000372 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000373
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000374 // Clone unswitched values info:
375 // for new loop switches we clone info about values that was
376 // already unswitched and has redundant successors.
377 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000378 const SwitchInst *OldInst = I->first;
379 Value *NewI = VMap.lookup(OldInst);
380 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000381 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000382
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000383 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
384 }
385}
386
Dan Gohmand78c4002008-05-13 00:00:25 +0000387char LoopUnswitch::ID = 0;
Eugene Zelenkofa6434b2017-08-31 21:56:16 +0000388
Owen Anderson8ac477f2010-10-12 19:48:12 +0000389INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
390 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000391INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000392INITIALIZE_PASS_DEPENDENCY(LoopPass)
393INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000394INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
Alina Sbirleaa4961432018-09-11 19:19:21 +0000395INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000396INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
397 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000398
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000399Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
400 return new LoopUnswitch(Os, hasBranchDivergence);
Devang Patel506310d2007-06-06 00:21:03 +0000401}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000402
Xin Tong16b85a62017-02-27 18:00:13 +0000403/// Operator chain lattice.
404enum OperatorChain {
405 OC_OpChainNone, ///< There is no operator.
406 OC_OpChainOr, ///< There are only ORs.
407 OC_OpChainAnd, ///< There are only ANDs.
408 OC_OpChainMixed ///< There are ANDs and ORs.
409};
410
Sanjay Patel956e29c2015-08-11 21:24:04 +0000411/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
412/// an invariant piece, return the invariant. Otherwise, return null.
Xin Tong16b85a62017-02-27 18:00:13 +0000413//
414/// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
415/// mixed operator chain, as we can not reliably find a value which will simplify
416/// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
417/// to simplify the chain.
418///
419/// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
420/// simplify the condition itself to a loop variant condition, but at the
421/// cost of creating an entirely new loop.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000422static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
Xin Tong16b85a62017-02-27 18:00:13 +0000423 OperatorChain &ParentChain,
Sanjoy Dasd8500682016-06-25 01:14:19 +0000424 DenseMap<Value *, Value *> &Cache) {
425 auto CacheIt = Cache.find(Cond);
426 if (CacheIt != Cache.end())
427 return CacheIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000428
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000429 // We started analyze new instruction, increment scanned instructions counter.
430 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000431
Chris Lattner302240d2010-02-02 02:26:54 +0000432 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000433 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000434 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000435
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000436 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000437 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000438
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000439 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000440
Dan Gohman4d6149f2009-07-14 01:37:59 +0000441 // Hoist simple values out.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000442 if (L->makeLoopInvariant(Cond, Changed)) {
443 Cache[Cond] = Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000444 return Cond;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000445 }
Dan Gohman4d6149f2009-07-14 01:37:59 +0000446
Xin Tong16b85a62017-02-27 18:00:13 +0000447 // Walk up the operator chain to find partial invariant conditions.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000448 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
449 if (BO->getOpcode() == Instruction::And ||
450 BO->getOpcode() == Instruction::Or) {
Xin Tong16b85a62017-02-27 18:00:13 +0000451 // Given the previous operator, compute the current operator chain status.
452 OperatorChain NewChain;
453 switch (ParentChain) {
454 case OC_OpChainNone:
455 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
456 OC_OpChainOr;
457 break;
458 case OC_OpChainOr:
459 NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
460 OC_OpChainMixed;
461 break;
462 case OC_OpChainAnd:
463 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
464 OC_OpChainMixed;
465 break;
466 case OC_OpChainMixed:
467 NewChain = OC_OpChainMixed;
468 break;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000469 }
Xin Tong16b85a62017-02-27 18:00:13 +0000470
471 // If we reach a Mixed state, we do not want to keep walking up as we can not
472 // reliably find a value that will simplify the chain. With this check, we
473 // will return null on the first sight of mixed chain and the caller will
474 // either backtrack to find partial LIV in other operand or return null.
475 if (NewChain != OC_OpChainMixed) {
476 // Update the current operator chain type before we search up the chain.
477 ParentChain = NewChain;
478 // If either the left or right side is invariant, we can unswitch on this,
479 // which will cause the branch to go away in one loop and the condition to
480 // simplify in the other one.
481 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
482 ParentChain, Cache)) {
483 Cache[Cond] = LHS;
484 return LHS;
485 }
486 // We did not manage to find a partial LIV in operand(0). Backtrack and try
487 // operand(1).
488 ParentChain = NewChain;
489 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
490 ParentChain, Cache)) {
491 Cache[Cond] = RHS;
492 return RHS;
493 }
Sanjoy Dasd8500682016-06-25 01:14:19 +0000494 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000495 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000496
Sanjoy Dasd8500682016-06-25 01:14:19 +0000497 Cache[Cond] = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000498 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000499}
500
Xin Tong16b85a62017-02-27 18:00:13 +0000501/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
502/// an invariant piece, return the invariant along with the operator chain type.
503/// Otherwise, return null.
504static std::pair<Value *, OperatorChain> FindLIVLoopCondition(Value *Cond,
505 Loop *L,
506 bool &Changed) {
Sanjoy Dasd8500682016-06-25 01:14:19 +0000507 DenseMap<Value *, Value *> Cache;
Xin Tong16b85a62017-02-27 18:00:13 +0000508 OperatorChain OpChain = OC_OpChainNone;
509 Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache);
510
511 // In case we do find a LIV, it can not be obtained by walking up a mixed
512 // operator chain.
513 assert((!FCond || OpChain != OC_OpChainMixed) &&
514 "Do not expect a partial LIV with mixed operator chain");
515 return {FCond, OpChain};
Sanjoy Dasd8500682016-06-25 01:14:19 +0000516}
517
Devang Patel901a27d2007-03-07 00:26:10 +0000518bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000519 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000520 return false;
521
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000522 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
523 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000524 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000525 LPM = &LPM_Ref;
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000526 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Alina Sbirleaa4961432018-09-11 19:19:21 +0000527 if (EnableMSSALoopDependency) {
528 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
529 MSSAU = make_unique<MemorySSAUpdater>(MSSA);
530 assert(DT && "Cannot update MemorySSA without a valid DomTree.");
531 }
Devang Patele149d4e2008-07-02 01:18:13 +0000532 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000533 Function *F = currentLoop->getHeader()->getParent();
Chen Li9f27fc02015-09-29 05:03:32 +0000534
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000535 SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
536 if (SanitizeMemory)
Max Kazantsev530b8d12018-08-15 05:55:43 +0000537 SafetyInfo.computeLoopSafetyInfo(L);
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000538
Alina Sbirleaa4961432018-09-11 19:19:21 +0000539 if (MSSA && VerifyMemorySSA)
540 MSSA->verifyMemorySSA();
541
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000542 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000543 do {
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000544 assert(currentLoop->isLCSSAForm(*DT));
Alina Sbirleaa4961432018-09-11 19:19:21 +0000545 if (MSSA && VerifyMemorySSA)
546 MSSA->verifyMemorySSA();
Devang Patel7d165e12007-07-30 23:07:10 +0000547 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000548 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000549 } while(redoLoop);
550
Alina Sbirleaa4961432018-09-11 19:19:21 +0000551 if (MSSA && VerifyMemorySSA)
552 MSSA->verifyMemorySSA();
553
Devang Patel7d165e12007-07-30 23:07:10 +0000554 return Changed;
555}
556
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000557// Return true if the BasicBlock BB is unreachable from the loop header.
558// Return false, otherwise.
559bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
560 auto *Node = DT->getNode(BB)->getIDom();
561 BasicBlock *DomBB = Node->getBlock();
562 while (currentLoop->contains(DomBB)) {
563 BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
564
565 Node = DT->getNode(DomBB)->getIDom();
566 DomBB = Node->getBlock();
567
568 if (!BInst || !BInst->isConditional())
569 continue;
570
571 Value *Cond = BInst->getCondition();
572 if (!isa<ConstantInt>(Cond))
573 continue;
574
575 BasicBlock *UnreachableSucc =
576 Cond == ConstantInt::getTrue(Cond->getContext())
577 ? BInst->getSuccessor(1)
578 : BInst->getSuccessor(0);
579
580 if (DT->dominates(UnreachableSucc, BB))
581 return true;
582 }
583 return false;
584}
585
Wei Mifc0e2452017-07-25 23:37:17 +0000586/// FIXME: Remove this workaround when freeze related patches are done.
587/// LoopUnswitch and Equality propagation in GVN have discrepancy about
588/// whether branch on undef/poison has undefine behavior. Here it is to
589/// rule out some common cases that we found such discrepancy already
590/// causing problems. Detail could be found in PR31652. Note if the
591/// func returns true, it is unsafe. But if it is false, it doesn't mean
592/// it is necessarily safe.
593static bool EqualityPropUnSafe(Value &LoopCond) {
594 ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
595 if (!CI || !CI->isEquality())
596 return false;
597
598 Value *LHS = CI->getOperand(0);
599 Value *RHS = CI->getOperand(1);
600 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
601 return true;
602
603 auto hasUndefInPHI = [](PHINode &PN) {
604 for (Value *Opd : PN.incoming_values()) {
605 if (isa<UndefValue>(Opd))
606 return true;
607 }
608 return false;
609 };
610 PHINode *LPHI = dyn_cast<PHINode>(LHS);
611 PHINode *RPHI = dyn_cast<PHINode>(RHS);
612 if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
613 return true;
614
615 auto hasUndefInSelect = [](SelectInst &SI) {
616 if (isa<UndefValue>(SI.getTrueValue()) ||
617 isa<UndefValue>(SI.getFalseValue()))
618 return true;
619 return false;
620 };
621 SelectInst *LSI = dyn_cast<SelectInst>(LHS);
622 SelectInst *RSI = dyn_cast<SelectInst>(RHS);
623 if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
624 return true;
625 return false;
626}
627
Sanjay Patel956e29c2015-08-11 21:24:04 +0000628/// Do actual work and unswitch loop if possible and profitable.
Devang Patele149d4e2008-07-02 01:18:13 +0000629bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000630 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000631
632 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000633
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000634 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
635 if (!loopPreheader)
636 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000637
Andrew Trick4442bfe2012-04-10 05:14:42 +0000638 // Loops with indirectbr cannot be cloned.
639 if (!currentLoop->isSafeToClone())
640 return false;
641
642 // Without dedicated exits, splitting the exit edge may fail.
643 if (!currentLoop->hasDedicatedExits())
644 return false;
645
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000646 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000647
Chen Li567aa7a2015-10-14 19:47:43 +0000648 // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
Chandler Carruth705b1852015-01-31 03:43:40 +0000649 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000650 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000651 *currentLoop->getHeader()->getParent()),
652 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000653 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000654
Chen Lic0f3a152015-07-22 05:26:29 +0000655 // Try trivial unswitch first before loop over other basic blocks in the loop.
656 if (TryTrivialLoopUnswitch(Changed)) {
657 return true;
658 }
659
Philip Reames5c14ed82018-03-29 20:32:15 +0000660 // Do not do non-trivial unswitch while optimizing for size.
661 // FIXME: Use Function::optForSize().
662 if (OptimizeForSize ||
663 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
664 return false;
665
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000666 // Run through the instructions in the loop, keeping track of three things:
667 //
668 // - That we do not unswitch loops containing convergent operations, as we
669 // might be making them control dependent on the unswitch value when they
670 // were not before.
671 // FIXME: This could be refined to only bail if the convergent operation is
672 // not already control-dependent on the unswitch value.
673 //
674 // - That basic blocks in the loop contain invokes whose predecessor edges we
675 // cannot split.
676 //
677 // - The set of guard intrinsics encountered (these are non terminator
678 // instructions that are also profitable to be unswitched).
679
680 SmallVector<IntrinsicInst *, 4> Guards;
681
Owen Anderson2c9978b2015-10-09 18:40:20 +0000682 for (const auto BB : currentLoop->blocks()) {
Owen Anderson97ca0f32015-10-09 20:17:46 +0000683 for (auto &I : *BB) {
684 auto CS = CallSite(&I);
685 if (!CS) continue;
686 if (CS.hasFnAttr(Attribute::Convergent))
Owen Anderson2c9978b2015-10-09 18:40:20 +0000687 return false;
David Majnemer3d90bb72016-05-03 03:57:40 +0000688 if (auto *II = dyn_cast<InvokeInst>(&I))
689 if (!II->getUnwindDest()->canSplitPredecessors())
690 return false;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000691 if (auto *II = dyn_cast<IntrinsicInst>(&I))
692 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
693 Guards.push_back(II);
Owen Anderson2c9978b2015-10-09 18:40:20 +0000694 }
695 }
696
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000697 for (IntrinsicInst *Guard : Guards) {
698 Value *LoopCond =
Xin Tong16b85a62017-02-27 18:00:13 +0000699 FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed).first;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000700 if (LoopCond &&
701 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
702 // NB! Unswitching (if successful) could have erased some of the
703 // instructions in Guards leaving dangling pointers there. This is fine
704 // because we're returning now, and won't look at Guards again.
705 ++NumGuards;
706 return true;
707 }
708 }
709
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000710 // Loop over all of the basic blocks in the loop. If we find an interior
711 // block that is branching on a loop-invariant condition, we can unswitch this
712 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000713 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000714 E = currentLoop->block_end(); I != E; ++I) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000715 Instruction *TI = (*I)->getTerminator();
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000716
717 // Unswitching on a potentially uninitialized predicate is not
718 // MSan-friendly. Limit this to the cases when the original predicate is
719 // guaranteed to execute, to avoid creating a use-of-uninitialized-value
720 // in the code that did not have one.
721 // This is a workaround for the discrepancy between LLVM IR and MSan
722 // semantics. See PR28054 for more details.
723 if (SanitizeMemory &&
Max Kazantsevc8466f92018-10-16 06:34:53 +0000724 !SafetyInfo.isGuaranteedToExecute(*TI, DT, currentLoop))
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000725 continue;
726
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000727 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000728 // Some branches may be rendered unreachable because of previous
729 // unswitching.
730 // Unswitch only those branches that are reachable.
731 if (isUnreachableDueToPreviousUnswitching(*I))
732 continue;
Fangrui Songf78650a2018-07-30 19:41:25 +0000733
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000734 // If this isn't branching on an invariant condition, we can't unswitch
735 // it.
736 if (BI->isConditional()) {
737 // See if this, or some part of it, is loop invariant. If so, we can
738 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000739 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +0000740 currentLoop, Changed).first;
Wei Miebb93272017-08-29 21:45:11 +0000741 if (LoopCond && !EqualityPropUnSafe(*LoopCond) &&
742 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000743 ++NumBranches;
744 return true;
745 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000746 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000747 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Xin Tong16b85a62017-02-27 18:00:13 +0000748 Value *SC = SI->getCondition();
749 Value *LoopCond;
750 OperatorChain OpChain;
751 std::tie(LoopCond, OpChain) =
752 FindLIVLoopCondition(SC, currentLoop, Changed);
753
Andrew Trick4104ed92012-04-10 05:14:37 +0000754 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000755 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000756 // Find a value to unswitch on:
757 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000758 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000759 Constant *UnswitchVal = nullptr;
Xin Tong16b85a62017-02-27 18:00:13 +0000760 // Find a case value such that at least one case value is unswitched
761 // out.
762 if (OpChain == OC_OpChainAnd) {
763 // If the chain only has ANDs and the switch has a case value of 0.
764 // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
765 auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
766 if (BranchesInfo.isUnswitched(SI, AllZero))
767 continue;
768 // We are unswitching 0 out.
769 UnswitchVal = AllZero;
770 } else if (OpChain == OC_OpChainOr) {
771 // If the chain only has ORs and the switch has a case value of ~0.
772 // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
773 auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
774 if (BranchesInfo.isUnswitched(SI, AllOne))
775 continue;
776 // We are unswitching ~0 out.
777 UnswitchVal = AllOne;
778 } else {
Fangrui Songf78650a2018-07-30 19:41:25 +0000779 assert(OpChain == OC_OpChainNone &&
Xin Tong16b85a62017-02-27 18:00:13 +0000780 "Expect to unswitch on trivial chain");
781 // Do not process same value again and again.
782 // At this point we have some cases already unswitched and
783 // some not yet unswitched. Let's find the first not yet unswitched one.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000784 for (auto Case : SI->cases()) {
785 Constant *UnswitchValCandidate = Case.getCaseValue();
Xin Tong16b85a62017-02-27 18:00:13 +0000786 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
787 UnswitchVal = UnswitchValCandidate;
788 break;
789 }
Chad Rosier3ba90a12011-12-22 21:10:46 +0000790 }
791 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000792
Chad Rosier3ba90a12011-12-22 21:10:46 +0000793 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000794 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000795
Devang Patele149d4e2008-07-02 01:18:13 +0000796 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000797 ++NumSwitches;
Xin Tong16b85a62017-02-27 18:00:13 +0000798 // In case of a full LIV, UnswitchVal is the value we unswitched out.
799 // In case of a partial LIV, we only unswitch when its an AND-chain
800 // or OR-chain. In both cases switch input value simplifies to
801 // UnswitchVal.
802 BranchesInfo.setUnswitched(SI, UnswitchVal);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000803 return true;
804 }
805 }
806 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000807
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000808 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000809 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000810 BBI != E; ++BBI)
811 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000812 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +0000813 currentLoop, Changed).first;
Andrew Trick4104ed92012-04-10 05:14:37 +0000814 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000815 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000816 ++NumSelects;
817 return true;
818 }
819 }
820 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000821 return Changed;
822}
823
Sanjay Patel956e29c2015-08-11 21:24:04 +0000824/// Check to see if all paths from BB exit the loop with no side effects
825/// (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000826///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000827/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000828/// exit through.
829///
830static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
831 BasicBlock *&ExitBB,
832 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000833 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000834 // Already visited. Without more analysis, this could indicate an infinite
835 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000836 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000837 }
838 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000839 // Otherwise, this is a loop exit, this is fine so long as this is the
840 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000841 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000842 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000843 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000844 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000845
Chris Lattnerbaddba42006-02-17 06:39:56 +0000846 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000847 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000848 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000849 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000850 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000851 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000852
853 // Okay, everything after this looks good, check to make sure that this block
854 // doesn't include any side effects.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000855 for (Instruction &I : *BB)
856 if (I.mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000857 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000858
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000859 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000860}
861
Sanjay Patel956e29c2015-08-11 21:24:04 +0000862/// Return true if the specified block unconditionally leads to an exit from
863/// the specified loop, and has no side-effects in the process. If so, return
864/// the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000865static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
866 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000867 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000868 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000869 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
870 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000871 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000872}
Chris Lattner6e263152006-02-10 02:30:37 +0000873
Sanjay Patel956e29c2015-08-11 21:24:04 +0000874/// We have found that we can unswitch currentLoop when LoopCond == Val to
875/// simplify the loop. If we decide that this is profitable,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000876/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000877bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000878 Instruction *TI) {
Evan Chenged66db32010-04-03 02:23:43 +0000879 // Check to see if it would be profitable to unswitch current loop.
Mark Heffernan9b536a62015-06-23 18:26:50 +0000880 if (!BranchesInfo.CostAllowsUnswitching()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000881 LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
882 << currentLoop->getHeader()->getName()
883 << " at non-trivial condition '" << *Val
884 << "' == " << *LoopCond << "\n"
885 << ". Cost too high.\n");
Mark Heffernan9b536a62015-06-23 18:26:50 +0000886 return false;
887 }
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000888 if (hasBranchDivergence &&
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000889 getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000890 LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
891 << currentLoop->getHeader()->getName()
892 << " at non-trivial condition '" << *Val
893 << "' == " << *LoopCond << "\n"
894 << ". Condition is divergent.\n");
Stanislav Mekhanoshinee2dd782017-03-17 17:13:41 +0000895 return false;
896 }
Evan Chenged66db32010-04-03 02:23:43 +0000897
Weiming Zhaof1abad52015-06-23 05:31:09 +0000898 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000899 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000900}
901
Sanjay Patel956e29c2015-08-11 21:24:04 +0000902/// Recursively clone the specified loop and all of its children,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000903/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000904static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000905 LoopInfo *LI, LPPassManager *LPM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +0000906 Loop &New = *LI->AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +0000907 if (PL)
908 PL->addChildLoop(&New);
909 else
910 LI->addTopLevelLoop(&New);
911 LPM->addLoop(New);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000912
913 // Add all of the blocks in L to the new loop.
914 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
915 I != E; ++I)
916 if (LI->getLoopFor(*I) == L)
Justin Bogner35e46cd2015-10-22 21:21:32 +0000917 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000918
919 // Add all of the subloops to the new loop.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000920 for (Loop *I : *L)
921 CloneLoop(I, &New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000922
Justin Bogner35e46cd2015-10-22 21:21:32 +0000923 return &New;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000924}
925
Sanjay Patel956e29c2015-08-11 21:24:04 +0000926/// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000927/// otherwise branch to FalseDest. Insert the code immediately before OldBranch
928/// and remove (but not erase!) it from the function.
Devang Patel3304e462007-06-28 00:49:00 +0000929void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
930 BasicBlock *TrueDest,
931 BasicBlock *FalseDest,
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000932 BranchInst *OldBranch,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000933 Instruction *TI) {
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000934 assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
Alina Sbirleabee50032018-06-22 17:14:35 +0000935 assert(TrueDest != FalseDest && "Branch targets should be different");
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000936 // Insert a conditional branch on LIC to the two preheaders. The original
937 // code is the true version and the new code is the false version.
938 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000939 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000940 if (!isa<ConstantInt>(Val) ||
941 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000942 BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000943 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000944 // We want to enter the new loop when the condition is true.
945 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000946 Swapped = true;
947 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000948
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000949 // Old branch will be removed, so save its parent and successor to update the
950 // DomTree.
951 auto *OldBranchSucc = OldBranch->getSuccessor(0);
952 auto *OldBranchParent = OldBranch->getParent();
953
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000954 // Insert the new branch.
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000955 BranchInst *BI =
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000956 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000957 if (Swapped)
958 BI->swapProfMetadata();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000959
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000960 // Remove the old branch so there is only one branch at the end. This is
961 // needed to perform DomTree's internal DFS walk on the function's CFG.
962 OldBranch->removeFromParent();
963
964 // Inform the DT about the new branch.
965 if (DT) {
966 // First, add both successors.
967 SmallVector<DominatorTree::UpdateType, 3> Updates;
Alina Sbirleabee50032018-06-22 17:14:35 +0000968 if (TrueDest != OldBranchSucc)
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000969 Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
Alina Sbirleabee50032018-06-22 17:14:35 +0000970 if (FalseDest != OldBranchSucc)
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000971 Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
972 // If both of the new successors are different from the old one, inform the
973 // DT that the edge was deleted.
974 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
975 Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
976 }
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000977 DT->applyUpdates(Updates);
Alina Sbirleaa4961432018-09-11 19:19:21 +0000978
979 if (MSSAU)
980 MSSAU->applyUpdates(Updates, *DT);
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000981 }
982
Dan Gohman3ddbc242009-09-08 15:45:00 +0000983 // If either edge is critical, split it. This helps preserve LoopSimplify
984 // form for enclosing loops.
Alina Sbirleaa4961432018-09-11 19:19:21 +0000985 auto Options =
986 CriticalEdgeSplittingOptions(DT, LI, MSSAU.get()).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000987 SplitCriticalEdge(BI, 0, Options);
988 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000989}
990
Sanjay Patel956e29c2015-08-11 21:24:04 +0000991/// Given a loop that has a trivial unswitchable condition in it (a cond branch
992/// from its header block to its latch block, where the path through the loop
993/// that doesn't execute its body has no side-effects), unswitch it. This
994/// doesn't involve any code duplication, just moving the conditional branch
995/// outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000996void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
997 BasicBlock *ExitBlock,
Chandler Carruthedb12a82018-10-15 10:04:59 +0000998 Instruction *TI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000999 LLVM_DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
1000 << loopHeader->getName() << " [" << L->getBlocks().size()
1001 << " blocks] in Function "
1002 << L->getHeader()->getParent()->getName()
1003 << " on cond: " << *Val << " == " << *Cond << "\n");
Max Kazantsevd99f3ba2018-05-23 10:09:53 +00001004 // We are going to make essential changes to CFG. This may invalidate cached
1005 // information for L or one of its parent loops in SCEV.
1006 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1007 SEWP->getSE().forgetTopmostLoop(L);
Andrew Trick4104ed92012-04-10 05:14:37 +00001008
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001009 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +00001010 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +00001011 // conditional branch on Cond.
Alina Sbirleaa4961432018-09-11 19:19:21 +00001012 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
Chris Lattnered7a67b2006-02-10 01:24:09 +00001013
1014 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +00001015 // to branch to: this is the exit block out of the loop that we should
1016 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +00001017
Chris Lattnere5cb76d2006-02-15 22:03:36 +00001018 // Split this block now, so that the loop maintains its exit block, and so
1019 // that the jump from the preheader can execute the contents of the exit block
1020 // without actually branching to it (the exit block should be dominated by the
1021 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +00001022 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Alina Sbirleaa4961432018-09-11 19:19:21 +00001023 BasicBlock *NewExit =
1024 SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI, MSSAU.get());
Andrew Trick4104ed92012-04-10 05:14:37 +00001025
1026 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +00001027 // insert the new conditional branch.
Jakub Kuderskie35a4492017-08-17 16:45:35 +00001028 auto *OldBranch = dyn_cast<BranchInst>(loopPreheader->getTerminator());
1029 assert(OldBranch && "Failed to split the preheader");
1030 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1031 LPM->deleteSimpleAnalysisValue(OldBranch, L);
1032
1033 // EmitPreheaderBranchOnCondition removed the OldBranch from the function.
1034 // Delete it, as it is no longer needed.
1035 delete OldBranch;
Chris Lattnered7a67b2006-02-10 01:24:09 +00001036
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001037 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +00001038 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +00001039
Chris Lattnered7a67b2006-02-10 01:24:09 +00001040 // Now that we know that the loop is never entered when this condition is a
1041 // particular value, rewrite the loop with this info. We know that this will
1042 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001043 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Alina Sbirleaa4961432018-09-11 19:19:21 +00001044
Chris Lattner0b8ec1a2006-02-14 01:01:41 +00001045 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +00001046}
1047
Sanjay Patel41f3d952015-08-11 21:11:56 +00001048/// Check if the first non-constant condition starting from the loop header is
1049/// a trivial unswitch condition: that is, a condition controls whether or not
1050/// the loop does anything at all. If it is a trivial condition, unswitching
1051/// produces no code duplications (equivalently, it produces a simpler loop and
1052/// a new empty loop, which gets deleted). Therefore always unswitch trivial
1053/// condition.
Chen Lic0f3a152015-07-22 05:26:29 +00001054bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
Chen Li145c2f52015-07-25 03:21:06 +00001055 BasicBlock *CurrentBB = currentLoop->getHeader();
Chandler Carruthedb12a82018-10-15 10:04:59 +00001056 Instruction *CurrentTerm = CurrentBB->getTerminator();
Chen Li145c2f52015-07-25 03:21:06 +00001057 LLVMContext &Context = CurrentBB->getContext();
Chen Lic0f3a152015-07-22 05:26:29 +00001058
Chen Li145c2f52015-07-25 03:21:06 +00001059 // If loop header has only one reachable successor (currently via an
1060 // unconditional branch or constant foldable conditional branch, but
1061 // should also consider adding constant foldable switch instruction in
1062 // future), we should keep looking for trivial condition candidates in
1063 // the successor as well. An alternative is to constant fold conditions
1064 // and merge successors into loop header (then we only need to check header's
1065 // terminator). The reason for not doing this in LoopUnswitch pass is that
1066 // it could potentially break LoopPassManager's invariants. Folding dead
1067 // branches could either eliminate the current loop or make other loops
Sanjay Patel41f3d952015-08-11 21:11:56 +00001068 // unreachable. LCSSA form might also not be preserved after deleting
1069 // branches. The following code keeps traversing loop header's successors
1070 // until it finds the trivial condition candidate (condition that is not a
1071 // constant). Since unswitching generates branches with constant conditions,
1072 // this scenario could be very common in practice.
Florian Hahna1cc8482018-06-12 11:16:56 +00001073 SmallPtrSet<BasicBlock*, 8> Visited;
Chen Li145c2f52015-07-25 03:21:06 +00001074
1075 while (true) {
1076 // If we exit loop or reach a previous visited block, then
1077 // we can not reach any trivial condition candidates (unfoldable
1078 // branch instructions or switch instructions) and no unswitch
1079 // can happen. Exit and return false.
1080 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
Chen Lic0f3a152015-07-22 05:26:29 +00001081 return false;
1082
Chen Li145c2f52015-07-25 03:21:06 +00001083 // Check if this loop will execute any side-effecting instructions (e.g.
1084 // stores, calls, volatile loads) in the part of the loop that the code
1085 // *would* execute. Check the header first.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001086 for (Instruction &I : *CurrentBB)
1087 if (I.mayHaveSideEffects())
Chen Li145c2f52015-07-25 03:21:06 +00001088 return false;
1089
Chen Li145c2f52015-07-25 03:21:06 +00001090 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1091 if (BI->isUnconditional()) {
1092 CurrentBB = BI->getSuccessor(0);
1093 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
1094 CurrentBB = BI->getSuccessor(0);
1095 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
1096 CurrentBB = BI->getSuccessor(1);
1097 } else {
Sanjay Patel41f3d952015-08-11 21:11:56 +00001098 // Found a trivial condition candidate: non-foldable conditional branch.
Chen Li145c2f52015-07-25 03:21:06 +00001099 break;
1100 }
Xin Tonge5f8d642017-01-27 01:42:20 +00001101 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1102 // At this point, any constant-foldable instructions should have probably
1103 // been folded.
1104 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
1105 if (!Cond)
1106 break;
1107 // Find the target block we are definitely going to.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001108 CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
Karl-Johan Karlsson38cbf582017-02-14 07:31:36 +00001109 } else {
Xin Tonge5f8d642017-01-27 01:42:20 +00001110 // We do not understand these terminator instructions.
Chen Li145c2f52015-07-25 03:21:06 +00001111 break;
1112 }
1113
1114 CurrentTerm = CurrentBB->getTerminator();
1115 }
1116
Chen Lic0f3a152015-07-22 05:26:29 +00001117 // CondVal is the condition that controls the trivial condition.
1118 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1119 Constant *CondVal = nullptr;
1120 BasicBlock *LoopExitBB = nullptr;
1121
Chen Li145c2f52015-07-25 03:21:06 +00001122 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +00001123 // If this isn't branching on an invariant condition, we can't unswitch it.
1124 if (!BI->isConditional())
1125 return false;
1126
1127 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +00001128 currentLoop, Changed).first;
Chen Lic0f3a152015-07-22 05:26:29 +00001129
1130 // Unswitch only if the trivial condition itself is an LIV (not
1131 // partial LIV which could occur in and/or)
1132 if (!LoopCond || LoopCond != BI->getCondition())
1133 return false;
1134
1135 // Check to see if a successor of the branch is guaranteed to
1136 // exit through a unique exit block without having any
1137 // side-effects. If so, determine the value of Cond that causes
1138 // it to do this.
1139 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1140 BI->getSuccessor(0)))) {
1141 CondVal = ConstantInt::getTrue(Context);
1142 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1143 BI->getSuccessor(1)))) {
1144 CondVal = ConstantInt::getFalse(Context);
1145 }
1146
Sanjay Patel41f3d952015-08-11 21:11:56 +00001147 // If we didn't find a single unique LoopExit block, or if the loop exit
1148 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +00001149 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1150 return false; // Can't handle this.
1151
Wei Mifc0e2452017-07-25 23:37:17 +00001152 if (EqualityPropUnSafe(*LoopCond))
1153 return false;
1154
Sanjay Patel41f3d952015-08-11 21:11:56 +00001155 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1156 CurrentTerm);
Chen Lic0f3a152015-07-22 05:26:29 +00001157 ++NumBranches;
1158 return true;
Chen Li145c2f52015-07-25 03:21:06 +00001159 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +00001160 // If this isn't switching on an invariant condition, we can't unswitch it.
1161 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Xin Tong16b85a62017-02-27 18:00:13 +00001162 currentLoop, Changed).first;
Chen Lic0f3a152015-07-22 05:26:29 +00001163
1164 // Unswitch only if the trivial condition itself is an LIV (not
1165 // partial LIV which could occur in and/or)
1166 if (!LoopCond || LoopCond != SI->getCondition())
1167 return false;
1168
1169 // Check to see if a successor of the switch is guaranteed to go to the
1170 // latch block or exit through a one exit block without having any
1171 // side-effects. If so, determine the value of Cond that causes it to do
1172 // this.
1173 // Note that we can't trivially unswitch on the default case or
1174 // on already unswitched cases.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001175 for (auto Case : SI->cases()) {
Chen Lic0f3a152015-07-22 05:26:29 +00001176 BasicBlock *LoopExitCandidate;
Chandler Carruth927d8e62017-04-12 07:27:28 +00001177 if ((LoopExitCandidate =
1178 isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
Chen Lic0f3a152015-07-22 05:26:29 +00001179 // Okay, we found a trivial case, remember the value that is trivial.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001180 ConstantInt *CaseVal = Case.getCaseValue();
Chen Lic0f3a152015-07-22 05:26:29 +00001181
1182 // Check that it was not unswitched before, since already unswitched
1183 // trivial vals are looks trivial too.
1184 if (BranchesInfo.isUnswitched(SI, CaseVal))
1185 continue;
1186 LoopExitBB = LoopExitCandidate;
1187 CondVal = CaseVal;
1188 break;
1189 }
1190 }
1191
Sanjay Patel41f3d952015-08-11 21:11:56 +00001192 // If we didn't find a single unique LoopExit block, or if the loop exit
1193 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +00001194 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1195 return false; // Can't handle this.
1196
Sanjay Patel41f3d952015-08-11 21:11:56 +00001197 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1198 nullptr);
Xin Tong16b85a62017-02-27 18:00:13 +00001199
1200 // We are only unswitching full LIV.
1201 BranchesInfo.setUnswitched(SI, CondVal);
Chen Lic0f3a152015-07-22 05:26:29 +00001202 ++NumSwitches;
1203 return true;
1204 }
1205 return false;
1206}
1207
Sanjay Patel956e29c2015-08-11 21:24:04 +00001208/// Split all of the edges from inside the loop to their exit blocks.
1209/// Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +00001210void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +00001211 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +00001212
Chris Lattnered7a67b2006-02-10 01:24:09 +00001213 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001214 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +00001215 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1216 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +00001217
Nick Lewycky61158242011-06-03 06:27:15 +00001218 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1219 // general, if we call it on all predecessors of all exits then it does.
Alina Sbirleaa4961432018-09-11 19:19:21 +00001220 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI, MSSAU.get(),
Philip Reames9198b332015-01-28 23:06:47 +00001221 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +00001222 }
Devang Patele192e3252007-10-03 21:16:08 +00001223}
1224
Sanjay Patel956e29c2015-08-11 21:24:04 +00001225/// We determined that the loop is profitable to unswitch when LIC equal Val.
1226/// Split it into loop versions and test the condition outside of either loop.
1227/// Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +00001228void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Chandler Carruthedb12a82018-10-15 10:04:59 +00001229 Loop *L, Instruction *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +00001230 Function *F = loopHeader->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001231 LLVM_DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1232 << loopHeader->getName() << " [" << L->getBlocks().size()
1233 << " blocks] in Function " << F->getName() << " when '"
1234 << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +00001235
Max Kazantsevd99f3ba2018-05-23 10:09:53 +00001236 // We are going to make essential changes to CFG. This may invalidate cached
1237 // information for L or one of its parent loops in SCEV.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001238 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
Max Kazantsevd99f3ba2018-05-23 10:09:53 +00001239 SEWP->getSE().forgetTopmostLoop(L);
Cameron Zwarich99de19b2011-02-11 06:08:28 +00001240
Devang Pateled50fb52008-07-02 01:44:29 +00001241 LoopBlocks.clear();
1242 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +00001243
1244 // First step, split the preheader and exit blocks, and add these blocks to
1245 // the LoopBlocks list.
Alina Sbirleaa4961432018-09-11 19:19:21 +00001246 BasicBlock *NewPreheader =
1247 SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
Devang Patele192e3252007-10-03 21:16:08 +00001248 LoopBlocks.push_back(NewPreheader);
1249
1250 // We want the loop to come after the preheader, but before the exit blocks.
1251 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1252
1253 SmallVector<BasicBlock*, 8> ExitBlocks;
1254 L->getUniqueExitBlocks(ExitBlocks);
1255
1256 // Split all of the edges from inside the loop to their exit blocks. Update
1257 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +00001258 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +00001259
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001260 // The exit blocks may have been changed due to edge splitting, recompute.
1261 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +00001262 L->getUniqueExitBlocks(ExitBlocks);
1263
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001264 // Add exit blocks to the loop blocks.
1265 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001266
1267 // Next step, clone all of the basic blocks that make up the loop (including
1268 // the loop preheader and exit blocks), keeping track of the mapping between
1269 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001270 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +00001271 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001272 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001273 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +00001274
Evan Chengba930442010-04-05 21:16:25 +00001275 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001276 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +00001277 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001278 }
1279
1280 // Splice the newly inserted blocks into the function right before the
1281 // original preheader.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001282 F->getBasicBlockList().splice(NewPreheader->getIterator(),
1283 F->getBasicBlockList(),
1284 NewBlocks[0]->getIterator(), F->end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001285
1286 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001287 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001288
1289 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1290 // Probably clone more loop-unswitch related loop properties.
1291 BranchesInfo.cloneData(NewLoop, L, VMap);
1292
Chris Lattnerf1b15162006-02-10 23:26:14 +00001293 Loop *ParentLoop = L->getParentLoop();
1294 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +00001295 // Make sure to add the cloned preheader and exit blocks to the parent loop
1296 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +00001297 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001298 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001299
Chris Lattnerf1b15162006-02-10 23:26:14 +00001300 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001301 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +00001302 // The new exit block should be in the same loop as the old one.
1303 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +00001304 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +00001305
Chris Lattnerf1b15162006-02-10 23:26:14 +00001306 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1307 "Exit block should have been split to have one successor!");
1308 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +00001309
Chris Lattnerf1b15162006-02-10 23:26:14 +00001310 // If the successor of the exit block had PHI nodes, add an entry for
1311 // NewExit.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001312 for (PHINode &PN : ExitSucc->phis()) {
1313 Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +00001314 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001315 if (It != VMap.end()) V = It->second;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001316 PN.addIncoming(V, NewExit);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001317 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001318
1319 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +00001320 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001321 &*ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +00001322
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001323 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1324 I != E; ++I) {
1325 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +00001326 LandingPadInst *LPI = BB->getLandingPadInst();
1327 LPI->replaceAllUsesWith(PN);
1328 PN->addIncoming(LPI, BB);
1329 }
1330 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001331 }
1332
1333 // Rewrite the code to refer to itself.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001334 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1335 for (Instruction &I : *NewBlocks[i]) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001336 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001337 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001338 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1339 if (II->getIntrinsicID() == Intrinsic::assume)
1340 AC->registerAssumption(II);
1341 }
1342 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001343
Chris Lattnerf48f7772004-04-19 18:07:02 +00001344 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +00001345 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001346 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +00001347 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +00001348
Alina Sbirleaa4961432018-09-11 19:19:21 +00001349 if (MSSAU) {
1350 // Update MemorySSA after cloning, and before splitting to unreachables,
1351 // since that invalidates the 1:1 mapping of clones in VMap.
1352 LoopBlocksRPO LBRPO(L);
1353 LBRPO.perform(LI);
1354 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1355 }
1356
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001357 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +00001358 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1359 TI);
Devang Pateld4911982007-07-31 08:03:26 +00001360 LPM->deleteSimpleAnalysisValue(OldBR, L);
Alina Sbirleaa4961432018-09-11 19:19:21 +00001361 if (MSSAU) {
1362 // Update MemoryPhis in Exit blocks.
1363 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1364 if (VerifyMemorySSA)
1365 MSSA->verifyMemorySSA();
1366 }
Jakub Kuderskie35a4492017-08-17 16:45:35 +00001367
1368 // The OldBr was replaced by a new one and removed (but not erased) by
1369 // EmitPreheaderBranchOnCondition. It is no longer needed, so delete it.
1370 delete OldBR;
Devang Patela8823282007-08-02 15:25:57 +00001371
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001372 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +00001373 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001374
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001375 // Keep a WeakTrackingVH holding onto LIC. If the first call to
1376 // RewriteLoopBody
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001377 // deletes the instruction (for example by simplifying a PHI that feeds into
1378 // the condition that we're unswitching on), we don't rewrite the second
1379 // iteration.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001380 WeakTrackingVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +00001381
Chris Lattnerf48f7772004-04-19 18:07:02 +00001382 // Now we rewrite the original code to know that the condition is true and the
1383 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +00001384 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +00001385
Chris Lattner5814d9d92010-04-20 05:09:16 +00001386 // It's possible that simplifying one loop could cause the other to be
1387 // changed to another value or a constant. If its a constant, don't simplify
1388 // it.
1389 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1390 LICHandle && !isa<Constant>(LICHandle))
1391 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Alina Sbirleaa4961432018-09-11 19:19:21 +00001392
1393 if (MSSA && VerifyMemorySSA)
1394 MSSA->verifyMemorySSA();
Chris Lattnerf48f7772004-04-19 18:07:02 +00001395}
1396
Sanjay Patel956e29c2015-08-11 21:24:04 +00001397/// Remove all instances of I from the worklist vector specified.
Andrew Trick4104ed92012-04-10 05:14:37 +00001398static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +00001399 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +00001400
1401 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1402 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001403}
1404
Sanjay Patel956e29c2015-08-11 21:24:04 +00001405/// When we find that I really equals V, remove I from the
Chris Lattner6fd13622006-02-17 00:31:07 +00001406/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +00001407static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +00001408 std::vector<Instruction*> &Worklist,
1409 Loop *L, LPPassManager *LPM) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001410 LLVM_DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
Chris Lattner6fd13622006-02-17 00:31:07 +00001411
1412 // Add uses to the worklist, which may be dead now.
1413 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1414 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1415 Worklist.push_back(Use);
1416
1417 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001418 for (User *U : I->users())
1419 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +00001420 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001421 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001422 I->replaceAllUsesWith(V);
Davide Italiano534e3142017-04-29 00:12:18 +00001423 if (!I->mayHaveSideEffects())
1424 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001425 ++NumSimplify;
1426}
1427
Sanjay Patel956e29c2015-08-11 21:24:04 +00001428/// We know either that the value LIC has the value specified by Val in the
1429/// specified loop, or we know it does NOT have that value.
1430/// Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001431void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001432 Constant *Val,
1433 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001434 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001435
Chris Lattnerf48f7772004-04-19 18:07:02 +00001436 // FIXME: Support correlated properties, like:
1437 // for (...)
1438 // if (li1 < li2)
1439 // ...
1440 // if (li1 > li2)
1441 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001442
Chris Lattner6e263152006-02-10 02:30:37 +00001443 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1444 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001445 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001446 LLVMContext &Context = Val->getContext();
1447
Chris Lattner6fd13622006-02-17 00:31:07 +00001448 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1449 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001450 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001451 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001452 Value *Replacement;
1453 if (IsEqual)
1454 Replacement = Val;
1455 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001456 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001457 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001458
Chandler Carruthcdf47882014-03-09 03:16:01 +00001459 for (User *U : LIC->users()) {
1460 Instruction *UI = dyn_cast<Instruction>(U);
1461 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001462 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001463 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001464 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001465
Benjamin Kramer135f7352016-06-26 12:28:59 +00001466 for (Instruction *UI : Worklist)
1467 UI->replaceUsesOfWith(LIC, Replacement);
Andrew Trick4104ed92012-04-10 05:14:37 +00001468
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001469 SimplifyCode(Worklist, L);
1470 return;
1471 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001472
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001473 // Otherwise, we don't know the precise value of LIC, but we do know that it
1474 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1475 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001476 for (User *U : LIC->users()) {
1477 Instruction *UI = dyn_cast<Instruction>(U);
1478 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001479 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001480
Xin Tongec6f90b2017-02-23 23:42:19 +00001481 // At this point, we know LIC is definitely not Val. Try to use some simple
1482 // logic to simplify the user w.r.t. to the context.
1483 if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1484 if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1485 // This in-loop instruction has been simplified w.r.t. its context,
1486 // i.e. LIC != Val, make sure we propagate its replacement value to
1487 // all its users.
Fangrui Songf78650a2018-07-30 19:41:25 +00001488 //
Xin Tongf51d8042017-02-24 01:43:36 +00001489 // We can not yet delete UI, the LIC user, yet, because that would invalidate
1490 // the LIC->users() iterator !. However, we can make this instruction
1491 // dead by replacing all its users and push it onto the worklist so that
Fangrui Songf78650a2018-07-30 19:41:25 +00001492 // it can be properly deleted and its operands simplified.
Xin Tongf51d8042017-02-24 01:43:36 +00001493 UI->replaceAllUsesWith(Replacement);
Xin Tongec6f90b2017-02-23 23:42:19 +00001494 }
1495 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001496
Xin Tong01feb292017-02-28 03:32:41 +00001497 // This is a LIC user, push it into the worklist so that SimplifyCode can
1498 // attempt to simplify it.
Xin Tongec6f90b2017-02-23 23:42:19 +00001499 Worklist.push_back(UI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001500
1501 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001502 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001503 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001504
Xin Tong16b85a62017-02-27 18:00:13 +00001505 // NOTE: if a case value for the switch is unswitched out, we record it
1506 // after the unswitch finishes. We can not record it here as the switch
1507 // is not a direct user of the partial LIV.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001508 SwitchInst::CaseHandle DeadCase =
1509 *SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001510 // Default case is live for multiple values.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001511 if (DeadCase == *SI->case_default())
1512 continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001513
1514 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001515 // successor if they become single-entry, those PHI nodes may
1516 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001517
Evan Cheng1b55f562011-05-24 23:12:57 +00001518 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001519 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001520 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001521
Nick Lewycky61158242011-06-03 06:27:15 +00001522 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001523 // If the DeadCase successor dominates the loop latch, then the
1524 // transformation isn't safe since it will delete the sole predecessor edge
1525 // to the latch.
1526 if (Latch && DT->dominates(SISucc, Latch))
1527 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001528
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001529 // FIXME: This is a hack. We need to keep the successor around
1530 // and hooked up so as to preserve the loop structure, because
1531 // trying to update it is complicated. So instead we preserve the
1532 // loop structure and put the block on a dead code path.
Alina Sbirleaa4961432018-09-11 19:19:21 +00001533 SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001534 // Compute the successors instead of relying on the return value
1535 // of SplitEdge, since it may have split the switch successor
1536 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001537 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001538 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1539 // Create an "unreachable" destination.
1540 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1541 Switch->getParent(),
1542 OldSISucc);
1543 new UnreachableInst(Context, Abort);
1544 // Force the new case destination to branch to the "unreachable"
1545 // block while maintaining a (dead) CFG edge to the old block.
1546 NewSISucc->getTerminator()->eraseFromParent();
1547 BranchInst::Create(Abort, OldSISucc,
1548 ConstantInt::getTrue(Context), NewSISucc);
1549 // Release the PHI operands for this edge.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001550 for (PHINode &PN : NewSISucc->phis())
1551 PN.setIncomingValue(PN.getBasicBlockIndex(Switch),
1552 UndefValue::get(PN.getType()));
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001553 // Tell the domtree about the new block. We don't fully update the
1554 // domtree here -- instead we force it to do a full recomputation
1555 // after the pass is complete -- but we do need to inform it of
1556 // new blocks.
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +00001557 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001558 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001559
Devang Pateld4911982007-07-31 08:03:26 +00001560 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001561}
1562
Sanjay Patel956e29c2015-08-11 21:24:04 +00001563/// Now that we have simplified some instructions in the loop, walk over it and
1564/// constant prop, dce, and fold control flow where possible. Note that this is
1565/// effectively a very simple loop-structure-aware optimizer. During processing
1566/// of this loop, L could very well be deleted, so it must not be used.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001567///
1568/// FIXME: When the loop optimizer is more mature, separate this out to a new
1569/// pass.
1570///
Devang Pateld4911982007-07-31 08:03:26 +00001571void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001572 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001573 while (!Worklist.empty()) {
1574 Instruction *I = Worklist.back();
1575 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001576
Chris Lattner6fd13622006-02-17 00:31:07 +00001577 // Simple DCE.
1578 if (isInstructionTriviallyDead(I)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001579 LLVM_DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001580
Chris Lattner6fd13622006-02-17 00:31:07 +00001581 // Add uses to the worklist, which may be dead now.
1582 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1583 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1584 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001585 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001586 RemoveFromWorklist(I, Worklist);
Alina Sbirleaa4961432018-09-11 19:19:21 +00001587 if (MSSAU)
1588 MSSAU->removeMemoryAccess(I);
Devang Patel83cc3f82007-09-20 23:45:50 +00001589 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001590 ++NumSimplify;
1591 continue;
1592 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001593
Chris Lattner66e809a2010-04-20 05:33:18 +00001594 // See if instruction simplification can hack this up. This is common for
1595 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001596 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001597 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001598 if (LI->replacementPreservesLCSSAForm(I, V)) {
1599 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1600 continue;
1601 }
1602
Chris Lattner6fd13622006-02-17 00:31:07 +00001603 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001604 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001605 if (BI->isUnconditional()) {
1606 // If BI's parent is the only pred of the successor, fold the two blocks
1607 // together.
1608 BasicBlock *Pred = BI->getParent();
1609 BasicBlock *Succ = BI->getSuccessor(0);
1610 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1611 if (!SinglePred) continue; // Nothing to do.
1612 assert(SinglePred == Pred && "CFG broken");
1613
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001614 LLVM_DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1615 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001616
Chris Lattner6fd13622006-02-17 00:31:07 +00001617 // Resolve any single entry PHI nodes in Succ.
1618 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001619 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001620
Jay Foad61ea0e42011-06-23 09:09:15 +00001621 // If Succ has any successors with PHI nodes, update them to have
1622 // entries coming from Pred instead of Succ.
1623 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001624
Chris Lattner6fd13622006-02-17 00:31:07 +00001625 // Move all of the successor contents from Succ to Pred.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001626 Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
1627 Succ->begin(), Succ->end());
Alina Sbirleaa4961432018-09-11 19:19:21 +00001628 if (MSSAU)
1629 MSSAU->moveAllAfterMergeBlocks(Succ, Pred, BI);
Devang Pateld4911982007-07-31 08:03:26 +00001630 LPM->deleteSimpleAnalysisValue(BI, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001631 RemoveFromWorklist(BI, Worklist);
Xin Tong3caaa362017-01-06 21:49:08 +00001632 BI->eraseFromParent();
Andrew Trick4104ed92012-04-10 05:14:37 +00001633
Chris Lattner6fd13622006-02-17 00:31:07 +00001634 // Remove Succ from the loop tree.
1635 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001636 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001637 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001638 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001639 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001640 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001641
Chris Lattner66e809a2010-04-20 05:33:18 +00001642 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001643 }
1644 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001645}
Xin Tongec6f90b2017-02-23 23:42:19 +00001646
1647/// Simple simplifications we can do given the information that Cond is
1648/// definitely not equal to Val.
1649Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
1650 Value *Invariant,
1651 Constant *Val) {
1652 // icmp eq cond, val -> false
1653 ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1654 if (CI && CI->isEquality()) {
1655 Value *Op0 = CI->getOperand(0);
1656 Value *Op1 = CI->getOperand(1);
1657 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1658 LLVMContext &Ctx = Inst->getContext();
1659 if (CI->getPredicate() == CmpInst::ICMP_EQ)
1660 return ConstantInt::getFalse(Ctx);
Fangrui Songf78650a2018-07-30 19:41:25 +00001661 else
Xin Tongec6f90b2017-02-23 23:42:19 +00001662 return ConstantInt::getTrue(Ctx);
1663 }
1664 }
1665
1666 // FIXME: there may be other opportunities, e.g. comparison with floating
1667 // point, or Invariant - Val != 0, etc.
1668 return nullptr;
1669}