blob: 977c53a3bc6327046fb53d31c9eaf8bddfef26b9 [file] [log] [blame]
Chris Lattner18f16092004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner18f16092004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner18f16092004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
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
Chris Lattner18f16092004-04-19 18:07:02 +000029#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Analysis/InstructionSimplify.h"
35#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Analysis/LoopPass.h"
37#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carrutha5157e62013-01-21 13:04:33 +000038#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000039#include "llvm/IR/Constants.h"
40#include "llvm/IR/DerivedTypes.h"
Stephen Hines36b56882014-04-23 16:57:46 -070041#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000042#include "llvm/IR/Function.h"
43#include "llvm/IR/Instructions.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000044#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000045#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000046#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Cloning.h"
49#include "llvm/Transforms/Utils/Local.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000050#include <algorithm>
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000051#include <map>
Chris Lattner2f4b8982006-02-09 19:14:52 +000052#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000053using namespace llvm;
54
Stephen Hinesdce4a402014-05-29 02:49:00 -070055#define DEBUG_TYPE "loop-unswitch"
56
Chris Lattner0e5f4992006-12-19 21:40:18 +000057STATISTIC(NumBranches, "Number of branches unswitched");
58STATISTIC(NumSwitches, "Number of switches unswitched");
59STATISTIC(NumSelects , "Number of selects unswitched");
60STATISTIC(NumTrivial , "Number of unswitches that are trivial");
61STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +000062STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000063
Stepan Dyatkovskiy27bf5602012-01-16 20:48:04 +000064// The specific value of 100 here was chosen based only on intuition and a
Dan Gohmanb24f6c72009-10-13 17:50:43 +000065// few specific examples.
Dan Gohman844731a2008-05-13 00:00:25 +000066static cl::opt<unsigned>
67Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +000068 cl::init(100), cl::Hidden);
Andrew Trick64c07482012-04-10 05:14:37 +000069
Dan Gohman844731a2008-05-13 00:00:25 +000070namespace {
Andrew Trick64c07482012-04-10 05:14:37 +000071
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000072 class LUAnalysisCache {
73
74 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
75 UnswitchedValsMap;
Andrew Trick64c07482012-04-10 05:14:37 +000076
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000077 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick64c07482012-04-10 05:14:37 +000078
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000079 struct LoopProperties {
80 unsigned CanBeUnswitchedCount;
81 unsigned SizeEstimation;
82 UnswitchedValsMap UnswitchedVals;
83 };
Andrew Trick64c07482012-04-10 05:14:37 +000084
85 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000086 // LoopProperties pointer for current loop for better performance.
87 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
88 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick64c07482012-04-10 05:14:37 +000089
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000090 LoopPropsMap LoopsProperties;
Jakub Staszak7198ee62013-08-06 17:03:42 +000091 UnswitchedValsMap *CurLoopInstructions;
92 LoopProperties *CurrentLoopProperties;
Andrew Trick64c07482012-04-10 05:14:37 +000093
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000094 // Max size of code we can produce on remained iterations.
95 unsigned MaxSize;
Andrew Trick64c07482012-04-10 05:14:37 +000096
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000097 public:
Andrew Trick64c07482012-04-10 05:14:37 +000098
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000099 LUAnalysisCache() :
Stephen Hinesdce4a402014-05-29 02:49:00 -0700100 CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000101 MaxSize(Threshold)
102 {}
Andrew Trick64c07482012-04-10 05:14:37 +0000103
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000104 // Analyze loop. Check its size, calculate is it possible to unswitch
105 // it. Returns true if we can unswitch this loop.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000106 bool countLoop(const Loop *L, const TargetTransformInfo &TTI);
Andrew Trick64c07482012-04-10 05:14:37 +0000107
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000108 // Clean all data related to given loop.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000109 void forgetLoop(const Loop *L);
Andrew Trick64c07482012-04-10 05:14:37 +0000110
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000111 // Mark case value as unswitched.
112 // Since SI instruction can be partly unswitched, in order to avoid
113 // extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000114 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick64c07482012-04-10 05:14:37 +0000115
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000116 // Check was this case value unswitched before or not.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000117 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick64c07482012-04-10 05:14:37 +0000118
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000119 // Clone all loop-unswitch related loop properties.
120 // Redistribute unswitching quotas.
121 // Note, that new loop data is stored inside the VMap.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000122 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
123 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000124 };
Andrew Trick64c07482012-04-10 05:14:37 +0000125
Chris Lattner3e8b6632009-09-02 06:11:42 +0000126 class LoopUnswitch : public LoopPass {
Chris Lattner18f16092004-04-19 18:07:02 +0000127 LoopInfo *LI; // Loop information
Devang Patel1bc89362007-03-07 00:26:10 +0000128 LPPassManager *LPM;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000129
Devang Patel1bc89362007-03-07 00:26:10 +0000130 // LoopProcessWorklist - Used to check if second loop needs processing
131 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000132 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000133
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000134 LUAnalysisCache BranchesInfo;
Andrew Trick64c07482012-04-10 05:14:37 +0000135
Devang Patel743f7e82007-06-06 00:21:03 +0000136 bool OptimizeForSize;
Devang Patel6f62af62007-07-30 23:07:10 +0000137 bool redoLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000138
Devang Patele6962df2008-07-02 01:18:13 +0000139 Loop *currentLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000140 DominatorTree *DT;
Devang Patele6962df2008-07-02 01:18:13 +0000141 BasicBlock *loopHeader;
142 BasicBlock *loopPreheader;
Andrew Trick64c07482012-04-10 05:14:37 +0000143
Devang Patel1e41f6d2008-07-02 01:44:29 +0000144 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick64c07482012-04-10 05:14:37 +0000145 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Patel1e41f6d2008-07-02 01:44:29 +0000146 // loop, in that order.
147 std::vector<BasicBlock*> LoopBlocks;
148 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
149 std::vector<BasicBlock*> NewBlocks;
Devang Patel77a01132008-07-03 17:37:52 +0000150
Chris Lattner18f16092004-04-19 18:07:02 +0000151 public:
Devang Patel19974732007-05-03 01:11:54 +0000152 static char ID; // Pass ID, replacement for typeid
Andrew Trick64c07482012-04-10 05:14:37 +0000153 explicit LoopUnswitch(bool Os = false) :
154 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Stephen Hinesdce4a402014-05-29 02:49:00 -0700155 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
156 loopPreheader(nullptr) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000157 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
158 }
Devang Patel794fd752007-05-01 21:15:47 +0000159
Stephen Hines36b56882014-04-23 16:57:46 -0700160 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele6962df2008-07-02 01:18:13 +0000161 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +0000162
163 /// This transformation requires natural loop information & requires that
Chris Lattnerea109232010-08-29 17:23:19 +0000164 /// loop preheaders be inserted into the CFG.
Chris Lattner18f16092004-04-19 18:07:02 +0000165 ///
Stephen Hines36b56882014-04-23 16:57:46 -0700166 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner18f16092004-04-19 18:07:02 +0000167 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000168 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000169 AU.addRequired<LoopInfo>();
170 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000171 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000172 AU.addPreservedID(LCSSAID);
Stephen Hines36b56882014-04-23 16:57:46 -0700173 AU.addPreserved<DominatorTreeWrapperPass>();
Cameron Zwarich71132af2011-02-11 06:08:28 +0000174 AU.addPreserved<ScalarEvolution>();
Chandler Carrutha5157e62013-01-21 13:04:33 +0000175 AU.addRequired<TargetTransformInfo>();
Chris Lattner18f16092004-04-19 18:07:02 +0000176 }
177
178 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000179
Stephen Hines36b56882014-04-23 16:57:46 -0700180 void releaseMemory() override {
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000181 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman5c89b522009-09-08 15:45:00 +0000182 }
183
Devang Patele6962df2008-07-02 01:18:13 +0000184 void initLoopData() {
185 loopHeader = currentLoop->getHeader();
186 loopPreheader = currentLoop->getLoopPreheader();
187 }
Andrew Trick64c07482012-04-10 05:14:37 +0000188
Chris Lattner48a80b02008-04-21 00:25:49 +0000189 /// Split all of the edges from inside the loop to their exit blocks.
190 /// Update the appropriate Phi nodes as we do so.
Craig Toppera0ec3f92013-07-14 04:42:23 +0000191 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000192
Devang Patele6962df2008-07-02 01:18:13 +0000193 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000194 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000195 BasicBlock *ExitBlock);
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000196 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000197
198 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
199 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000200
201 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick64c07482012-04-10 05:14:37 +0000202 BasicBlock *TrueDest,
Devang Patelcce624a2007-06-28 00:49:00 +0000203 BasicBlock *FalseDest,
204 Instruction *InsertPt);
205
Devang Patel15c260a2007-07-31 08:03:26 +0000206 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700207 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
208 BasicBlock **LoopExit = nullptr);
Devang Patele6962df2008-07-02 01:18:13 +0000209
Chris Lattner18f16092004-04-19 18:07:02 +0000210 };
Chris Lattner18f16092004-04-19 18:07:02 +0000211}
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000212
213// Analyze loop. Check its size, calculate is it possible to unswitch
214// it. Returns true if we can unswitch this loop.
Chandler Carrutha5157e62013-01-21 13:04:33 +0000215bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) {
Andrew Trick64c07482012-04-10 05:14:37 +0000216
Jakub Staszak7198ee62013-08-06 17:03:42 +0000217 LoopPropsMapIt PropsIt;
218 bool Inserted;
Stephen Hines36b56882014-04-23 16:57:46 -0700219 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000220 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick64c07482012-04-10 05:14:37 +0000221
Jakub Staszak7198ee62013-08-06 17:03:42 +0000222 LoopProperties &Props = PropsIt->second;
Andrew Trick64c07482012-04-10 05:14:37 +0000223
Jakub Staszak7198ee62013-08-06 17:03:42 +0000224 if (Inserted) {
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000225 // New loop.
226
227 // Limit the number of instructions to avoid causing significant code
228 // expansion, and the number of basic blocks, to avoid loops with
229 // large numbers of branches which cause loop unswitching to go crazy.
230 // This is a very ad-hoc heuristic.
Andrew Trick64c07482012-04-10 05:14:37 +0000231
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000232 // FIXME: This is overly conservative because it does not take into
233 // consideration code simplification opportunities and code that can
234 // be shared by the resultant unswitched loops.
235 CodeMetrics Metrics;
Jakub Staszak7198ee62013-08-06 17:03:42 +0000236 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000237 I != E; ++I)
Chandler Carrutha5157e62013-01-21 13:04:33 +0000238 Metrics.analyzeBasicBlock(*I, TTI);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000239
240 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
241 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
242 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy67ae1352012-12-20 16:04:27 +0000243
244 if (Metrics.notDuplicatable) {
245 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak7198ee62013-08-06 17:03:42 +0000246 << L->getHeader()->getName() << ", contents cannot be "
247 << "duplicated!\n");
James Molloy67ae1352012-12-20 16:04:27 +0000248 return false;
249 }
Andrew Trick64c07482012-04-10 05:14:37 +0000250 }
251
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000252 if (!Props.CanBeUnswitchedCount) {
253 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak7198ee62013-08-06 17:03:42 +0000254 << L->getHeader()->getName() << ", cost too high: "
255 << L->getBlocks().size() << "\n");
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000256 return false;
257 }
Andrew Trick64c07482012-04-10 05:14:37 +0000258
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000259 // Be careful. This links are good only before new loop addition.
260 CurrentLoopProperties = &Props;
261 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick64c07482012-04-10 05:14:37 +0000262
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000263 return true;
264}
265
266// Clean all data related to given loop.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000267void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick64c07482012-04-10 05:14:37 +0000268
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000269 LoopPropsMapIt LIt = LoopsProperties.find(L);
270
271 if (LIt != LoopsProperties.end()) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000272 LoopProperties &Props = LIt->second;
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000273 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
274 LoopsProperties.erase(LIt);
275 }
Andrew Trick64c07482012-04-10 05:14:37 +0000276
Stephen Hinesdce4a402014-05-29 02:49:00 -0700277 CurrentLoopProperties = nullptr;
278 CurLoopInstructions = nullptr;
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000279}
280
281// Mark case value as unswitched.
282// Since SI instruction can be partly unswitched, in order to avoid
283// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000284void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000285 (*CurLoopInstructions)[SI].insert(V);
286}
287
288// Check was this case value unswitched before or not.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000289bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick64c07482012-04-10 05:14:37 +0000290 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000291}
292
293// Clone all loop-unswitch related loop properties.
294// Redistribute unswitching quotas.
295// Note, that new loop data is stored inside the VMap.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000296void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
297 const ValueToValueMapTy &VMap) {
Andrew Trick64c07482012-04-10 05:14:37 +0000298
Jakub Staszak7198ee62013-08-06 17:03:42 +0000299 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
300 LoopProperties &OldLoopProps = *CurrentLoopProperties;
301 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick64c07482012-04-10 05:14:37 +0000302
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000303 // Reallocate "can-be-unswitched quota"
304
305 --OldLoopProps.CanBeUnswitchedCount;
306 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
307 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
308 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick64c07482012-04-10 05:14:37 +0000309
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000310 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick64c07482012-04-10 05:14:37 +0000311
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000312 // Clone unswitched values info:
313 // for new loop switches we clone info about values that was
314 // already unswitched and has redundant successors.
315 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000316 const SwitchInst *OldInst = I->first;
317 Value *NewI = VMap.lookup(OldInst);
318 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000319 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick64c07482012-04-10 05:14:37 +0000320
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000321 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
322 }
323}
324
Dan Gohman844731a2008-05-13 00:00:25 +0000325char LoopUnswitch::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000326INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
327 false, false)
Chandler Carrutha5157e62013-01-21 13:04:33 +0000328INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000329INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
330INITIALIZE_PASS_DEPENDENCY(LoopInfo)
331INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000332INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
333 false, false)
Chris Lattner18f16092004-04-19 18:07:02 +0000334
Andrew Trick64c07482012-04-10 05:14:37 +0000335Pass *llvm::createLoopUnswitchPass(bool Os) {
336 return new LoopUnswitch(Os);
Devang Patel743f7e82007-06-06 00:21:03 +0000337}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000338
339/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
340/// invariant in the loop, or has an invariant piece, return the invariant.
341/// Otherwise, return null.
342static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick64c07482012-04-10 05:14:37 +0000343
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000344 // We started analyze new instruction, increment scanned instructions counter.
345 ++TotalInsts;
Andrew Trick64c07482012-04-10 05:14:37 +0000346
Chris Lattner3d606bb2010-02-02 02:26:54 +0000347 // We can never unswitch on vector conditions.
Duncan Sands1df98592010-02-16 11:11:14 +0000348 if (Cond->getType()->isVectorTy())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700349 return nullptr;
Chris Lattner3d606bb2010-02-02 02:26:54 +0000350
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000351 // Constants should be folded, not unswitched on!
Stephen Hinesdce4a402014-05-29 02:49:00 -0700352 if (isa<Constant>(Cond)) return nullptr;
Devang Patel558f1b82007-06-28 00:44:10 +0000353
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000354 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patel265ca5d2008-11-03 19:38:07 +0000355
Dan Gohman0df6e092009-07-14 01:37:59 +0000356 // Hoist simple values out.
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000357 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman0df6e092009-07-14 01:37:59 +0000358 return Cond;
Dan Gohman0df6e092009-07-14 01:37:59 +0000359
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000360 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
361 if (BO->getOpcode() == Instruction::And ||
362 BO->getOpcode() == Instruction::Or) {
363 // If either the left or right side is invariant, we can unswitch on this,
364 // which will cause the branch to go away in one loop and the condition to
365 // simplify in the other one.
366 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
367 return LHS;
368 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
369 return RHS;
370 }
Andrew Trick64c07482012-04-10 05:14:37 +0000371
Stephen Hinesdce4a402014-05-29 02:49:00 -0700372 return nullptr;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000373}
374
Devang Patel1bc89362007-03-07 00:26:10 +0000375bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Stephen Hines36b56882014-04-23 16:57:46 -0700376 if (skipOptnoneFunction(L))
377 return false;
378
Devang Patel1bc89362007-03-07 00:26:10 +0000379 LI = &getAnalysis<LoopInfo>();
380 LPM = &LPM_Ref;
Stephen Hines36b56882014-04-23 16:57:46 -0700381 DominatorTreeWrapperPass *DTWP =
382 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700383 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Devang Patele6962df2008-07-02 01:18:13 +0000384 currentLoop = L;
Devang Pateldeafefa2008-09-04 22:43:59 +0000385 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000386 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000387 do {
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000388 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel6f62af62007-07-30 23:07:10 +0000389 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000390 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000391 } while(redoLoop);
392
Devang Pateldeafefa2008-09-04 22:43:59 +0000393 if (Changed) {
394 // FIXME: Reconstruct dom info, because it is not preserved properly.
395 if (DT)
Stephen Hines36b56882014-04-23 16:57:46 -0700396 DT->recalculate(*F);
Devang Pateldeafefa2008-09-04 22:43:59 +0000397 }
Devang Patel6f62af62007-07-30 23:07:10 +0000398 return Changed;
399}
400
Andrew Trick64c07482012-04-10 05:14:37 +0000401/// processCurrentLoop - Do actual work and unswitch loop if possible
Devang Patele6962df2008-07-02 01:18:13 +0000402/// and profitable.
403bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000404 bool Changed = false;
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000405
406 initLoopData();
Andrew Trick64c07482012-04-10 05:14:37 +0000407
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000408 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
409 if (!loopPreheader)
410 return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000411
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000412 // Loops with indirectbr cannot be cloned.
413 if (!currentLoop->isSafeToClone())
414 return false;
415
416 // Without dedicated exits, splitting the exit edge may fail.
417 if (!currentLoop->hasDedicatedExits())
418 return false;
419
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000420 LLVMContext &Context = loopHeader->getContext();
Andrew Trick64c07482012-04-10 05:14:37 +0000421
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000422 // Probably we reach the quota of branches for this loop. If so
423 // stop unswitching.
Chandler Carrutha5157e62013-01-21 13:04:33 +0000424 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>()))
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000425 return false;
Devang Patel6f62af62007-07-30 23:07:10 +0000426
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000427 // Loop over all of the basic blocks in the loop. If we find an interior
428 // block that is branching on a loop-invariant condition, we can unswitch this
429 // loop.
Andrew Trick64c07482012-04-10 05:14:37 +0000430 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattner9e185802010-04-05 21:18:32 +0000431 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000432 TerminatorInst *TI = (*I)->getTerminator();
433 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
434 // If this isn't branching on an invariant condition, we can't unswitch
435 // it.
436 if (BI->isConditional()) {
437 // See if this, or some part of it, is loop invariant. If so, we can
438 // unswitch on it if we desire.
Andrew Trick64c07482012-04-10 05:14:37 +0000439 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele6962df2008-07-02 01:18:13 +0000440 currentLoop, Changed);
Andrew Trick64c07482012-04-10 05:14:37 +0000441 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000442 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000443 ++NumBranches;
444 return true;
445 }
Andrew Trick64c07482012-04-10 05:14:37 +0000446 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000447 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick64c07482012-04-10 05:14:37 +0000448 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele6962df2008-07-02 01:18:13 +0000449 currentLoop, Changed);
Andrew Trick64c07482012-04-10 05:14:37 +0000450 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +0000451 if (LoopCond && NumCases) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000452 // Find a value to unswitch on:
453 // FIXME: this should chose the most expensive case!
Nick Lewycky444f2972011-06-03 06:27:15 +0000454 // FIXME: scan for a case with a non-critical edge?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700455 Constant *UnswitchVal = nullptr;
Andrew Trick64c07482012-04-10 05:14:37 +0000456
Devang Patel52956922007-02-26 19:31:58 +0000457 // Do not process same value again and again.
Chad Rosiera816bf72011-12-22 21:10:46 +0000458 // At this point we have some cases already unswitched and
459 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +0000460 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000461 i != e; ++i) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000462 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000463 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosiera816bf72011-12-22 21:10:46 +0000464 UnswitchVal = UnswitchValCandidate;
465 break;
466 }
467 }
Andrew Trick64c07482012-04-10 05:14:37 +0000468
Chad Rosiera816bf72011-12-22 21:10:46 +0000469 if (!UnswitchVal)
Devang Patel52956922007-02-26 19:31:58 +0000470 continue;
Devang Patel52956922007-02-26 19:31:58 +0000471
Devang Patele6962df2008-07-02 01:18:13 +0000472 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000473 ++NumSwitches;
474 return true;
475 }
476 }
477 }
Andrew Trick64c07482012-04-10 05:14:37 +0000478
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000479 // Scan the instructions to check for unswitchable values.
Andrew Trick64c07482012-04-10 05:14:37 +0000480 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000481 BBI != E; ++BBI)
482 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick64c07482012-04-10 05:14:37 +0000483 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele6962df2008-07-02 01:18:13 +0000484 currentLoop, Changed);
Andrew Trick64c07482012-04-10 05:14:37 +0000485 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000486 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000487 ++NumSelects;
488 return true;
489 }
490 }
491 }
Chris Lattner18f16092004-04-19 18:07:02 +0000492 return Changed;
493}
494
Dan Gohmanb0a57212010-09-01 21:46:45 +0000495/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
496/// loop with no side effects (including infinite loops).
Chris Lattner4e132392006-02-15 22:03:36 +0000497///
Dan Gohmanb0a57212010-09-01 21:46:45 +0000498/// If true, we return true and set ExitBB to the block we
Chris Lattner4e132392006-02-15 22:03:36 +0000499/// exit through.
500///
501static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
502 BasicBlock *&ExitBB,
503 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000504 if (!Visited.insert(BB).second) {
Nick Lewycky8a5641d2011-12-23 23:49:25 +0000505 // Already visited. Without more analysis, this could indicate an infinite
506 // loop.
Dan Gohmanb0a57212010-09-01 21:46:45 +0000507 return false;
Jakub Staszak7198ee62013-08-06 17:03:42 +0000508 }
509 if (!L->contains(BB)) {
Chris Lattner0017d482006-02-17 06:39:56 +0000510 // Otherwise, this is a loop exit, this is fine so long as this is the
511 // first exit.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700512 if (ExitBB) return false;
Chris Lattner0017d482006-02-17 06:39:56 +0000513 ExitBB = BB;
Edward O'Callaghan25798432009-11-25 05:38:41 +0000514 return true;
Chris Lattner0017d482006-02-17 06:39:56 +0000515 }
Andrew Trick64c07482012-04-10 05:14:37 +0000516
Chris Lattner0017d482006-02-17 06:39:56 +0000517 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000518 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000519 // Check to see if the successor is a trivial loop exit.
520 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
521 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000522 }
Chris Lattner4e132392006-02-15 22:03:36 +0000523
524 // Okay, everything after this looks good, check to make sure that this block
525 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000526 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000527 if (I->mayHaveSideEffects())
Chris Lattner4e132392006-02-15 22:03:36 +0000528 return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000529
Chris Lattner4e132392006-02-15 22:03:36 +0000530 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000531}
532
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000533/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
Andrew Trick64c07482012-04-10 05:14:37 +0000534/// leads to an exit from the specified loop, and has no side-effects in the
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000535/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000536static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
537 std::set<BasicBlock*> Visited;
Dan Gohmanb0a57212010-09-01 21:46:45 +0000538 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700539 BasicBlock *ExitBB = nullptr;
Chris Lattner4e132392006-02-15 22:03:36 +0000540 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
541 return ExitBB;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700542 return nullptr;
Chris Lattner4e132392006-02-15 22:03:36 +0000543}
Chris Lattner708e1a52006-02-10 02:30:37 +0000544
Chris Lattner4c41d492006-02-10 01:24:09 +0000545/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
546/// trivial: that is, that the condition controls whether or not the loop does
547/// anything at all. If this is a trivial condition, unswitching produces no
548/// code duplications (equivalently, it produces a simpler loop and a new empty
549/// loop, which gets deleted).
550///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000551/// If this is a trivial condition, return true, otherwise return false. When
552/// returning true, this sets Cond and Val to the condition that controls the
553/// trivial condition: when Cond dynamically equals Val, the loop is known to
554/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
555/// Cond == Val.
556///
Devang Patele6962df2008-07-02 01:18:13 +0000557bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
558 BasicBlock **LoopExit) {
559 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000560 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Andersone922c022009-07-22 00:24:57 +0000561 LLVMContext &Context = Header->getContext();
Andrew Trick64c07482012-04-10 05:14:37 +0000562
Stephen Hinesdce4a402014-05-29 02:49:00 -0700563 BasicBlock *LoopExitBB = nullptr;
Chris Lattnera48654e2006-02-15 22:52:05 +0000564 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
565 // If the header block doesn't end with a conditional branch on Cond, we
566 // can't handle it.
567 if (!BI->isConditional() || BI->getCondition() != Cond)
568 return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000569
570 // Check to see if a successor of the branch is guaranteed to
571 // exit through a unique exit block without having any
Chris Lattnera48654e2006-02-15 22:52:05 +0000572 // side-effects. If so, determine the value of Cond that causes it to do
573 // this.
Andrew Trick64c07482012-04-10 05:14:37 +0000574 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele6962df2008-07-02 01:18:13 +0000575 BI->getSuccessor(0)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000576 if (Val) *Val = ConstantInt::getTrue(Context);
Andrew Trick64c07482012-04-10 05:14:37 +0000577 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele6962df2008-07-02 01:18:13 +0000578 BI->getSuccessor(1)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000579 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnera48654e2006-02-15 22:52:05 +0000580 }
581 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
582 // If this isn't a switch on Cond, we can't handle it.
583 if (SI->getCondition() != Cond) return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000584
Chris Lattnera48654e2006-02-15 22:52:05 +0000585 // Check to see if a successor of the switch is guaranteed to go to the
Andrew Trick64c07482012-04-10 05:14:37 +0000586 // latch block or exit through a one exit block without having any
Chris Lattnera48654e2006-02-15 22:52:05 +0000587 // side-effects. If so, determine the value of Cond that causes it to do
Andrew Trick64c07482012-04-10 05:14:37 +0000588 // this.
Chad Rosiera816bf72011-12-22 21:10:46 +0000589 // Note that we can't trivially unswitch on the default case or
590 // on already unswitched cases.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +0000591 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000592 i != e; ++i) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000593 BasicBlock *LoopExitCandidate;
Andrew Trick64c07482012-04-10 05:14:37 +0000594 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000595 i.getCaseSuccessor()))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000596 // Okay, we found a trivial case, remember the value that is trivial.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000597 ConstantInt *CaseVal = i.getCaseValue();
Chad Rosiera816bf72011-12-22 21:10:46 +0000598
599 // Check that it was not unswitched before, since already unswitched
600 // trivial vals are looks trivial too.
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000601 if (BranchesInfo.isUnswitched(SI, CaseVal))
Chad Rosiera816bf72011-12-22 21:10:46 +0000602 continue;
603 LoopExitBB = LoopExitCandidate;
604 if (Val) *Val = CaseVal;
Chris Lattnera48654e2006-02-15 22:52:05 +0000605 break;
606 }
Chad Rosiera816bf72011-12-22 21:10:46 +0000607 }
Chris Lattner4e132392006-02-15 22:03:36 +0000608 }
609
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000610 // If we didn't find a single unique LoopExit block, or if the loop exit block
611 // contains phi nodes, this isn't trivial.
612 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000613 return false; // Can't handle this.
Andrew Trick64c07482012-04-10 05:14:37 +0000614
Chris Lattnera48654e2006-02-15 22:52:05 +0000615 if (LoopExit) *LoopExit = LoopExitBB;
Andrew Trick64c07482012-04-10 05:14:37 +0000616
Chris Lattner4c41d492006-02-10 01:24:09 +0000617 // We already know that nothing uses any scalar values defined inside of this
618 // loop. As such, we just have to check to see if this loop will execute any
619 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000620 // part of the loop that the code *would* execute. We already checked the
621 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000622 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000623 if (I->mayHaveSideEffects())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000624 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000625 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000626}
627
Devang Patele6962df2008-07-02 01:18:13 +0000628/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000629/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
630/// unswitch the loop, reprocess the pieces, then return true.
Chris Lattner3d606bb2010-02-02 02:26:54 +0000631bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
Dan Gohmanf68d0c12009-12-09 22:55:01 +0000632 Function *F = loopHeader->getParent();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700633 Constant *CondVal = nullptr;
634 BasicBlock *ExitBlock = nullptr;
Bill Wendling6aa33272012-04-30 09:23:48 +0000635
Devang Patele6962df2008-07-02 01:18:13 +0000636 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Cheng02720242010-04-03 02:23:43 +0000637 // If the condition is trivial, always unswitch. There is no code growth
638 // for this case.
Devang Patele6962df2008-07-02 01:18:13 +0000639 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Evan Cheng02720242010-04-03 02:23:43 +0000640 return true;
Chris Lattnerc2358092006-02-11 00:43:37 +0000641 }
Devang Patel4be7d292008-07-03 06:48:21 +0000642
Evan Cheng02720242010-04-03 02:23:43 +0000643 // Check to see if it would be profitable to unswitch current loop.
644
645 // Do not do non-trivial unswitch while optimizing for size.
Bill Wendling67658342012-10-09 07:45:08 +0000646 if (OptimizeForSize ||
Bill Wendling831737d2012-12-30 10:32:01 +0000647 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
648 Attribute::OptimizeForSize))
Evan Cheng02720242010-04-03 02:23:43 +0000649 return false;
650
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000651 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
652 return true;
Chris Lattnerc2358092006-02-11 00:43:37 +0000653}
654
Chris Lattner18f16092004-04-19 18:07:02 +0000655/// CloneLoop - Recursively clone the specified loop and all of its children,
656/// mapping the blocks with the specified map.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000657static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000658 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000659 Loop *New = new Loop();
Devang Patel1bc89362007-03-07 00:26:10 +0000660 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000661
662 // Add all of the blocks in L to the new loop.
663 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
664 I != E; ++I)
665 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000666 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000667
668 // Add all of the subloops to the new loop.
669 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000670 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000671
Chris Lattner18f16092004-04-19 18:07:02 +0000672 return New;
673}
674
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000675/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
676/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
677/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000678void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
679 BasicBlock *TrueDest,
680 BasicBlock *FalseDest,
681 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000682 // Insert a conditional branch on LIC to the two preheaders. The original
683 // code is the true version and the new code is the false version.
684 Value *BranchVal = LIC;
Owen Anderson1d0be152009-08-13 21:58:54 +0000685 if (!isa<ConstantInt>(Val) ||
686 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramera9390a42011-09-27 20:39:19 +0000687 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Owen Anderson5defacc2009-07-31 17:39:07 +0000688 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000689 // We want to enter the new loop when the condition is true.
690 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000691
692 // Insert the new branch.
Dan Gohman5c89b522009-09-08 15:45:00 +0000693 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
694
695 // If either edge is critical, split it. This helps preserve LoopSimplify
696 // form for enclosing loops.
Bill Wendlingbfbab992012-04-30 10:44:54 +0000697 SplitCriticalEdge(BI, 0, this, false, false, true);
698 SplitCriticalEdge(BI, 1, this, false, false, true);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000699}
700
Chris Lattner4c41d492006-02-10 01:24:09 +0000701/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
702/// condition in it (a cond branch from its header block to its latch block,
Andrew Trick64c07482012-04-10 05:14:37 +0000703/// where the path through the loop that doesn't execute its body has no
Chris Lattner4c41d492006-02-10 01:24:09 +0000704/// side-effects), unswitch it. This doesn't involve any code duplication, just
705/// moving the conditional branch outside of the loop and updating loop info.
Andrew Trick64c07482012-04-10 05:14:37 +0000706void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
707 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000708 BasicBlock *ExitBlock) {
David Greened4c56fb2010-01-05 01:27:04 +0000709 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000710 << loopHeader->getName() << " [" << L->getBlocks().size()
711 << " blocks] in Function " << L->getHeader()->getParent()->getName()
712 << " on cond: " << *Val << " == " << *Cond << "\n");
Andrew Trick64c07482012-04-10 05:14:37 +0000713
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000714 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000715 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000716 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000717 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000718
719 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000720 // to branch to: this is the exit block out of the loop that we should
721 // short-circuit to.
Andrew Trick64c07482012-04-10 05:14:37 +0000722
Chris Lattner4e132392006-02-15 22:03:36 +0000723 // Split this block now, so that the loop maintains its exit block, and so
724 // that the jump from the preheader can execute the contents of the exit block
725 // without actually branching to it (the exit block should be dominated by the
726 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000727 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000728 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Andrew Trick64c07482012-04-10 05:14:37 +0000729
730 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattner4c41d492006-02-10 01:24:09 +0000731 // insert the new conditional branch.
Andrew Trick64c07482012-04-10 05:14:37 +0000732 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000733 loopPreheader->getTerminator());
Devang Patele6962df2008-07-02 01:18:13 +0000734 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
735 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000736
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000737 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000738 redoLoop = true;
Andrew Trick64c07482012-04-10 05:14:37 +0000739
Chris Lattner4c41d492006-02-10 01:24:09 +0000740 // Now that we know that the loop is never entered when this condition is a
741 // particular value, rewrite the loop with this info. We know that this will
742 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000743 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000744 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000745}
746
Chris Lattner48a80b02008-04-21 00:25:49 +0000747/// SplitExitEdges - Split all of the edges from inside the loop to their exit
748/// blocks. Update the appropriate Phi nodes as we do so.
Andrew Trick64c07482012-04-10 05:14:37 +0000749void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000750 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000751
Chris Lattner4c41d492006-02-10 01:24:09 +0000752 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000753 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman5c89b522009-09-08 15:45:00 +0000754 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
755 pred_end(ExitBlock));
Bill Wendlingd5520982011-09-27 00:59:31 +0000756
Nick Lewycky444f2972011-06-03 06:27:15 +0000757 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
758 // general, if we call it on all predecessors of all exits then it does.
Bill Wendlingd5520982011-09-27 00:59:31 +0000759 if (!ExitBlock->isLandingPad()) {
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000760 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
Bill Wendlingd5520982011-09-27 00:59:31 +0000761 } else {
762 SmallVector<BasicBlock*, 2> NewBBs;
763 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
764 this, NewBBs);
765 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000766 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000767}
768
Andrew Trick64c07482012-04-10 05:14:37 +0000769/// UnswitchNontrivialCondition - We determined that the loop is profitable
770/// to unswitch when LIC equal Val. Split it into loop versions and test the
Devang Patelc1e26602007-10-03 21:17:43 +0000771/// condition outside of either loop. Return the loops created as Out1/Out2.
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000772void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Devang Patelf476e8e2007-10-03 21:16:08 +0000773 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000774 Function *F = loopHeader->getParent();
David Greened4c56fb2010-01-05 01:27:04 +0000775 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000776 << loopHeader->getName() << " [" << L->getBlocks().size()
777 << " blocks] in Function " << F->getName()
778 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patelf476e8e2007-10-03 21:16:08 +0000779
Cameron Zwarich71132af2011-02-11 06:08:28 +0000780 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
781 SE->forgetLoop(L);
782
Devang Patel1e41f6d2008-07-02 01:44:29 +0000783 LoopBlocks.clear();
784 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000785
786 // First step, split the preheader and exit blocks, and add these blocks to
787 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000788 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000789 LoopBlocks.push_back(NewPreheader);
790
791 // We want the loop to come after the preheader, but before the exit blocks.
792 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
793
794 SmallVector<BasicBlock*, 8> ExitBlocks;
795 L->getUniqueExitBlocks(ExitBlocks);
796
797 // Split all of the edges from inside the loop to their exit blocks. Update
798 // the appropriate Phi nodes as we do so.
Devang Patel77a01132008-07-03 17:37:52 +0000799 SplitExitEdges(L, ExitBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000800
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000801 // The exit blocks may have been changed due to edge splitting, recompute.
802 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000803 L->getUniqueExitBlocks(ExitBlocks);
804
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000805 // Add exit blocks to the loop blocks.
806 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000807
808 // Next step, clone all of the basic blocks that make up the loop (including
809 // the loop preheader and exit blocks), keeping track of the mapping between
810 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000811 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000812 ValueToValueMapTy VMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000813 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000814 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick64c07482012-04-10 05:14:37 +0000815
Evan Cheng0f1666b2010-04-05 21:16:25 +0000816 NewBlocks.push_back(NewBB);
Devang Patele9916a32010-06-24 00:33:28 +0000817 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000818 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000819 }
820
821 // Splice the newly inserted blocks into the function right before the
822 // original preheader.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000823 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattner18f16092004-04-19 18:07:02 +0000824 NewBlocks[0], F->end());
825
826 // Now we create the new Loop object for the versioned loop.
Devang Patele9916a32010-06-24 00:33:28 +0000827 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000828
829 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
830 // Probably clone more loop-unswitch related loop properties.
831 BranchesInfo.cloneData(NewLoop, L, VMap);
832
Chris Lattnere8255932006-02-10 23:26:14 +0000833 Loop *ParentLoop = L->getParentLoop();
834 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000835 // Make sure to add the cloned preheader and exit blocks to the parent loop
836 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000837 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000838 }
Bill Wendlingd5520982011-09-27 00:59:31 +0000839
Chris Lattnere8255932006-02-10 23:26:14 +0000840 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000841 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000842 // The new exit block should be in the same loop as the old one.
843 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000844 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Andrew Trick64c07482012-04-10 05:14:37 +0000845
Chris Lattnere8255932006-02-10 23:26:14 +0000846 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
847 "Exit block should have been split to have one successor!");
848 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Patel77a01132008-07-03 17:37:52 +0000849
Chris Lattnere8255932006-02-10 23:26:14 +0000850 // If the successor of the exit block had PHI nodes, add an entry for
851 // NewExit.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000852 for (BasicBlock::iterator I = ExitSucc->begin();
853 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnere8255932006-02-10 23:26:14 +0000854 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000855 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patele9916a32010-06-24 00:33:28 +0000856 if (It != VMap.end()) V = It->second;
Chris Lattnere8255932006-02-10 23:26:14 +0000857 PN->addIncoming(V, NewExit);
858 }
Bill Wendlingd5520982011-09-27 00:59:31 +0000859
860 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000861 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
862 ExitSucc->getFirstInsertionPt());
Bill Wendlingd5520982011-09-27 00:59:31 +0000863
864 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
865 I != E; ++I) {
866 BasicBlock *BB = *I;
867 LandingPadInst *LPI = BB->getLandingPadInst();
868 LPI->replaceAllUsesWith(PN);
869 PN->addIncoming(LPI, BB);
870 }
871 }
Chris Lattner18f16092004-04-19 18:07:02 +0000872 }
873
874 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000875 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
876 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
877 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000878 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick64c07482012-04-10 05:14:37 +0000879
Chris Lattner18f16092004-04-19 18:07:02 +0000880 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000881 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000882 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000883 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000884
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000885 // Emit the new branch that selects between the two versions of this loop.
886 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000887 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000888 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000889
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000890 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000891 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000892
Chris Lattnera78130c2010-04-20 05:09:16 +0000893 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
894 // deletes the instruction (for example by simplifying a PHI that feeds into
895 // the condition that we're unswitching on), we don't rewrite the second
896 // iteration.
897 WeakVH LICHandle(LIC);
Andrew Trick64c07482012-04-10 05:14:37 +0000898
Chris Lattner18f16092004-04-19 18:07:02 +0000899 // Now we rewrite the original code to know that the condition is true and the
900 // new code to know that the condition is false.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000901 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Patel77a01132008-07-03 17:37:52 +0000902
Chris Lattnera78130c2010-04-20 05:09:16 +0000903 // It's possible that simplifying one loop could cause the other to be
904 // changed to another value or a constant. If its a constant, don't simplify
905 // it.
906 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
907 LICHandle && !isa<Constant>(LICHandle))
908 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000909}
910
Chris Lattner52221f72006-02-17 00:31:07 +0000911/// RemoveFromWorklist - Remove all instances of I from the worklist vector
912/// specified.
Andrew Trick64c07482012-04-10 05:14:37 +0000913static void RemoveFromWorklist(Instruction *I,
Chris Lattner52221f72006-02-17 00:31:07 +0000914 std::vector<Instruction*> &Worklist) {
Jakub Staszakbe6f8842012-10-16 19:52:32 +0000915
916 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
917 Worklist.end());
Chris Lattner52221f72006-02-17 00:31:07 +0000918}
919
920/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
921/// program, replacing all uses with V and update the worklist.
Andrew Trick64c07482012-04-10 05:14:37 +0000922static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000923 std::vector<Instruction*> &Worklist,
924 Loop *L, LPPassManager *LPM) {
David Greened4c56fb2010-01-05 01:27:04 +0000925 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner52221f72006-02-17 00:31:07 +0000926
927 // Add uses to the worklist, which may be dead now.
928 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
929 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
930 Worklist.push_back(Use);
931
932 // Add users to the worklist which may be simplified now.
Stephen Hines36b56882014-04-23 16:57:46 -0700933 for (User *U : I->users())
934 Worklist.push_back(cast<Instruction>(U));
Devang Patel15c260a2007-07-31 08:03:26 +0000935 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000936 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000937 I->replaceAllUsesWith(V);
938 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000939 ++NumSimplify;
940}
941
Chris Lattnerc2358092006-02-11 00:43:37 +0000942// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
943// the value specified by Val in the specified loop, or we know it does NOT have
944// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +0000945void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +0000946 Constant *Val,
947 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000948 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick64c07482012-04-10 05:14:37 +0000949
Chris Lattner18f16092004-04-19 18:07:02 +0000950 // FIXME: Support correlated properties, like:
951 // for (...)
952 // if (li1 < li2)
953 // ...
954 // if (li1 > li2)
955 // ...
Andrew Trick64c07482012-04-10 05:14:37 +0000956
Chris Lattner708e1a52006-02-10 02:30:37 +0000957 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
958 // selects, switches.
Chris Lattner52221f72006-02-17 00:31:07 +0000959 std::vector<Instruction*> Worklist;
Owen Andersone922c022009-07-22 00:24:57 +0000960 LLVMContext &Context = Val->getContext();
961
Chris Lattner52221f72006-02-17 00:31:07 +0000962 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
963 // in the loop with the appropriate one directly.
Owen Anderson1d0be152009-08-13 21:58:54 +0000964 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000965 Val->getType()->isIntegerTy(1))) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000966 Value *Replacement;
967 if (IsEqual)
968 Replacement = Val;
969 else
Andrew Trick64c07482012-04-10 05:14:37 +0000970 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencer579dca12007-01-12 04:24:46 +0000971 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick64c07482012-04-10 05:14:37 +0000972
Stephen Hines36b56882014-04-23 16:57:46 -0700973 for (User *U : LIC->users()) {
974 Instruction *UI = dyn_cast<Instruction>(U);
975 if (!UI || !L->contains(UI))
Evan Cheng424641e2011-05-24 23:12:57 +0000976 continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700977 Worklist.push_back(UI);
Evan Cheng424641e2011-05-24 23:12:57 +0000978 }
Andrew Trick64c07482012-04-10 05:14:37 +0000979
Jakub Staszak7198ee62013-08-06 17:03:42 +0000980 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
981 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick64c07482012-04-10 05:14:37 +0000982 (*UI)->replaceUsesOfWith(LIC, Replacement);
983
Chris Lattner9e185802010-04-05 21:18:32 +0000984 SimplifyCode(Worklist, L);
985 return;
986 }
Andrew Trick64c07482012-04-10 05:14:37 +0000987
Chris Lattner9e185802010-04-05 21:18:32 +0000988 // Otherwise, we don't know the precise value of LIC, but we do know that it
989 // is certainly NOT "Val". As such, simplify any uses in the loop that we
990 // can. This case occurs when we unswitch switch statements.
Stephen Hines36b56882014-04-23 16:57:46 -0700991 for (User *U : LIC->users()) {
992 Instruction *UI = dyn_cast<Instruction>(U);
993 if (!UI || !L->contains(UI))
Chris Lattner9e185802010-04-05 21:18:32 +0000994 continue;
Chris Lattner52221f72006-02-17 00:31:07 +0000995
Stephen Hines36b56882014-04-23 16:57:46 -0700996 Worklist.push_back(UI);
Chris Lattner52221f72006-02-17 00:31:07 +0000997
Andrew Trick64c07482012-04-10 05:14:37 +0000998 // TODO: We could do other simplifications, for example, turning
Chris Lattner9e185802010-04-05 21:18:32 +0000999 // 'icmp eq LIC, Val' -> false.
1000
1001 // If we know that LIC is not Val, use this info to simplify code.
Stephen Hines36b56882014-04-23 16:57:46 -07001002 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001003 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick64c07482012-04-10 05:14:37 +00001004
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001005 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00001006 // Default case is live for multiple values.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001007 if (DeadCase == SI->case_default()) continue;
Andrew Trick64c07482012-04-10 05:14:37 +00001008
1009 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattner9e185802010-04-05 21:18:32 +00001010 // successor if they become single-entry, those PHI nodes may
1011 // be in the Users list.
Nick Lewycky444f2972011-06-03 06:27:15 +00001012
Evan Cheng424641e2011-05-24 23:12:57 +00001013 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001014 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng424641e2011-05-24 23:12:57 +00001015 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick64c07482012-04-10 05:14:37 +00001016
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +00001017 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick64c07482012-04-10 05:14:37 +00001018
Nick Lewycky444f2972011-06-03 06:27:15 +00001019 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng237d10d2011-05-25 18:17:13 +00001020 // If the DeadCase successor dominates the loop latch, then the
1021 // transformation isn't safe since it will delete the sole predecessor edge
1022 // to the latch.
1023 if (Latch && DT->dominates(SISucc, Latch))
1024 continue;
Evan Cheng424641e2011-05-24 23:12:57 +00001025
Chris Lattner9e185802010-04-05 21:18:32 +00001026 // FIXME: This is a hack. We need to keep the successor around
1027 // and hooked up so as to preserve the loop structure, because
1028 // trying to update it is complicated. So instead we preserve the
1029 // loop structure and put the block on a dead code path.
Evan Cheng424641e2011-05-24 23:12:57 +00001030 SplitEdge(Switch, SISucc, this);
Chris Lattner9e185802010-04-05 21:18:32 +00001031 // Compute the successors instead of relying on the return value
1032 // of SplitEdge, since it may have split the switch successor
1033 // after PHI nodes.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001034 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattner9e185802010-04-05 21:18:32 +00001035 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1036 // Create an "unreachable" destination.
1037 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1038 Switch->getParent(),
1039 OldSISucc);
1040 new UnreachableInst(Context, Abort);
1041 // Force the new case destination to branch to the "unreachable"
1042 // block while maintaining a (dead) CFG edge to the old block.
1043 NewSISucc->getTerminator()->eraseFromParent();
1044 BranchInst::Create(Abort, OldSISucc,
1045 ConstantInt::getTrue(Context), NewSISucc);
1046 // Release the PHI operands for this edge.
1047 for (BasicBlock::iterator II = NewSISucc->begin();
1048 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1049 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1050 UndefValue::get(PN->getType()));
1051 // Tell the domtree about the new block. We don't fully update the
1052 // domtree here -- instead we force it to do a full recomputation
1053 // after the pass is complete -- but we do need to inform it of
1054 // new blocks.
1055 if (DT)
1056 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner52221f72006-02-17 00:31:07 +00001057 }
Andrew Trick64c07482012-04-10 05:14:37 +00001058
Devang Patel15c260a2007-07-31 08:03:26 +00001059 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001060}
1061
Mike Stumpc02f0d72009-09-09 17:57:16 +00001062/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001063/// loop, walk over it and constant prop, dce, and fold control flow where
1064/// possible. Note that this is effectively a very simple loop-structure-aware
1065/// optimizer. During processing of this loop, L could very well be deleted, so
1066/// it must not be used.
1067///
1068/// FIXME: When the loop optimizer is more mature, separate this out to a new
1069/// pass.
1070///
Devang Patel15c260a2007-07-31 08:03:26 +00001071void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001072 while (!Worklist.empty()) {
1073 Instruction *I = Worklist.back();
1074 Worklist.pop_back();
Duncan Sands0f827632010-11-23 20:24:21 +00001075
Chris Lattner52221f72006-02-17 00:31:07 +00001076 // Simple DCE.
1077 if (isInstructionTriviallyDead(I)) {
David Greened4c56fb2010-01-05 01:27:04 +00001078 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick64c07482012-04-10 05:14:37 +00001079
Chris Lattner52221f72006-02-17 00:31:07 +00001080 // Add uses to the worklist, which may be dead now.
1081 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1082 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1083 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001084 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001085 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001086 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001087 ++NumSimplify;
1088 continue;
1089 }
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00001090
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001091 // See if instruction simplification can hack this up. This is common for
1092 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbournefcaf5fa2012-05-20 01:32:09 +00001093 // 'false'. TODO: update the domtree properly so we can pass it here.
1094 if (Value *V = SimplifyInstruction(I))
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00001095 if (LI->replacementPreservesLCSSAForm(I, V)) {
1096 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1097 continue;
1098 }
1099
Chris Lattner52221f72006-02-17 00:31:07 +00001100 // Special case hacks that appear commonly in unswitched code.
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001101 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner52221f72006-02-17 00:31:07 +00001102 if (BI->isUnconditional()) {
1103 // If BI's parent is the only pred of the successor, fold the two blocks
1104 // together.
1105 BasicBlock *Pred = BI->getParent();
1106 BasicBlock *Succ = BI->getSuccessor(0);
1107 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1108 if (!SinglePred) continue; // Nothing to do.
1109 assert(SinglePred == Pred && "CFG broken");
1110
Andrew Trick64c07482012-04-10 05:14:37 +00001111 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001112 << Succ->getName() << "\n");
Andrew Trick64c07482012-04-10 05:14:37 +00001113
Chris Lattner52221f72006-02-17 00:31:07 +00001114 // Resolve any single entry PHI nodes in Succ.
1115 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001116 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick64c07482012-04-10 05:14:37 +00001117
Jay Foad95c3e482011-06-23 09:09:15 +00001118 // If Succ has any successors with PHI nodes, update them to have
1119 // entries coming from Pred instead of Succ.
1120 Succ->replaceAllUsesWith(Pred);
Andrew Trick64c07482012-04-10 05:14:37 +00001121
Chris Lattner52221f72006-02-17 00:31:07 +00001122 // Move all of the successor contents from Succ to Pred.
1123 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1124 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001125 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001126 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001127 RemoveFromWorklist(BI, Worklist);
Andrew Trick64c07482012-04-10 05:14:37 +00001128
Chris Lattner52221f72006-02-17 00:31:07 +00001129 // Remove Succ from the loop tree.
1130 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001131 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001132 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001133 ++NumSimplify;
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001134 continue;
Chris Lattner9e185802010-04-05 21:18:32 +00001135 }
Andrew Trick64c07482012-04-10 05:14:37 +00001136
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001137 continue;
Chris Lattner52221f72006-02-17 00:31:07 +00001138 }
1139 }
Chris Lattner18f16092004-04-19 18:07:02 +00001140}