blob: c4ebfd5f413d9c90f9b268ddc9efc69272db78f0 [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
29#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/Analysis/CodeMetrics.h"
35#include "llvm/Analysis/Dominators.h"
36#include "llvm/Analysis/InstructionSimplify.h"
37#include "llvm/Analysis/LoopInfo.h"
38#include "llvm/Analysis/LoopPass.h"
39#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carrutha5157e62013-01-21 13:04:33 +000040#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000041#include "llvm/IR/Constants.h"
42#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/Instructions.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000045#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000046#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Cloning.h"
50#include "llvm/Transforms/Utils/Local.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000051#include <algorithm>
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000052#include <map>
Chris Lattner2f4b8982006-02-09 19:14:52 +000053#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000054using namespace llvm;
55
Chris Lattner0e5f4992006-12-19 21:40:18 +000056STATISTIC(NumBranches, "Number of branches unswitched");
57STATISTIC(NumSwitches, "Number of switches unswitched");
58STATISTIC(NumSelects , "Number of selects unswitched");
59STATISTIC(NumTrivial , "Number of unswitches that are trivial");
60STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +000061STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000062
Stepan Dyatkovskiy27bf5602012-01-16 20:48:04 +000063// The specific value of 100 here was chosen based only on intuition and a
Dan Gohmanb24f6c72009-10-13 17:50:43 +000064// few specific examples.
Dan Gohman844731a2008-05-13 00:00:25 +000065static cl::opt<unsigned>
66Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +000067 cl::init(100), cl::Hidden);
Andrew Trick64c07482012-04-10 05:14:37 +000068
Dan Gohman844731a2008-05-13 00:00:25 +000069namespace {
Andrew Trick64c07482012-04-10 05:14:37 +000070
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000071 class LUAnalysisCache {
72
73 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
74 UnswitchedValsMap;
Andrew Trick64c07482012-04-10 05:14:37 +000075
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000076 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick64c07482012-04-10 05:14:37 +000077
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000078 struct LoopProperties {
79 unsigned CanBeUnswitchedCount;
80 unsigned SizeEstimation;
81 UnswitchedValsMap UnswitchedVals;
82 };
Andrew Trick64c07482012-04-10 05:14:37 +000083
84 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000085 // LoopProperties pointer for current loop for better performance.
86 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
87 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick64c07482012-04-10 05:14:37 +000088
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000089 LoopPropsMap LoopsProperties;
Jakub Staszak7198ee62013-08-06 17:03:42 +000090 UnswitchedValsMap *CurLoopInstructions;
91 LoopProperties *CurrentLoopProperties;
Andrew Trick64c07482012-04-10 05:14:37 +000092
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000093 // Max size of code we can produce on remained iterations.
94 unsigned MaxSize;
Andrew Trick64c07482012-04-10 05:14:37 +000095
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000096 public:
Andrew Trick64c07482012-04-10 05:14:37 +000097
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +000098 LUAnalysisCache() :
Jakub Staszak7198ee62013-08-06 17:03:42 +000099 CurLoopInstructions(0), CurrentLoopProperties(0),
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000100 MaxSize(Threshold)
101 {}
Andrew Trick64c07482012-04-10 05:14:37 +0000102
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000103 // Analyze loop. Check its size, calculate is it possible to unswitch
104 // it. Returns true if we can unswitch this loop.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000105 bool countLoop(const Loop *L, const TargetTransformInfo &TTI);
Andrew Trick64c07482012-04-10 05:14:37 +0000106
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000107 // Clean all data related to given loop.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000108 void forgetLoop(const Loop *L);
Andrew Trick64c07482012-04-10 05:14:37 +0000109
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000110 // Mark case value as unswitched.
111 // Since SI instruction can be partly unswitched, in order to avoid
112 // extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000113 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick64c07482012-04-10 05:14:37 +0000114
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000115 // Check was this case value unswitched before or not.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000116 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick64c07482012-04-10 05:14:37 +0000117
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000118 // Clone all loop-unswitch related loop properties.
119 // Redistribute unswitching quotas.
120 // Note, that new loop data is stored inside the VMap.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000121 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
122 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000123 };
Andrew Trick64c07482012-04-10 05:14:37 +0000124
Chris Lattner3e8b6632009-09-02 06:11:42 +0000125 class LoopUnswitch : public LoopPass {
Chris Lattner18f16092004-04-19 18:07:02 +0000126 LoopInfo *LI; // Loop information
Devang Patel1bc89362007-03-07 00:26:10 +0000127 LPPassManager *LPM;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000128
Devang Patel1bc89362007-03-07 00:26:10 +0000129 // LoopProcessWorklist - Used to check if second loop needs processing
130 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000131 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000132
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000133 LUAnalysisCache BranchesInfo;
Andrew Trick64c07482012-04-10 05:14:37 +0000134
Devang Patel743f7e82007-06-06 00:21:03 +0000135 bool OptimizeForSize;
Devang Patel6f62af62007-07-30 23:07:10 +0000136 bool redoLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000137
Devang Patele6962df2008-07-02 01:18:13 +0000138 Loop *currentLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000139 DominatorTree *DT;
Devang Patele6962df2008-07-02 01:18:13 +0000140 BasicBlock *loopHeader;
141 BasicBlock *loopPreheader;
Andrew Trick64c07482012-04-10 05:14:37 +0000142
Devang Patel1e41f6d2008-07-02 01:44:29 +0000143 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick64c07482012-04-10 05:14:37 +0000144 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Patel1e41f6d2008-07-02 01:44:29 +0000145 // loop, in that order.
146 std::vector<BasicBlock*> LoopBlocks;
147 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
148 std::vector<BasicBlock*> NewBlocks;
Devang Patel77a01132008-07-03 17:37:52 +0000149
Chris Lattner18f16092004-04-19 18:07:02 +0000150 public:
Devang Patel19974732007-05-03 01:11:54 +0000151 static char ID; // Pass ID, replacement for typeid
Andrew Trick64c07482012-04-10 05:14:37 +0000152 explicit LoopUnswitch(bool Os = false) :
153 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Jakub Staszak7198ee62013-08-06 17:03:42 +0000154 currentLoop(0), DT(0), loopHeader(0),
155 loopPreheader(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000156 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
157 }
Devang Patel794fd752007-05-01 21:15:47 +0000158
Devang Patel1bc89362007-03-07 00:26:10 +0000159 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele6962df2008-07-02 01:18:13 +0000160 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +0000161
162 /// This transformation requires natural loop information & requires that
Chris Lattnerea109232010-08-29 17:23:19 +0000163 /// loop preheaders be inserted into the CFG.
Chris Lattner18f16092004-04-19 18:07:02 +0000164 ///
165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000167 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000168 AU.addRequired<LoopInfo>();
169 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000170 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000171 AU.addPreservedID(LCSSAID);
Devang Patel4be7d292008-07-03 06:48:21 +0000172 AU.addPreserved<DominatorTree>();
Cameron Zwarich71132af2011-02-11 06:08:28 +0000173 AU.addPreserved<ScalarEvolution>();
Chandler Carrutha5157e62013-01-21 13:04:33 +0000174 AU.addRequired<TargetTransformInfo>();
Chris Lattner18f16092004-04-19 18:07:02 +0000175 }
176
177 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000178
Dan Gohman5c89b522009-09-08 15:45:00 +0000179 virtual void releaseMemory() {
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000180 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman5c89b522009-09-08 15:45:00 +0000181 }
182
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000183 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
184 /// remove it.
185 void RemoveLoopFromWorklist(Loop *L) {
186 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
187 LoopProcessWorklist.end(), L);
188 if (I != LoopProcessWorklist.end())
189 LoopProcessWorklist.erase(I);
190 }
Andrew Trick64c07482012-04-10 05:14:37 +0000191
Devang Patele6962df2008-07-02 01:18:13 +0000192 void initLoopData() {
193 loopHeader = currentLoop->getHeader();
194 loopPreheader = currentLoop->getLoopPreheader();
195 }
Andrew Trick64c07482012-04-10 05:14:37 +0000196
Chris Lattner48a80b02008-04-21 00:25:49 +0000197 /// Split all of the edges from inside the loop to their exit blocks.
198 /// Update the appropriate Phi nodes as we do so.
Craig Toppera0ec3f92013-07-14 04:42:23 +0000199 void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000200
Devang Patele6962df2008-07-02 01:18:13 +0000201 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000202 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000203 BasicBlock *ExitBlock);
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000204 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000205
206 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
207 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000208
209 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick64c07482012-04-10 05:14:37 +0000210 BasicBlock *TrueDest,
Devang Patelcce624a2007-06-28 00:49:00 +0000211 BasicBlock *FalseDest,
212 Instruction *InsertPt);
213
Devang Patel15c260a2007-07-31 08:03:26 +0000214 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000215 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele6962df2008-07-02 01:18:13 +0000216 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
217 BasicBlock **LoopExit = 0);
218
Chris Lattner18f16092004-04-19 18:07:02 +0000219 };
Chris Lattner18f16092004-04-19 18:07:02 +0000220}
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000221
222// Analyze loop. Check its size, calculate is it possible to unswitch
223// it. Returns true if we can unswitch this loop.
Chandler Carrutha5157e62013-01-21 13:04:33 +0000224bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI) {
Andrew Trick64c07482012-04-10 05:14:37 +0000225
Jakub Staszak7198ee62013-08-06 17:03:42 +0000226 LoopPropsMapIt PropsIt;
227 bool Inserted;
228 llvm::tie(PropsIt, Inserted) =
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000229 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick64c07482012-04-10 05:14:37 +0000230
Jakub Staszak7198ee62013-08-06 17:03:42 +0000231 LoopProperties &Props = PropsIt->second;
Andrew Trick64c07482012-04-10 05:14:37 +0000232
Jakub Staszak7198ee62013-08-06 17:03:42 +0000233 if (Inserted) {
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000234 // New loop.
235
236 // Limit the number of instructions to avoid causing significant code
237 // expansion, and the number of basic blocks, to avoid loops with
238 // large numbers of branches which cause loop unswitching to go crazy.
239 // This is a very ad-hoc heuristic.
Andrew Trick64c07482012-04-10 05:14:37 +0000240
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000241 // FIXME: This is overly conservative because it does not take into
242 // consideration code simplification opportunities and code that can
243 // be shared by the resultant unswitched loops.
244 CodeMetrics Metrics;
Jakub Staszak7198ee62013-08-06 17:03:42 +0000245 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000246 I != E; ++I)
Chandler Carrutha5157e62013-01-21 13:04:33 +0000247 Metrics.analyzeBasicBlock(*I, TTI);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000248
249 Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
250 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
251 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy67ae1352012-12-20 16:04:27 +0000252
253 if (Metrics.notDuplicatable) {
254 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak7198ee62013-08-06 17:03:42 +0000255 << L->getHeader()->getName() << ", contents cannot be "
256 << "duplicated!\n");
James Molloy67ae1352012-12-20 16:04:27 +0000257 return false;
258 }
Andrew Trick64c07482012-04-10 05:14:37 +0000259 }
260
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000261 if (!Props.CanBeUnswitchedCount) {
262 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak7198ee62013-08-06 17:03:42 +0000263 << L->getHeader()->getName() << ", cost too high: "
264 << L->getBlocks().size() << "\n");
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000265 return false;
266 }
Andrew Trick64c07482012-04-10 05:14:37 +0000267
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000268 // Be careful. This links are good only before new loop addition.
269 CurrentLoopProperties = &Props;
270 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick64c07482012-04-10 05:14:37 +0000271
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000272 return true;
273}
274
275// Clean all data related to given loop.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000276void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick64c07482012-04-10 05:14:37 +0000277
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000278 LoopPropsMapIt LIt = LoopsProperties.find(L);
279
280 if (LIt != LoopsProperties.end()) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000281 LoopProperties &Props = LIt->second;
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000282 MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
283 LoopsProperties.erase(LIt);
284 }
Andrew Trick64c07482012-04-10 05:14:37 +0000285
Jakub Staszak7198ee62013-08-06 17:03:42 +0000286 CurrentLoopProperties = 0;
287 CurLoopInstructions = 0;
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000288}
289
290// Mark case value as unswitched.
291// Since SI instruction can be partly unswitched, in order to avoid
292// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000293void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000294 (*CurLoopInstructions)[SI].insert(V);
295}
296
297// Check was this case value unswitched before or not.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000298bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick64c07482012-04-10 05:14:37 +0000299 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000300}
301
302// Clone all loop-unswitch related loop properties.
303// Redistribute unswitching quotas.
304// Note, that new loop data is stored inside the VMap.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000305void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
306 const ValueToValueMapTy &VMap) {
Andrew Trick64c07482012-04-10 05:14:37 +0000307
Jakub Staszak7198ee62013-08-06 17:03:42 +0000308 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
309 LoopProperties &OldLoopProps = *CurrentLoopProperties;
310 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick64c07482012-04-10 05:14:37 +0000311
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000312 // Reallocate "can-be-unswitched quota"
313
314 --OldLoopProps.CanBeUnswitchedCount;
315 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
316 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
317 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick64c07482012-04-10 05:14:37 +0000318
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000319 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick64c07482012-04-10 05:14:37 +0000320
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000321 // Clone unswitched values info:
322 // for new loop switches we clone info about values that was
323 // already unswitched and has redundant successors.
324 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000325 const SwitchInst *OldInst = I->first;
326 Value *NewI = VMap.lookup(OldInst);
327 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000328 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick64c07482012-04-10 05:14:37 +0000329
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000330 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
331 }
332}
333
Dan Gohman844731a2008-05-13 00:00:25 +0000334char LoopUnswitch::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000335INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
336 false, false)
Chandler Carrutha5157e62013-01-21 13:04:33 +0000337INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000338INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
339INITIALIZE_PASS_DEPENDENCY(LoopInfo)
340INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000341INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
342 false, false)
Chris Lattner18f16092004-04-19 18:07:02 +0000343
Andrew Trick64c07482012-04-10 05:14:37 +0000344Pass *llvm::createLoopUnswitchPass(bool Os) {
345 return new LoopUnswitch(Os);
Devang Patel743f7e82007-06-06 00:21:03 +0000346}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000347
348/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
349/// invariant in the loop, or has an invariant piece, return the invariant.
350/// Otherwise, return null.
351static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick64c07482012-04-10 05:14:37 +0000352
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000353 // We started analyze new instruction, increment scanned instructions counter.
354 ++TotalInsts;
Andrew Trick64c07482012-04-10 05:14:37 +0000355
Chris Lattner3d606bb2010-02-02 02:26:54 +0000356 // We can never unswitch on vector conditions.
Duncan Sands1df98592010-02-16 11:11:14 +0000357 if (Cond->getType()->isVectorTy())
Chris Lattner3d606bb2010-02-02 02:26:54 +0000358 return 0;
359
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000360 // Constants should be folded, not unswitched on!
Dan Gohmana1fcd772008-10-17 00:56:52 +0000361 if (isa<Constant>(Cond)) return 0;
Devang Patel558f1b82007-06-28 00:44:10 +0000362
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000363 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patel265ca5d2008-11-03 19:38:07 +0000364
Dan Gohman0df6e092009-07-14 01:37:59 +0000365 // Hoist simple values out.
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000366 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman0df6e092009-07-14 01:37:59 +0000367 return Cond;
Dan Gohman0df6e092009-07-14 01:37:59 +0000368
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
370 if (BO->getOpcode() == Instruction::And ||
371 BO->getOpcode() == Instruction::Or) {
372 // If either the left or right side is invariant, we can unswitch on this,
373 // which will cause the branch to go away in one loop and the condition to
374 // simplify in the other one.
375 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
376 return LHS;
377 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
378 return RHS;
379 }
Andrew Trick64c07482012-04-10 05:14:37 +0000380
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000381 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000382}
383
Devang Patel1bc89362007-03-07 00:26:10 +0000384bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000385 LI = &getAnalysis<LoopInfo>();
386 LPM = &LPM_Ref;
Duncan Sands1465d612009-01-28 13:14:17 +0000387 DT = getAnalysisIfAvailable<DominatorTree>();
Devang Patele6962df2008-07-02 01:18:13 +0000388 currentLoop = L;
Devang Pateldeafefa2008-09-04 22:43:59 +0000389 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000390 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000391 do {
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000392 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel6f62af62007-07-30 23:07:10 +0000393 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000394 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000395 } while(redoLoop);
396
Devang Pateldeafefa2008-09-04 22:43:59 +0000397 if (Changed) {
398 // FIXME: Reconstruct dom info, because it is not preserved properly.
399 if (DT)
400 DT->runOnFunction(*F);
Devang Pateldeafefa2008-09-04 22:43:59 +0000401 }
Devang Patel6f62af62007-07-30 23:07:10 +0000402 return Changed;
403}
404
Andrew Trick64c07482012-04-10 05:14:37 +0000405/// processCurrentLoop - Do actual work and unswitch loop if possible
Devang Patele6962df2008-07-02 01:18:13 +0000406/// and profitable.
407bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000408 bool Changed = false;
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000409
410 initLoopData();
Andrew Trick64c07482012-04-10 05:14:37 +0000411
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000412 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
413 if (!loopPreheader)
414 return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000415
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000416 // Loops with indirectbr cannot be cloned.
417 if (!currentLoop->isSafeToClone())
418 return false;
419
420 // Without dedicated exits, splitting the exit edge may fail.
421 if (!currentLoop->hasDedicatedExits())
422 return false;
423
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000424 LLVMContext &Context = loopHeader->getContext();
Andrew Trick64c07482012-04-10 05:14:37 +0000425
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000426 // Probably we reach the quota of branches for this loop. If so
427 // stop unswitching.
Chandler Carrutha5157e62013-01-21 13:04:33 +0000428 if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>()))
Stepan Dyatkovskiy88c5c422012-01-11 08:40:51 +0000429 return false;
Devang Patel6f62af62007-07-30 23:07:10 +0000430
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000431 // Loop over all of the basic blocks in the loop. If we find an interior
432 // block that is branching on a loop-invariant condition, we can unswitch this
433 // loop.
Andrew Trick64c07482012-04-10 05:14:37 +0000434 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattner9e185802010-04-05 21:18:32 +0000435 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000436 TerminatorInst *TI = (*I)->getTerminator();
437 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
438 // If this isn't branching on an invariant condition, we can't unswitch
439 // it.
440 if (BI->isConditional()) {
441 // See if this, or some part of it, is loop invariant. If so, we can
442 // unswitch on it if we desire.
Andrew Trick64c07482012-04-10 05:14:37 +0000443 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele6962df2008-07-02 01:18:13 +0000444 currentLoop, Changed);
Andrew Trick64c07482012-04-10 05:14:37 +0000445 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000446 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000447 ++NumBranches;
448 return true;
449 }
Andrew Trick64c07482012-04-10 05:14:37 +0000450 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000451 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick64c07482012-04-10 05:14:37 +0000452 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele6962df2008-07-02 01:18:13 +0000453 currentLoop, Changed);
Andrew Trick64c07482012-04-10 05:14:37 +0000454 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +0000455 if (LoopCond && NumCases) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000456 // Find a value to unswitch on:
457 // FIXME: this should chose the most expensive case!
Nick Lewycky444f2972011-06-03 06:27:15 +0000458 // FIXME: scan for a case with a non-critical edge?
Jakub Staszak7198ee62013-08-06 17:03:42 +0000459 Constant *UnswitchVal = 0;
Andrew Trick64c07482012-04-10 05:14:37 +0000460
Devang Patel52956922007-02-26 19:31:58 +0000461 // Do not process same value again and again.
Chad Rosiera816bf72011-12-22 21:10:46 +0000462 // At this point we have some cases already unswitched and
463 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +0000464 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000465 i != e; ++i) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000466 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000467 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosiera816bf72011-12-22 21:10:46 +0000468 UnswitchVal = UnswitchValCandidate;
469 break;
470 }
471 }
Andrew Trick64c07482012-04-10 05:14:37 +0000472
Chad Rosiera816bf72011-12-22 21:10:46 +0000473 if (!UnswitchVal)
Devang Patel52956922007-02-26 19:31:58 +0000474 continue;
Devang Patel52956922007-02-26 19:31:58 +0000475
Devang Patele6962df2008-07-02 01:18:13 +0000476 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000477 ++NumSwitches;
478 return true;
479 }
480 }
481 }
Andrew Trick64c07482012-04-10 05:14:37 +0000482
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000483 // Scan the instructions to check for unswitchable values.
Andrew Trick64c07482012-04-10 05:14:37 +0000484 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000485 BBI != E; ++BBI)
486 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick64c07482012-04-10 05:14:37 +0000487 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele6962df2008-07-02 01:18:13 +0000488 currentLoop, Changed);
Andrew Trick64c07482012-04-10 05:14:37 +0000489 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000490 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000491 ++NumSelects;
492 return true;
493 }
494 }
495 }
Chris Lattner18f16092004-04-19 18:07:02 +0000496 return Changed;
497}
498
Dan Gohmanb0a57212010-09-01 21:46:45 +0000499/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
500/// loop with no side effects (including infinite loops).
Chris Lattner4e132392006-02-15 22:03:36 +0000501///
Dan Gohmanb0a57212010-09-01 21:46:45 +0000502/// If true, we return true and set ExitBB to the block we
Chris Lattner4e132392006-02-15 22:03:36 +0000503/// exit through.
504///
505static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
506 BasicBlock *&ExitBB,
507 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000508 if (!Visited.insert(BB).second) {
Nick Lewycky8a5641d2011-12-23 23:49:25 +0000509 // Already visited. Without more analysis, this could indicate an infinite
510 // loop.
Dan Gohmanb0a57212010-09-01 21:46:45 +0000511 return false;
Jakub Staszak7198ee62013-08-06 17:03:42 +0000512 }
513 if (!L->contains(BB)) {
Chris Lattner0017d482006-02-17 06:39:56 +0000514 // Otherwise, this is a loop exit, this is fine so long as this is the
515 // first exit.
516 if (ExitBB != 0) return false;
517 ExitBB = BB;
Edward O'Callaghan25798432009-11-25 05:38:41 +0000518 return true;
Chris Lattner0017d482006-02-17 06:39:56 +0000519 }
Andrew Trick64c07482012-04-10 05:14:37 +0000520
Chris Lattner0017d482006-02-17 06:39:56 +0000521 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000522 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000523 // Check to see if the successor is a trivial loop exit.
524 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
525 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000526 }
Chris Lattner4e132392006-02-15 22:03:36 +0000527
528 // Okay, everything after this looks good, check to make sure that this block
529 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000530 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000531 if (I->mayHaveSideEffects())
Chris Lattner4e132392006-02-15 22:03:36 +0000532 return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000533
Chris Lattner4e132392006-02-15 22:03:36 +0000534 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000535}
536
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000537/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
Andrew Trick64c07482012-04-10 05:14:37 +0000538/// leads to an exit from the specified loop, and has no side-effects in the
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000539/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000540static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
541 std::set<BasicBlock*> Visited;
Dan Gohmanb0a57212010-09-01 21:46:45 +0000542 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Chris Lattner4e132392006-02-15 22:03:36 +0000543 BasicBlock *ExitBB = 0;
544 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
545 return ExitBB;
546 return 0;
547}
Chris Lattner708e1a52006-02-10 02:30:37 +0000548
Chris Lattner4c41d492006-02-10 01:24:09 +0000549/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
550/// trivial: that is, that the condition controls whether or not the loop does
551/// anything at all. If this is a trivial condition, unswitching produces no
552/// code duplications (equivalently, it produces a simpler loop and a new empty
553/// loop, which gets deleted).
554///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000555/// If this is a trivial condition, return true, otherwise return false. When
556/// returning true, this sets Cond and Val to the condition that controls the
557/// trivial condition: when Cond dynamically equals Val, the loop is known to
558/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
559/// Cond == Val.
560///
Devang Patele6962df2008-07-02 01:18:13 +0000561bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
562 BasicBlock **LoopExit) {
563 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000564 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Andersone922c022009-07-22 00:24:57 +0000565 LLVMContext &Context = Header->getContext();
Andrew Trick64c07482012-04-10 05:14:37 +0000566
Chris Lattnera48654e2006-02-15 22:52:05 +0000567 BasicBlock *LoopExitBB = 0;
568 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
569 // If the header block doesn't end with a conditional branch on Cond, we
570 // can't handle it.
571 if (!BI->isConditional() || BI->getCondition() != Cond)
572 return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000573
574 // Check to see if a successor of the branch is guaranteed to
575 // exit through a unique exit block without having any
Chris Lattnera48654e2006-02-15 22:52:05 +0000576 // side-effects. If so, determine the value of Cond that causes it to do
577 // this.
Andrew Trick64c07482012-04-10 05:14:37 +0000578 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele6962df2008-07-02 01:18:13 +0000579 BI->getSuccessor(0)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000580 if (Val) *Val = ConstantInt::getTrue(Context);
Andrew Trick64c07482012-04-10 05:14:37 +0000581 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
Devang Patele6962df2008-07-02 01:18:13 +0000582 BI->getSuccessor(1)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000583 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnera48654e2006-02-15 22:52:05 +0000584 }
585 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
586 // If this isn't a switch on Cond, we can't handle it.
587 if (SI->getCondition() != Cond) return false;
Andrew Trick64c07482012-04-10 05:14:37 +0000588
Chris Lattnera48654e2006-02-15 22:52:05 +0000589 // Check to see if a successor of the switch is guaranteed to go to the
Andrew Trick64c07482012-04-10 05:14:37 +0000590 // latch block or exit through a one exit block without having any
Chris Lattnera48654e2006-02-15 22:52:05 +0000591 // side-effects. If so, determine the value of Cond that causes it to do
Andrew Trick64c07482012-04-10 05:14:37 +0000592 // this.
Chad Rosiera816bf72011-12-22 21:10:46 +0000593 // Note that we can't trivially unswitch on the default case or
594 // on already unswitched cases.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +0000595 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000596 i != e; ++i) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000597 BasicBlock *LoopExitCandidate;
Andrew Trick64c07482012-04-10 05:14:37 +0000598 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +0000599 i.getCaseSuccessor()))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000600 // Okay, we found a trivial case, remember the value that is trivial.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000601 ConstantInt *CaseVal = i.getCaseValue();
Chad Rosiera816bf72011-12-22 21:10:46 +0000602
603 // Check that it was not unswitched before, since already unswitched
604 // trivial vals are looks trivial too.
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000605 if (BranchesInfo.isUnswitched(SI, CaseVal))
Chad Rosiera816bf72011-12-22 21:10:46 +0000606 continue;
607 LoopExitBB = LoopExitCandidate;
608 if (Val) *Val = CaseVal;
Chris Lattnera48654e2006-02-15 22:52:05 +0000609 break;
610 }
Chad Rosiera816bf72011-12-22 21:10:46 +0000611 }
Chris Lattner4e132392006-02-15 22:03:36 +0000612 }
613
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000614 // If we didn't find a single unique LoopExit block, or if the loop exit block
615 // contains phi nodes, this isn't trivial.
616 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000617 return false; // Can't handle this.
Andrew Trick64c07482012-04-10 05:14:37 +0000618
Chris Lattnera48654e2006-02-15 22:52:05 +0000619 if (LoopExit) *LoopExit = LoopExitBB;
Andrew Trick64c07482012-04-10 05:14:37 +0000620
Chris Lattner4c41d492006-02-10 01:24:09 +0000621 // We already know that nothing uses any scalar values defined inside of this
622 // loop. As such, we just have to check to see if this loop will execute any
623 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000624 // part of the loop that the code *would* execute. We already checked the
625 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000626 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000627 if (I->mayHaveSideEffects())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000628 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000629 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000630}
631
Devang Patele6962df2008-07-02 01:18:13 +0000632/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000633/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
634/// unswitch the loop, reprocess the pieces, then return true.
Chris Lattner3d606bb2010-02-02 02:26:54 +0000635bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
Dan Gohmanf68d0c12009-12-09 22:55:01 +0000636 Function *F = loopHeader->getParent();
Evan Cheng02720242010-04-03 02:23:43 +0000637 Constant *CondVal = 0;
638 BasicBlock *ExitBlock = 0;
Bill Wendling6aa33272012-04-30 09:23:48 +0000639
Devang Patele6962df2008-07-02 01:18:13 +0000640 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Cheng02720242010-04-03 02:23:43 +0000641 // If the condition is trivial, always unswitch. There is no code growth
642 // for this case.
Devang Patele6962df2008-07-02 01:18:13 +0000643 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Evan Cheng02720242010-04-03 02:23:43 +0000644 return true;
Chris Lattnerc2358092006-02-11 00:43:37 +0000645 }
Devang Patel4be7d292008-07-03 06:48:21 +0000646
Evan Cheng02720242010-04-03 02:23:43 +0000647 // Check to see if it would be profitable to unswitch current loop.
648
649 // Do not do non-trivial unswitch while optimizing for size.
Bill Wendling67658342012-10-09 07:45:08 +0000650 if (OptimizeForSize ||
Bill Wendling831737d2012-12-30 10:32:01 +0000651 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
652 Attribute::OptimizeForSize))
Evan Cheng02720242010-04-03 02:23:43 +0000653 return false;
654
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000655 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
656 return true;
Chris Lattnerc2358092006-02-11 00:43:37 +0000657}
658
Chris Lattner18f16092004-04-19 18:07:02 +0000659/// CloneLoop - Recursively clone the specified loop and all of its children,
660/// mapping the blocks with the specified map.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000661static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000662 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000663 Loop *New = new Loop();
Devang Patel1bc89362007-03-07 00:26:10 +0000664 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000665
666 // Add all of the blocks in L to the new loop.
667 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
668 I != E; ++I)
669 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000670 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000671
672 // Add all of the subloops to the new loop.
673 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000674 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000675
Chris Lattner18f16092004-04-19 18:07:02 +0000676 return New;
677}
678
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000679/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
680/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
681/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000682void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
683 BasicBlock *TrueDest,
684 BasicBlock *FalseDest,
685 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000686 // Insert a conditional branch on LIC to the two preheaders. The original
687 // code is the true version and the new code is the false version.
688 Value *BranchVal = LIC;
Owen Anderson1d0be152009-08-13 21:58:54 +0000689 if (!isa<ConstantInt>(Val) ||
690 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramera9390a42011-09-27 20:39:19 +0000691 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Owen Anderson5defacc2009-07-31 17:39:07 +0000692 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000693 // We want to enter the new loop when the condition is true.
694 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000695
696 // Insert the new branch.
Dan Gohman5c89b522009-09-08 15:45:00 +0000697 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
698
699 // If either edge is critical, split it. This helps preserve LoopSimplify
700 // form for enclosing loops.
Bill Wendlingbfbab992012-04-30 10:44:54 +0000701 SplitCriticalEdge(BI, 0, this, false, false, true);
702 SplitCriticalEdge(BI, 1, this, false, false, true);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000703}
704
Chris Lattner4c41d492006-02-10 01:24:09 +0000705/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
706/// condition in it (a cond branch from its header block to its latch block,
Andrew Trick64c07482012-04-10 05:14:37 +0000707/// where the path through the loop that doesn't execute its body has no
Chris Lattner4c41d492006-02-10 01:24:09 +0000708/// side-effects), unswitch it. This doesn't involve any code duplication, just
709/// moving the conditional branch outside of the loop and updating loop info.
Andrew Trick64c07482012-04-10 05:14:37 +0000710void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
711 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000712 BasicBlock *ExitBlock) {
David Greened4c56fb2010-01-05 01:27:04 +0000713 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000714 << loopHeader->getName() << " [" << L->getBlocks().size()
715 << " blocks] in Function " << L->getHeader()->getParent()->getName()
716 << " on cond: " << *Val << " == " << *Cond << "\n");
Andrew Trick64c07482012-04-10 05:14:37 +0000717
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000718 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000719 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000720 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000721 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000722
723 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000724 // to branch to: this is the exit block out of the loop that we should
725 // short-circuit to.
Andrew Trick64c07482012-04-10 05:14:37 +0000726
Chris Lattner4e132392006-02-15 22:03:36 +0000727 // Split this block now, so that the loop maintains its exit block, and so
728 // that the jump from the preheader can execute the contents of the exit block
729 // without actually branching to it (the exit block should be dominated by the
730 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000731 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000732 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Andrew Trick64c07482012-04-10 05:14:37 +0000733
734 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattner4c41d492006-02-10 01:24:09 +0000735 // insert the new conditional branch.
Andrew Trick64c07482012-04-10 05:14:37 +0000736 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000737 loopPreheader->getTerminator());
Devang Patele6962df2008-07-02 01:18:13 +0000738 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
739 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000740
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000741 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000742 redoLoop = true;
Andrew Trick64c07482012-04-10 05:14:37 +0000743
Chris Lattner4c41d492006-02-10 01:24:09 +0000744 // Now that we know that the loop is never entered when this condition is a
745 // particular value, rewrite the loop with this info. We know that this will
746 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000747 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000748 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000749}
750
Chris Lattner48a80b02008-04-21 00:25:49 +0000751/// SplitExitEdges - Split all of the edges from inside the loop to their exit
752/// blocks. Update the appropriate Phi nodes as we do so.
Andrew Trick64c07482012-04-10 05:14:37 +0000753void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000754 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000755
Chris Lattner4c41d492006-02-10 01:24:09 +0000756 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000757 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman5c89b522009-09-08 15:45:00 +0000758 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
759 pred_end(ExitBlock));
Bill Wendlingd5520982011-09-27 00:59:31 +0000760
Nick Lewycky444f2972011-06-03 06:27:15 +0000761 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
762 // general, if we call it on all predecessors of all exits then it does.
Bill Wendlingd5520982011-09-27 00:59:31 +0000763 if (!ExitBlock->isLandingPad()) {
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000764 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
Bill Wendlingd5520982011-09-27 00:59:31 +0000765 } else {
766 SmallVector<BasicBlock*, 2> NewBBs;
767 SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
768 this, NewBBs);
769 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000770 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000771}
772
Andrew Trick64c07482012-04-10 05:14:37 +0000773/// UnswitchNontrivialCondition - We determined that the loop is profitable
774/// to unswitch when LIC equal Val. Split it into loop versions and test the
Devang Patelc1e26602007-10-03 21:17:43 +0000775/// condition outside of either loop. Return the loops created as Out1/Out2.
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000776void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Devang Patelf476e8e2007-10-03 21:16:08 +0000777 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000778 Function *F = loopHeader->getParent();
David Greened4c56fb2010-01-05 01:27:04 +0000779 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000780 << loopHeader->getName() << " [" << L->getBlocks().size()
781 << " blocks] in Function " << F->getName()
782 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patelf476e8e2007-10-03 21:16:08 +0000783
Cameron Zwarich71132af2011-02-11 06:08:28 +0000784 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
785 SE->forgetLoop(L);
786
Devang Patel1e41f6d2008-07-02 01:44:29 +0000787 LoopBlocks.clear();
788 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000789
790 // First step, split the preheader and exit blocks, and add these blocks to
791 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000792 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000793 LoopBlocks.push_back(NewPreheader);
794
795 // We want the loop to come after the preheader, but before the exit blocks.
796 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
797
798 SmallVector<BasicBlock*, 8> ExitBlocks;
799 L->getUniqueExitBlocks(ExitBlocks);
800
801 // Split all of the edges from inside the loop to their exit blocks. Update
802 // the appropriate Phi nodes as we do so.
Devang Patel77a01132008-07-03 17:37:52 +0000803 SplitExitEdges(L, ExitBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000804
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000805 // The exit blocks may have been changed due to edge splitting, recompute.
806 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000807 L->getUniqueExitBlocks(ExitBlocks);
808
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000809 // Add exit blocks to the loop blocks.
810 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000811
812 // Next step, clone all of the basic blocks that make up the loop (including
813 // the loop preheader and exit blocks), keeping track of the mapping between
814 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000815 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000816 ValueToValueMapTy VMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000817 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000818 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick64c07482012-04-10 05:14:37 +0000819
Evan Cheng0f1666b2010-04-05 21:16:25 +0000820 NewBlocks.push_back(NewBB);
Devang Patele9916a32010-06-24 00:33:28 +0000821 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000822 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000823 }
824
825 // Splice the newly inserted blocks into the function right before the
826 // original preheader.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000827 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattner18f16092004-04-19 18:07:02 +0000828 NewBlocks[0], F->end());
829
830 // Now we create the new Loop object for the versioned loop.
Devang Patele9916a32010-06-24 00:33:28 +0000831 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +0000832
833 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
834 // Probably clone more loop-unswitch related loop properties.
835 BranchesInfo.cloneData(NewLoop, L, VMap);
836
Chris Lattnere8255932006-02-10 23:26:14 +0000837 Loop *ParentLoop = L->getParentLoop();
838 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000839 // Make sure to add the cloned preheader and exit blocks to the parent loop
840 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000841 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000842 }
Bill Wendlingd5520982011-09-27 00:59:31 +0000843
Chris Lattnere8255932006-02-10 23:26:14 +0000844 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000845 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000846 // The new exit block should be in the same loop as the old one.
847 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000848 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Andrew Trick64c07482012-04-10 05:14:37 +0000849
Chris Lattnere8255932006-02-10 23:26:14 +0000850 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
851 "Exit block should have been split to have one successor!");
852 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Patel77a01132008-07-03 17:37:52 +0000853
Chris Lattnere8255932006-02-10 23:26:14 +0000854 // If the successor of the exit block had PHI nodes, add an entry for
855 // NewExit.
Jakub Staszak7198ee62013-08-06 17:03:42 +0000856 for (BasicBlock::iterator I = ExitSucc->begin();
857 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnere8255932006-02-10 23:26:14 +0000858 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000859 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patele9916a32010-06-24 00:33:28 +0000860 if (It != VMap.end()) V = It->second;
Chris Lattnere8255932006-02-10 23:26:14 +0000861 PN->addIncoming(V, NewExit);
862 }
Bill Wendlingd5520982011-09-27 00:59:31 +0000863
864 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak7198ee62013-08-06 17:03:42 +0000865 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
866 ExitSucc->getFirstInsertionPt());
Bill Wendlingd5520982011-09-27 00:59:31 +0000867
868 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
869 I != E; ++I) {
870 BasicBlock *BB = *I;
871 LandingPadInst *LPI = BB->getLandingPadInst();
872 LPI->replaceAllUsesWith(PN);
873 PN->addIncoming(LPI, BB);
874 }
875 }
Chris Lattner18f16092004-04-19 18:07:02 +0000876 }
877
878 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000879 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
880 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
881 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000882 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick64c07482012-04-10 05:14:37 +0000883
Chris Lattner18f16092004-04-19 18:07:02 +0000884 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000885 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000886 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000887 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000888
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000889 // Emit the new branch that selects between the two versions of this loop.
890 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000891 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000892 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000893
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000894 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000895 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000896
Chris Lattnera78130c2010-04-20 05:09:16 +0000897 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
898 // deletes the instruction (for example by simplifying a PHI that feeds into
899 // the condition that we're unswitching on), we don't rewrite the second
900 // iteration.
901 WeakVH LICHandle(LIC);
Andrew Trick64c07482012-04-10 05:14:37 +0000902
Chris Lattner18f16092004-04-19 18:07:02 +0000903 // Now we rewrite the original code to know that the condition is true and the
904 // new code to know that the condition is false.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000905 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Patel77a01132008-07-03 17:37:52 +0000906
Chris Lattnera78130c2010-04-20 05:09:16 +0000907 // It's possible that simplifying one loop could cause the other to be
908 // changed to another value or a constant. If its a constant, don't simplify
909 // it.
910 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
911 LICHandle && !isa<Constant>(LICHandle))
912 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000913}
914
Chris Lattner52221f72006-02-17 00:31:07 +0000915/// RemoveFromWorklist - Remove all instances of I from the worklist vector
916/// specified.
Andrew Trick64c07482012-04-10 05:14:37 +0000917static void RemoveFromWorklist(Instruction *I,
Chris Lattner52221f72006-02-17 00:31:07 +0000918 std::vector<Instruction*> &Worklist) {
Jakub Staszakbe6f8842012-10-16 19:52:32 +0000919
920 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
921 Worklist.end());
Chris Lattner52221f72006-02-17 00:31:07 +0000922}
923
924/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
925/// program, replacing all uses with V and update the worklist.
Andrew Trick64c07482012-04-10 05:14:37 +0000926static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000927 std::vector<Instruction*> &Worklist,
928 Loop *L, LPPassManager *LPM) {
David Greened4c56fb2010-01-05 01:27:04 +0000929 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner52221f72006-02-17 00:31:07 +0000930
931 // Add uses to the worklist, which may be dead now.
932 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
933 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
934 Worklist.push_back(Use);
935
936 // Add users to the worklist which may be simplified now.
937 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
938 UI != E; ++UI)
939 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +0000940 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000941 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000942 I->replaceAllUsesWith(V);
943 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000944 ++NumSimplify;
945}
946
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000947/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
948/// become unwrapped, either because the backedge was deleted, or because the
949/// edge into the header was removed. If the edge into the header from the
950/// latch block was removed, the loop is unwrapped but subloops are still alive,
951/// so they just reparent loops. If the loops are actually dead, they will be
952/// removed later.
953void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +0000954 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000955 RemoveLoopFromWorklist(L);
956}
957
Chris Lattnerc2358092006-02-11 00:43:37 +0000958// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
959// the value specified by Val in the specified loop, or we know it does NOT have
960// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +0000961void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +0000962 Constant *Val,
963 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000964 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick64c07482012-04-10 05:14:37 +0000965
Chris Lattner18f16092004-04-19 18:07:02 +0000966 // FIXME: Support correlated properties, like:
967 // for (...)
968 // if (li1 < li2)
969 // ...
970 // if (li1 > li2)
971 // ...
Andrew Trick64c07482012-04-10 05:14:37 +0000972
Chris Lattner708e1a52006-02-10 02:30:37 +0000973 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
974 // selects, switches.
Chris Lattner52221f72006-02-17 00:31:07 +0000975 std::vector<Instruction*> Worklist;
Owen Andersone922c022009-07-22 00:24:57 +0000976 LLVMContext &Context = Val->getContext();
977
Chris Lattner52221f72006-02-17 00:31:07 +0000978 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
979 // in the loop with the appropriate one directly.
Owen Anderson1d0be152009-08-13 21:58:54 +0000980 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000981 Val->getType()->isIntegerTy(1))) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000982 Value *Replacement;
983 if (IsEqual)
984 Replacement = Val;
985 else
Andrew Trick64c07482012-04-10 05:14:37 +0000986 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencer579dca12007-01-12 04:24:46 +0000987 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick64c07482012-04-10 05:14:37 +0000988
Evan Cheng424641e2011-05-24 23:12:57 +0000989 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
990 UI != E; ++UI) {
Evan Cheng21d378d2011-05-24 23:47:50 +0000991 Instruction *U = dyn_cast<Instruction>(*UI);
992 if (!U || !L->contains(U))
Evan Cheng424641e2011-05-24 23:12:57 +0000993 continue;
Evan Cheng424641e2011-05-24 23:12:57 +0000994 Worklist.push_back(U);
995 }
Andrew Trick64c07482012-04-10 05:14:37 +0000996
Jakub Staszak7198ee62013-08-06 17:03:42 +0000997 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
998 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick64c07482012-04-10 05:14:37 +0000999 (*UI)->replaceUsesOfWith(LIC, Replacement);
1000
Chris Lattner9e185802010-04-05 21:18:32 +00001001 SimplifyCode(Worklist, L);
1002 return;
1003 }
Andrew Trick64c07482012-04-10 05:14:37 +00001004
Chris Lattner9e185802010-04-05 21:18:32 +00001005 // Otherwise, we don't know the precise value of LIC, but we do know that it
1006 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1007 // can. This case occurs when we unswitch switch statements.
Evan Cheng424641e2011-05-24 23:12:57 +00001008 for (Value::use_iterator UI = LIC->use_begin(), E = LIC->use_end();
1009 UI != E; ++UI) {
Evan Cheng21d378d2011-05-24 23:47:50 +00001010 Instruction *U = dyn_cast<Instruction>(*UI);
1011 if (!U || !L->contains(U))
Chris Lattner9e185802010-04-05 21:18:32 +00001012 continue;
Chris Lattner52221f72006-02-17 00:31:07 +00001013
Chris Lattner9e185802010-04-05 21:18:32 +00001014 Worklist.push_back(U);
Chris Lattner52221f72006-02-17 00:31:07 +00001015
Andrew Trick64c07482012-04-10 05:14:37 +00001016 // TODO: We could do other simplifications, for example, turning
Chris Lattner9e185802010-04-05 21:18:32 +00001017 // 'icmp eq LIC, Val' -> false.
1018
1019 // If we know that LIC is not Val, use this info to simplify code.
1020 SwitchInst *SI = dyn_cast<SwitchInst>(U);
1021 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
Andrew Trick64c07482012-04-10 05:14:37 +00001022
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001023 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00001024 // Default case is live for multiple values.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001025 if (DeadCase == SI->case_default()) continue;
Andrew Trick64c07482012-04-10 05:14:37 +00001026
1027 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattner9e185802010-04-05 21:18:32 +00001028 // successor if they become single-entry, those PHI nodes may
1029 // be in the Users list.
Nick Lewycky444f2972011-06-03 06:27:15 +00001030
Evan Cheng424641e2011-05-24 23:12:57 +00001031 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001032 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng424641e2011-05-24 23:12:57 +00001033 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick64c07482012-04-10 05:14:37 +00001034
Stepan Dyatkovskiy209287d2012-01-15 09:44:07 +00001035 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick64c07482012-04-10 05:14:37 +00001036
Nick Lewycky444f2972011-06-03 06:27:15 +00001037 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng237d10d2011-05-25 18:17:13 +00001038 // If the DeadCase successor dominates the loop latch, then the
1039 // transformation isn't safe since it will delete the sole predecessor edge
1040 // to the latch.
1041 if (Latch && DT->dominates(SISucc, Latch))
1042 continue;
Evan Cheng424641e2011-05-24 23:12:57 +00001043
Chris Lattner9e185802010-04-05 21:18:32 +00001044 // FIXME: This is a hack. We need to keep the successor around
1045 // and hooked up so as to preserve the loop structure, because
1046 // trying to update it is complicated. So instead we preserve the
1047 // loop structure and put the block on a dead code path.
Evan Cheng424641e2011-05-24 23:12:57 +00001048 SplitEdge(Switch, SISucc, this);
Chris Lattner9e185802010-04-05 21:18:32 +00001049 // Compute the successors instead of relying on the return value
1050 // of SplitEdge, since it may have split the switch successor
1051 // after PHI nodes.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001052 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattner9e185802010-04-05 21:18:32 +00001053 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1054 // Create an "unreachable" destination.
1055 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1056 Switch->getParent(),
1057 OldSISucc);
1058 new UnreachableInst(Context, Abort);
1059 // Force the new case destination to branch to the "unreachable"
1060 // block while maintaining a (dead) CFG edge to the old block.
1061 NewSISucc->getTerminator()->eraseFromParent();
1062 BranchInst::Create(Abort, OldSISucc,
1063 ConstantInt::getTrue(Context), NewSISucc);
1064 // Release the PHI operands for this edge.
1065 for (BasicBlock::iterator II = NewSISucc->begin();
1066 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1067 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1068 UndefValue::get(PN->getType()));
1069 // Tell the domtree about the new block. We don't fully update the
1070 // domtree here -- instead we force it to do a full recomputation
1071 // after the pass is complete -- but we do need to inform it of
1072 // new blocks.
1073 if (DT)
1074 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner52221f72006-02-17 00:31:07 +00001075 }
Andrew Trick64c07482012-04-10 05:14:37 +00001076
Devang Patel15c260a2007-07-31 08:03:26 +00001077 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001078}
1079
Mike Stumpc02f0d72009-09-09 17:57:16 +00001080/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001081/// loop, walk over it and constant prop, dce, and fold control flow where
1082/// possible. Note that this is effectively a very simple loop-structure-aware
1083/// optimizer. During processing of this loop, L could very well be deleted, so
1084/// it must not be used.
1085///
1086/// FIXME: When the loop optimizer is more mature, separate this out to a new
1087/// pass.
1088///
Devang Patel15c260a2007-07-31 08:03:26 +00001089void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001090 while (!Worklist.empty()) {
1091 Instruction *I = Worklist.back();
1092 Worklist.pop_back();
Duncan Sands0f827632010-11-23 20:24:21 +00001093
Chris Lattner52221f72006-02-17 00:31:07 +00001094 // Simple DCE.
1095 if (isInstructionTriviallyDead(I)) {
David Greened4c56fb2010-01-05 01:27:04 +00001096 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick64c07482012-04-10 05:14:37 +00001097
Chris Lattner52221f72006-02-17 00:31:07 +00001098 // Add uses to the worklist, which may be dead now.
1099 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1100 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1101 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001102 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001103 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001104 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001105 ++NumSimplify;
1106 continue;
1107 }
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00001108
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001109 // See if instruction simplification can hack this up. This is common for
1110 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbournefcaf5fa2012-05-20 01:32:09 +00001111 // 'false'. TODO: update the domtree properly so we can pass it here.
1112 if (Value *V = SimplifyInstruction(I))
Duncan Sandsd0c6f3d2010-11-18 19:59:41 +00001113 if (LI->replacementPreservesLCSSAForm(I, V)) {
1114 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1115 continue;
1116 }
1117
Chris Lattner52221f72006-02-17 00:31:07 +00001118 // Special case hacks that appear commonly in unswitched code.
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001119 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner52221f72006-02-17 00:31:07 +00001120 if (BI->isUnconditional()) {
1121 // If BI's parent is the only pred of the successor, fold the two blocks
1122 // together.
1123 BasicBlock *Pred = BI->getParent();
1124 BasicBlock *Succ = BI->getSuccessor(0);
1125 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1126 if (!SinglePred) continue; // Nothing to do.
1127 assert(SinglePred == Pred && "CFG broken");
1128
Andrew Trick64c07482012-04-10 05:14:37 +00001129 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001130 << Succ->getName() << "\n");
Andrew Trick64c07482012-04-10 05:14:37 +00001131
Chris Lattner52221f72006-02-17 00:31:07 +00001132 // Resolve any single entry PHI nodes in Succ.
1133 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001134 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick64c07482012-04-10 05:14:37 +00001135
Jay Foad95c3e482011-06-23 09:09:15 +00001136 // If Succ has any successors with PHI nodes, update them to have
1137 // entries coming from Pred instead of Succ.
1138 Succ->replaceAllUsesWith(Pred);
Andrew Trick64c07482012-04-10 05:14:37 +00001139
Chris Lattner52221f72006-02-17 00:31:07 +00001140 // Move all of the successor contents from Succ to Pred.
1141 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1142 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001143 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001144 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001145 RemoveFromWorklist(BI, Worklist);
Andrew Trick64c07482012-04-10 05:14:37 +00001146
Chris Lattner52221f72006-02-17 00:31:07 +00001147 // Remove Succ from the loop tree.
1148 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001149 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001150 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001151 ++NumSimplify;
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001152 continue;
Chris Lattner9e185802010-04-05 21:18:32 +00001153 }
Andrew Trick64c07482012-04-10 05:14:37 +00001154
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001155 continue;
Chris Lattner52221f72006-02-17 00:31:07 +00001156 }
1157 }
Chris Lattner18f16092004-04-19 18:07:02 +00001158}