blob: 9b058c3416284d52efe4ba0b689063ef72bbb4d4 [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// 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.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// This pass does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
Bill Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
Chris Lattnerac695822008-01-04 06:41:45 +000024#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000025#include "llvm/CodeGen/MachineDominators.h"
Evan Chengd94671a2010-04-07 00:41:17 +000026#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Evan Chengab8be962011-06-29 01:14:12 +000031#include "llvm/MC/MCInstrItineraries.h"
Evan Cheng0e673912010-10-14 01:16:09 +000032#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000033#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000034#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000035#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000036#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000037#include "llvm/ADT/DenseMap.h"
Evan Chengd94671a2010-04-07 00:41:17 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000039#include "llvm/ADT/Statistic.h"
Evan Cheng7007e4c2011-10-12 21:33:49 +000040#include "llvm/Support/CommandLine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000041#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000042#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000043using namespace llvm;
44
Evan Cheng7007e4c2011-10-12 21:33:49 +000045static cl::opt<bool>
46AvoidSpeculation("avoid-speculation",
47 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73b5bb32011-10-26 01:26:57 +000048 cl::init(true), cl::Hidden);
Evan Cheng7007e4c2011-10-12 21:33:49 +000049
Evan Cheng03a9fdf2010-10-16 02:20:26 +000050STATISTIC(NumHoisted,
51 "Number of machine instructions hoisted out of loops");
52STATISTIC(NumLowRP,
53 "Number of instructions hoisted in low reg pressure situation");
54STATISTIC(NumHighLatency,
55 "Number of high latency instructions hoisted");
56STATISTIC(NumCSEed,
57 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000058STATISTIC(NumPostRAHoisted,
59 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000060
Bill Wendling0f940c92007-12-07 21:42:31 +000061namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000062 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000063 bool PreRegAlloc;
64
Bill Wendling9258cd32008-01-02 19:32:43 +000065 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000066 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000067 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000068 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000069 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000070 MachineRegisterInfo *MRI;
71 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000074 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000075 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000076 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000077
Bill Wendling0f940c92007-12-07 21:42:31 +000078 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000079 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000080 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000081 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000082 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000083
Evan Cheng0e673912010-10-14 01:16:09 +000084 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000085 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000086 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000087
88 // Register pressure "limit" per register class. If the pressure
89 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000090 SmallVector<unsigned, 8> RegLimit;
91
Evan Cheng03a9fdf2010-10-16 02:20:26 +000092 // Register pressure on path leading from loop preheader to current BB.
93 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
94
Dale Johannesenc46a5f22010-07-29 17:45:24 +000095 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000096 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000097
Evan Chengfad62872011-10-11 23:48:44 +000098 enum {
99 SpeculateFalse = 0,
100 SpeculateTrue = 1,
101 SpeculateUnknown = 2
102 };
103
Devang Patel2e350472011-10-11 18:09:58 +0000104 // If a MBB does not dominate loop exiting blocks then it may not safe
105 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000106 // Tri-state: 0 - false, 1 - true, 2 - unknown
107 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000108
Bill Wendling0f940c92007-12-07 21:42:31 +0000109 public:
110 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000111 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000112 MachineFunctionPass(ID), PreRegAlloc(true) {
113 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
114 }
Evan Chengd94671a2010-04-07 00:41:17 +0000115
116 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000117 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
118 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
119 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000120
121 virtual bool runOnMachineFunction(MachineFunction &MF);
122
Dan Gohman72241702008-12-18 01:37:56 +0000123 const char *getPassName() const { return "Machine Instruction LICM"; }
124
Bill Wendling0f940c92007-12-07 21:42:31 +0000125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000126 AU.addRequired<MachineLoopInfo>();
127 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000128 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000129 AU.addPreserved<MachineLoopInfo>();
130 AU.addPreserved<MachineDominatorTree>();
131 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000132 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000133
134 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000135 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000136 RegPressure.clear();
137 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000138 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000139 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
140 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
141 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000142 CSEMap.clear();
143 }
144
Bill Wendling0f940c92007-12-07 21:42:31 +0000145 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000146 /// CandidateInfo - Keep track of information about hoisting candidates.
147 struct CandidateInfo {
148 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000149 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000150 int FI;
151 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
152 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000153 };
154
155 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
156 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000157 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000158
159 /// HoistPostRA - When an instruction is found to only use loop invariant
160 /// operands that is safe to hoist, this instruction is called to do the
161 /// dirty work.
162 void HoistPostRA(MachineInstr *MI, unsigned Def);
163
164 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
165 /// gather register def and frame object update information.
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000166 void ProcessMI(MachineInstr *MI,
167 BitVector &PhysRegDefs,
168 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000169 SmallSet<int, 32> &StoredFIs,
170 SmallVector<CandidateInfo, 32> &Candidates);
171
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000172 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
173 /// current loop.
174 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000175
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000176 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000177 /// candidate for LICM. e.g. If the instruction is a call, then it's
178 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000179 bool IsLICMCandidate(MachineInstr &I);
180
Bill Wendling041b3f82007-12-08 23:58:46 +0000181 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000182 /// invariant. I.e., all virtual register operands are defined outside of
183 /// the loop, physical registers aren't accessed (explicitly or implicitly),
184 /// and the instruction is hoistable.
185 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000186 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000187
Evan Chengd67705f2011-04-11 21:09:18 +0000188 /// HasAnyPHIUse - Return true if the specified register is used by any
189 /// phi node.
190 bool HasAnyPHIUse(unsigned Reg) const;
191
Evan Cheng23128422010-10-19 18:58:51 +0000192 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
193 /// and an use in the current loop, return true if the target considered
194 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000195 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
196 unsigned Reg) const;
197
198 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000199
Evan Cheng134982d2010-10-20 22:03:58 +0000200 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
201 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000202 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000203 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
204
205 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
206 /// the current block and update their register pressures to reflect the
207 /// effect of hoisting MI from the current block to the preheader.
208 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000209
Evan Cheng45e94d62009-02-04 09:19:56 +0000210 /// IsProfitableToHoist - Return true if it is potentially profitable to
211 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000212 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000213
Devang Patel2e350472011-10-11 18:09:58 +0000214 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
215 /// If not then a load from this mbb may not be safe to hoist.
216 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
217
Pete Cooperacde91e2011-12-22 02:05:40 +0000218 void EnterScope(MachineBasicBlock *MBB);
219
220 void ExitScope(MachineBasicBlock *MBB);
221
222 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
223 /// dominator tree node if its a leaf or all of its children are done. Walk
224 /// up the dominator tree to destroy ancestors which are now done.
225 void ExitScopeIfDone(MachineDomTreeNode *Node,
226 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
227 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
228
229 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
230 /// blocks dominated by the specified header block, and that are in the
231 /// current loop) in depth first order w.r.t the DominatorTree. This allows
232 /// us to visit definitions before uses, allowing us to hoist a loop body in
233 /// one pass without iteration.
Bill Wendling0f940c92007-12-07 21:42:31 +0000234 ///
Pete Cooperacde91e2011-12-22 02:05:40 +0000235 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
236 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendling0f940c92007-12-07 21:42:31 +0000237
Evan Cheng61560e22011-09-01 01:45:00 +0000238 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
239 /// index, return the ID and cost of its representative register class by
240 /// reference.
241 void getRegisterClassIDAndCost(const MachineInstr *MI,
242 unsigned Reg, unsigned OpIdx,
243 unsigned &RCId, unsigned &RCCost) const;
244
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000245 /// InitRegPressure - Find all virtual register references that are liveout
246 /// of the preheader to initialize the starting "register pressure". Note
247 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000248 void InitRegPressure(MachineBasicBlock *BB);
249
Evan Cheng134982d2010-10-20 22:03:58 +0000250 /// UpdateRegPressure - Update estimate of register pressure after the
251 /// specified instruction.
252 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000253
Dan Gohman5c952302009-10-29 17:47:20 +0000254 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
255 /// the load itself could be hoisted. Return the unfolded and hoistable
256 /// load, or null if the load couldn't be unfolded or if it wouldn't
257 /// be hoistable.
258 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
259
Evan Cheng78e5c112009-11-07 03:52:02 +0000260 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
261 /// duplicate of MI. Return this instruction if it's found.
262 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
263 std::vector<const MachineInstr*> &PrevMIs);
264
Evan Cheng9fb744e2009-11-05 00:51:13 +0000265 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
266 /// the preheader that compute the same value. If it's found, do a RAU on
267 /// with the definition of the existing instruction rather than hoisting
268 /// the instruction to the preheader.
269 bool EliminateCSE(MachineInstr *MI,
270 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
271
Evan Cheng7efba852011-10-12 00:09:14 +0000272 /// MayCSE - Return true if the given instruction will be CSE'd if it's
273 /// hoisted out of the loop.
274 bool MayCSE(MachineInstr *MI);
275
Bill Wendling0f940c92007-12-07 21:42:31 +0000276 /// Hoist - When an instruction is found to only use loop invariant operands
277 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000278 /// It returns true if the instruction is hoisted.
279 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000280
281 /// InitCSEMap - Initialize the CSE map with instructions that are in the
282 /// current loop preheader that may become duplicates of instructions that
283 /// are hoisted out of the loop.
284 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000285
286 /// getCurPreheader - Get the preheader for the current loop, splitting
287 /// a critical edge if needed.
288 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000289 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000290} // end anonymous namespace
291
Dan Gohman844731a2008-05-13 00:00:25 +0000292char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000293INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
294 "Machine Loop Invariant Code Motion", false, false)
295INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
296INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
297INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
298INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000299 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000300
Evan Chengd94671a2010-04-07 00:41:17 +0000301FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
302 return new MachineLICM(PreRegAlloc);
303}
Bill Wendling0f940c92007-12-07 21:42:31 +0000304
Dan Gohman853d3fb2010-06-22 17:25:57 +0000305/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
306/// loop that has a unique predecessor.
307static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000308 // Check whether this loop even has a unique predecessor.
309 if (!CurLoop->getLoopPredecessor())
310 return false;
311 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000312 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000313 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000314 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000315 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000316 return true;
317}
318
Bill Wendling0f940c92007-12-07 21:42:31 +0000319bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000320 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000321 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000322 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000323 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
324 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000325
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000326 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000327 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000328 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000329 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000330 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000331 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000332 MRI = &MF.getRegInfo();
333 InstrItins = TM->getInstrItineraryData();
Bill Wendling0f940c92007-12-07 21:42:31 +0000334
Evan Cheng0e673912010-10-14 01:16:09 +0000335 if (PreRegAlloc) {
336 // Estimate register pressure during pre-regalloc pass.
337 unsigned NumRC = TRI->getNumRegClasses();
338 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000339 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000340 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000341 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
342 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000343 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000344 }
345
Bill Wendling0f940c92007-12-07 21:42:31 +0000346 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000347 MLI = &getAnalysis<MachineLoopInfo>();
348 DT = &getAnalysis<MachineDominatorTree>();
349 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000350
Dan Gohmanaa742602010-07-09 18:49:45 +0000351 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
352 while (!Worklist.empty()) {
353 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000354 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000355
Evan Cheng4038f9c2010-04-08 01:03:47 +0000356 // If this is done before regalloc, only visit outer-most preheader-sporting
357 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000358 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
359 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000360 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000361 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000362
Evan Chengd94671a2010-04-07 00:41:17 +0000363 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000364 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000365 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000366 // CSEMap is initialized for loop header when the first instruction is
367 // being hoisted.
368 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000369 FirstInLoop = true;
Pete Cooperacde91e2011-12-22 02:05:40 +0000370 HoistOutOfLoop(N);
Evan Chengd94671a2010-04-07 00:41:17 +0000371 CSEMap.clear();
372 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000373 }
374
375 return Changed;
376}
377
Evan Cheng4038f9c2010-04-08 01:03:47 +0000378/// InstructionStoresToFI - Return true if instruction stores to the
379/// specified frame.
380static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
381 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
382 oe = MI->memoperands_end(); o != oe; ++o) {
383 if (!(*o)->isStore() || !(*o)->getValue())
384 continue;
385 if (const FixedStackPseudoSourceValue *Value =
386 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
387 if (Value->getFrameIndex() == FI)
388 return true;
389 }
390 }
391 return false;
392}
393
394/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
395/// gather register def and frame object update information.
396void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000397 BitVector &PhysRegDefs,
398 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000399 SmallSet<int, 32> &StoredFIs,
400 SmallVector<CandidateInfo, 32> &Candidates) {
401 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000402 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000403 unsigned Def = 0;
404 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
405 const MachineOperand &MO = MI->getOperand(i);
406 if (MO.isFI()) {
407 // Remember if the instruction stores to the frame index.
408 int FI = MO.getIndex();
409 if (!StoredFIs.count(FI) &&
410 MFI->isSpillSlotObjectIndex(FI) &&
411 InstructionStoresToFI(MI, FI))
412 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000413 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000414 continue;
415 }
416
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000417 // We can't hoist an instruction defining a physreg that is clobbered in
418 // the loop.
419 if (MO.isRegMask()) {
Jakob Stoklund Olesen478a8a02012-02-02 23:52:57 +0000420 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000421 continue;
422 }
423
Evan Cheng4038f9c2010-04-08 01:03:47 +0000424 if (!MO.isReg())
425 continue;
426 unsigned Reg = MO.getReg();
427 if (!Reg)
428 continue;
429 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
430 "Not expecting virtual register!");
431
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000432 if (!MO.isDef()) {
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000433 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000434 // If it's using a non-loop-invariant register, then it's obviously not
435 // safe to hoist.
436 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000437 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000438 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000439
440 if (MO.isImplicit()) {
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000441 for (const unsigned *AS = TRI->getOverlaps(Reg); *AS; ++AS)
442 PhysRegClobbers.set(*AS);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000443 if (!MO.isDead())
444 // Non-dead implicit def? This cannot be hoisted.
445 RuledOut = true;
446 // No need to check if a dead implicit def is also defined by
447 // another instruction.
448 continue;
449 }
450
451 // FIXME: For now, avoid instructions with multiple defs, unless
452 // it's a dead implicit def.
453 if (Def)
454 RuledOut = true;
455 else
456 Def = Reg;
457
458 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000459 // register, then this is not safe. Two defs is indicated by setting a
460 // PhysRegClobbers bit.
461 for (const unsigned *AS = TRI->getOverlaps(Reg); *AS; ++AS) {
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000462 if (PhysRegDefs.test(*AS))
463 PhysRegClobbers.set(*AS);
464 if (PhysRegClobbers.test(*AS))
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000465 // MI defined register is seen defined by another instruction in
466 // the loop, it cannot be a LICM candidate.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000467 RuledOut = true;
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000468 PhysRegDefs.set(*AS);
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000469 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000470 }
471
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000472 // Only consider reloads for now and remats which do not have register
473 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000474 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000475 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000476 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000477 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
478 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000479 }
480}
481
482/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
483/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000484void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000485 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000486 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
487 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Chengd94671a2010-04-07 00:41:17 +0000488
Evan Cheng4038f9c2010-04-08 01:03:47 +0000489 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000490 SmallSet<int, 32> StoredFIs;
491
492 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000493 // collect potential LICM candidates.
494 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
495 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
496 MachineBasicBlock *BB = Blocks[i];
Bill Wendlinga2e87912011-10-12 02:58:01 +0000497
498 // If the header of the loop containing this basic block is a landing pad,
499 // then don't try to hoist instructions out of this loop.
500 const MachineLoop *ML = MLI->getLoopFor(BB);
501 if (ML && ML->getHeader()->isLandingPad()) continue;
502
Evan Chengd94671a2010-04-07 00:41:17 +0000503 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000504 // FIXME: That means a reload that're reused in successor block(s) will not
505 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000506 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000507 E = BB->livein_end(); I != E; ++I) {
508 unsigned Reg = *I;
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000509 for (const unsigned *AS = TRI->getOverlaps(Reg); *AS; ++AS)
510 PhysRegDefs.set(*AS);
Evan Chengd94671a2010-04-07 00:41:17 +0000511 }
512
Evan Chengfad62872011-10-11 23:48:44 +0000513 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000514 for (MachineBasicBlock::iterator
515 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000516 MachineInstr *MI = &*MII;
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000517 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000518 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000519 }
Evan Chengd94671a2010-04-07 00:41:17 +0000520
521 // Now evaluate whether the potential candidates qualify.
522 // 1. Check if the candidate defined register is defined by another
523 // instruction in the loop.
524 // 2. If the candidate is a load from stack slot (always true for now),
525 // check if the slot is stored anywhere in the loop.
526 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000527 if (Candidates[i].FI != INT_MIN &&
528 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000529 continue;
530
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000531 if (!PhysRegClobbers.test(Candidates[i].Def)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000532 bool Safe = true;
533 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000534 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
535 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000536 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000537 continue;
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000538 if (PhysRegDefs.test(MO.getReg()) ||
539 PhysRegClobbers.test(MO.getReg())) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000540 // If it's using a non-loop-invariant register, then it's obviously
541 // not safe to hoist.
542 Safe = false;
543 break;
544 }
545 }
546 if (Safe)
547 HoistPostRA(MI, Candidates[i].Def);
548 }
Evan Chengd94671a2010-04-07 00:41:17 +0000549 }
550}
551
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000552/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
553/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000554void MachineLICM::AddToLiveIns(unsigned Reg) {
555 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000556 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
557 MachineBasicBlock *BB = Blocks[i];
558 if (!BB->isLiveIn(Reg))
559 BB->addLiveIn(Reg);
560 for (MachineBasicBlock::iterator
561 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
562 MachineInstr *MI = &*MII;
563 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
564 MachineOperand &MO = MI->getOperand(i);
565 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
566 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
567 MO.setIsKill(false);
568 }
569 }
570 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000571}
572
573/// HoistPostRA - When an instruction is found to only use loop invariant
574/// operands that is safe to hoist, this instruction is called to do the
575/// dirty work.
576void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000577 MachineBasicBlock *Preheader = getCurPreheader();
578 if (!Preheader) return;
579
Evan Chengd94671a2010-04-07 00:41:17 +0000580 // Now move the instructions to the predecessor, inserting it before any
581 // terminator instructions.
Jakob Stoklund Olesen39f66602012-01-23 21:01:11 +0000582 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
583 << MI->getParent()->getNumber() << ": " << *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000584
585 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000586 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000587 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000588
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000589 // Add register to livein list to all the BBs in the current loop since a
590 // loop invariant must be kept live throughout the whole loop. This is
591 // important to ensure later passes do not scavenge the def register.
592 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000593
594 ++NumPostRAHoisted;
595 Changed = true;
596}
597
Devang Patel2e350472011-10-11 18:09:58 +0000598// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
599// If not then a load from this mbb may not be safe to hoist.
600bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000601 if (SpeculationState != SpeculateUnknown)
602 return SpeculationState == SpeculateFalse;
603
Devang Patel2e350472011-10-11 18:09:58 +0000604 if (BB != CurLoop->getHeader()) {
605 // Check loop exiting blocks.
606 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
607 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
608 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
609 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewyckyea3abd52011-10-13 01:09:50 +0000610 SpeculationState = SpeculateTrue;
611 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000612 }
613 }
614
Evan Chengfad62872011-10-11 23:48:44 +0000615 SpeculationState = SpeculateFalse;
616 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000617}
618
Pete Cooperacde91e2011-12-22 02:05:40 +0000619void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
620 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendling0f940c92007-12-07 21:42:31 +0000621
Pete Cooperacde91e2011-12-22 02:05:40 +0000622 // Remember livein register pressure.
623 BackTrace.push_back(RegPressure);
624}
Bill Wendlinga2e87912011-10-12 02:58:01 +0000625
Pete Cooperacde91e2011-12-22 02:05:40 +0000626void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
627 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
628 BackTrace.pop_back();
629}
Bill Wendling0f940c92007-12-07 21:42:31 +0000630
Pete Cooperacde91e2011-12-22 02:05:40 +0000631/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
632/// dominator tree node if its a leaf or all of its children are done. Walk
633/// up the dominator tree to destroy ancestors which are now done.
634void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Cheng75fda5d2012-01-10 22:27:32 +0000635 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
636 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000637 if (OpenChildren[Node])
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000638 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000639
Pete Cooperacde91e2011-12-22 02:05:40 +0000640 // Pop scope.
641 ExitScope(Node->getBlock());
642
643 // Now traverse upwards to pop ancestors whose offsprings are all done.
644 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
645 unsigned Left = --OpenChildren[Parent];
646 if (Left != 0)
647 break;
648 ExitScope(Parent->getBlock());
649 Node = Parent;
650 }
651}
652
653/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
654/// blocks dominated by the specified header block, and that are in the
655/// current loop) in depth first order w.r.t the DominatorTree. This allows
656/// us to visit definitions before uses, allowing us to hoist a loop body in
657/// one pass without iteration.
658///
659void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
660 SmallVector<MachineDomTreeNode*, 32> Scopes;
661 SmallVector<MachineDomTreeNode*, 8> WorkList;
662 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
663 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
664
665 // Perform a DFS walk to determine the order of visit.
666 WorkList.push_back(HeaderN);
667 do {
668 MachineDomTreeNode *Node = WorkList.pop_back_val();
669 assert(Node != 0 && "Null dominator tree node?");
670 MachineBasicBlock *BB = Node->getBlock();
671
672 // If the header of the loop containing this basic block is a landing pad,
673 // then don't try to hoist instructions out of this loop.
674 const MachineLoop *ML = MLI->getLoopFor(BB);
675 if (ML && ML->getHeader()->isLandingPad())
676 continue;
677
678 // If this subregion is not in the top level loop at all, exit.
679 if (!CurLoop->contains(BB))
680 continue;
681
682 Scopes.push_back(Node);
683 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
684 unsigned NumChildren = Children.size();
685
686 // Don't hoist things out of a large switch statement. This often causes
687 // code to be hoisted that wasn't going to be executed, and increases
688 // register pressure in a situation where it's likely to matter.
689 if (BB->succ_size() >= 25)
690 NumChildren = 0;
691
692 OpenChildren[Node] = NumChildren;
693 // Add children in reverse order as then the next popped worklist node is
694 // the first child of this node. This means we ultimately traverse the
695 // DOM tree in exactly the same order as if we'd recursed.
696 for (int i = (int)NumChildren-1; i >= 0; --i) {
697 MachineDomTreeNode *Child = Children[i];
698 ParentMap[Child] = Node;
699 WorkList.push_back(Child);
700 }
701 } while (!WorkList.empty());
702
703 if (Scopes.size() != 0) {
704 MachineBasicBlock *Preheader = getCurPreheader();
705 if (!Preheader)
706 return;
707
Evan Cheng134982d2010-10-20 22:03:58 +0000708 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000709 RegSeen.clear();
710 BackTrace.clear();
711 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000712 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000713
Pete Cooperacde91e2011-12-22 02:05:40 +0000714 // Now perform LICM.
715 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
716 MachineDomTreeNode *Node = Scopes[i];
717 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng23128422010-10-19 18:58:51 +0000718
Pete Cooperacde91e2011-12-22 02:05:40 +0000719 MachineBasicBlock *Preheader = getCurPreheader();
720 if (!Preheader)
721 continue;
722
723 EnterScope(MBB);
724
725 // Process the block
726 SpeculationState = SpeculateUnknown;
727 for (MachineBasicBlock::iterator
728 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
729 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
730 MachineInstr *MI = &*MII;
731 if (!Hoist(MI, Preheader))
732 UpdateRegPressure(MI);
733 MII = NextMII;
734 }
735
736 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
737 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohmanc475c362009-01-15 22:01:38 +0000738 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000739}
740
Evan Cheng134982d2010-10-20 22:03:58 +0000741static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
742 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
743}
744
Evan Cheng61560e22011-09-01 01:45:00 +0000745/// getRegisterClassIDAndCost - For a given MI, register, and the operand
746/// index, return the ID and cost of its representative register class.
747void
748MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
749 unsigned Reg, unsigned OpIdx,
750 unsigned &RCId, unsigned &RCCost) const {
751 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
752 EVT VT = *RC->vt_begin();
Owen Anderson99aa14f2011-11-16 01:02:57 +0000753 if (VT == MVT::Untyped) {
Evan Cheng61560e22011-09-01 01:45:00 +0000754 RCId = RC->getID();
755 RCCost = 1;
756 } else {
757 RCId = TLI->getRepRegClassFor(VT)->getID();
758 RCCost = TLI->getRepRegClassCostFor(VT);
759 }
760}
761
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000762/// InitRegPressure - Find all virtual register references that are liveout of
763/// the preheader to initialize the starting "register pressure". Note this
764/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000765void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000766 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000767
Evan Cheng134982d2010-10-20 22:03:58 +0000768 // If the preheader has only a single predecessor and it ends with a
769 // fallthrough or an unconditional branch, then scan its predecessor for live
770 // defs as well. This happens whenever the preheader is created by splitting
771 // the critical edge from the loop predecessor to the loop header.
772 if (BB->pred_size() == 1) {
773 MachineBasicBlock *TBB = 0, *FBB = 0;
774 SmallVector<MachineOperand, 4> Cond;
775 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
776 InitRegPressure(*BB->pred_begin());
777 }
778
Evan Cheng0e673912010-10-14 01:16:09 +0000779 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
780 MII != E; ++MII) {
781 MachineInstr *MI = &*MII;
782 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
783 const MachineOperand &MO = MI->getOperand(i);
784 if (!MO.isReg() || MO.isImplicit())
785 continue;
786 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000787 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000788 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000789
Andrew Trickdc986d22010-10-19 02:50:50 +0000790 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000791 unsigned RCId, RCCost;
792 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000793 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000794 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000795 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000796 bool isKill = isOperandKill(MO, MRI);
797 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000798 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000799 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000800 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000801 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000802 }
Evan Cheng0e673912010-10-14 01:16:09 +0000803 }
804 }
805}
806
Evan Cheng134982d2010-10-20 22:03:58 +0000807/// UpdateRegPressure - Update estimate of register pressure after the
808/// specified instruction.
809void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
810 if (MI->isImplicitDef())
811 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000812
Evan Cheng134982d2010-10-20 22:03:58 +0000813 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000814 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
815 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000816 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000817 continue;
818 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000819 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000820 continue;
821
Andrew Trickdc986d22010-10-19 02:50:50 +0000822 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000823 if (MO.isDef())
824 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000825 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000826 unsigned RCId, RCCost;
827 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000828 if (RCCost > RegPressure[RCId])
829 RegPressure[RCId] = 0;
830 else
Evan Cheng23128422010-10-19 18:58:51 +0000831 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000832 }
Evan Cheng0e673912010-10-14 01:16:09 +0000833 }
Evan Cheng0e673912010-10-14 01:16:09 +0000834
Evan Cheng61560e22011-09-01 01:45:00 +0000835 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000836 while (!Defs.empty()) {
837 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000838 unsigned RCId, RCCost;
839 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000840 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000841 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000842 }
843}
844
Devang Patel06e16bb2011-10-20 17:42:23 +0000845/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
846/// loads from global offset table or constant pool.
847static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000848 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel6c15fec2011-10-17 17:35:01 +0000849 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
850 E = MI.memoperands_end(); I != E; ++I) {
851 if (const Value *V = (*I)->getValue()) {
852 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
Devang Patel06e16bb2011-10-20 17:42:23 +0000853 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
Devang Patel6c15fec2011-10-17 17:35:01 +0000854 return true;
855 }
856 }
857 return false;
858}
859
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000860/// IsLICMCandidate - Returns true if the instruction may be a suitable
861/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
862/// not safe to hoist it.
863bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000864 // Check if it's safe to move the instruction.
865 bool DontMoveAcrossStore = true;
866 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000867 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000868
869 // If it is load then check if it is guaranteed to execute by making sure that
870 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patele6de9f32011-10-20 17:31:18 +0000871 // the loop which does not execute this load, so we can't hoist it. Loads
872 // from constant memory are not safe to speculate all the time, for example
873 // indexed load from a jump table.
Devang Patel2e350472011-10-11 18:09:58 +0000874 // Stores and side effects are already checked by isSafeToMove.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000875 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel6c15fec2011-10-17 17:35:01 +0000876 !IsGuaranteedToExecute(I.getParent()))
Devang Patel2e350472011-10-11 18:09:58 +0000877 return false;
878
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000879 return true;
880}
881
882/// IsLoopInvariantInst - Returns true if the instruction is loop
883/// invariant. I.e., all virtual register operands are defined outside of the
884/// loop, physical registers aren't accessed explicitly, and there are no side
885/// effects that aren't captured by the operands or other flags.
886///
887bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
888 if (!IsLICMCandidate(I))
889 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000890
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000891 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000892 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
893 const MachineOperand &MO = I.getOperand(i);
894
Dan Gohmand735b802008-10-03 15:45:36 +0000895 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000896 continue;
897
Dan Gohmanc475c362009-01-15 22:01:38 +0000898 unsigned Reg = MO.getReg();
899 if (Reg == 0) continue;
900
901 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000902 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000903 if (MO.isUse()) {
904 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000905 // and we can freely move its uses. Alternatively, if it's allocatable,
906 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000907 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000908 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000909 // Otherwise it's safe to move.
910 continue;
911 } else if (!MO.isDead()) {
912 // A def that isn't dead. We can't move it.
913 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000914 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
915 // If the reg is live into the loop, we can't hoist an instruction
916 // which would clobber it.
917 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000918 }
919 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000920
921 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000922 continue;
923
Evan Cheng0e673912010-10-14 01:16:09 +0000924 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000925 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000926
927 // If the loop contains the definition of an operand, then the instruction
928 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000929 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000930 return false;
931 }
932
933 // If we got this far, the instruction is loop invariant!
934 return true;
935}
936
Evan Chengaf6949d2009-02-05 08:45:46 +0000937
Evan Chengd67705f2011-04-11 21:09:18 +0000938/// HasAnyPHIUse - Return true if the specified register is used by any
939/// phi node.
940bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000941 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
942 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000943 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000944 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000945 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000946 // Look pass copies as well.
947 if (UseMI->isCopy()) {
948 unsigned Def = UseMI->getOperand(0).getReg();
949 if (TargetRegisterInfo::isVirtualRegister(Def) &&
950 HasAnyPHIUse(Def))
951 return true;
952 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000953 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000954 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000955}
956
Evan Cheng23128422010-10-19 18:58:51 +0000957/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
958/// and an use in the current loop, return true if the target considered
959/// it 'high'.
960bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000961 unsigned DefIdx, unsigned Reg) const {
962 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000963 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000964
Evan Cheng0e673912010-10-14 01:16:09 +0000965 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
966 E = MRI->use_nodbg_end(); I != E; ++I) {
967 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000968 if (UseMI->isCopyLike())
969 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000970 if (!CurLoop->contains(UseMI->getParent()))
971 continue;
972 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
973 const MachineOperand &MO = UseMI->getOperand(i);
974 if (!MO.isReg() || !MO.isUse())
975 continue;
976 unsigned MOReg = MO.getReg();
977 if (MOReg != Reg)
978 continue;
979
Evan Cheng23128422010-10-19 18:58:51 +0000980 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
981 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000982 }
983
Evan Cheng23128422010-10-19 18:58:51 +0000984 // Only look at the first in loop use.
985 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000986 }
987
Evan Cheng23128422010-10-19 18:58:51 +0000988 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000989}
990
Evan Chengc8141df2010-10-26 02:08:50 +0000991/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
992/// the operand latency between its def and a use is one or less.
993bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000994 if (MI.isAsCheapAsAMove() || MI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +0000995 return true;
996 if (!InstrItins || InstrItins->isEmpty())
997 return false;
998
999 bool isCheap = false;
1000 unsigned NumDefs = MI.getDesc().getNumDefs();
1001 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1002 MachineOperand &DefMO = MI.getOperand(i);
1003 if (!DefMO.isReg() || !DefMO.isDef())
1004 continue;
1005 --NumDefs;
1006 unsigned Reg = DefMO.getReg();
1007 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1008 continue;
1009
1010 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1011 return false;
1012 isCheap = true;
1013 }
1014
1015 return isCheap;
1016}
1017
Evan Cheng134982d2010-10-20 22:03:58 +00001018/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001019/// if hoisting an instruction of the given cost matrix can cause high
1020/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +00001021bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
1022 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1023 CI != CE; ++CI) {
1024 if (CI->second <= 0)
1025 continue;
1026
1027 unsigned RCId = CI->first;
Pete Cooper3cfecf52011-12-22 02:13:25 +00001028 unsigned Limit = RegLimit[RCId];
1029 int Cost = CI->second;
Evan Cheng134982d2010-10-20 22:03:58 +00001030 for (unsigned i = BackTrace.size(); i != 0; --i) {
1031 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Pete Cooper3cfecf52011-12-22 02:13:25 +00001032 if (RP[RCId] + Cost >= Limit)
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001033 return true;
1034 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001035 }
1036
1037 return false;
1038}
1039
Evan Cheng134982d2010-10-20 22:03:58 +00001040/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1041/// current block and update their register pressures to reflect the effect
1042/// of hoisting MI from the current block to the preheader.
1043void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1044 if (MI->isImplicitDef())
1045 return;
1046
1047 // First compute the 'cost' of the instruction, i.e. its contribution
1048 // to register pressure.
1049 DenseMap<unsigned, int> Cost;
1050 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1051 const MachineOperand &MO = MI->getOperand(i);
1052 if (!MO.isReg() || MO.isImplicit())
1053 continue;
1054 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001055 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +00001056 continue;
1057
Evan Cheng61560e22011-09-01 01:45:00 +00001058 unsigned RCId, RCCost;
1059 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +00001060 if (MO.isDef()) {
1061 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1062 if (CI != Cost.end())
1063 CI->second += RCCost;
1064 else
1065 Cost.insert(std::make_pair(RCId, RCCost));
1066 } else if (isOperandKill(MO, MRI)) {
1067 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1068 if (CI != Cost.end())
1069 CI->second -= RCCost;
1070 else
1071 Cost.insert(std::make_pair(RCId, -RCCost));
1072 }
1073 }
1074
1075 // Update register pressure of blocks from loop header to current block.
1076 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1077 SmallVector<unsigned, 8> &RP = BackTrace[i];
1078 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1079 CI != CE; ++CI) {
1080 unsigned RCId = CI->first;
1081 RP[RCId] += CI->second;
1082 }
1083 }
1084}
1085
Evan Cheng45e94d62009-02-04 09:19:56 +00001086/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1087/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +00001088bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +00001089 if (MI.isImplicitDef())
1090 return true;
1091
Evan Cheng23128422010-10-19 18:58:51 +00001092 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
1093 // will increase register pressure. It's probably not worth it if the
1094 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +00001095 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
1096 // these tend to help performance in low register pressure situation. The
1097 // trade off is it may cause spill in high pressure situation. It will end up
1098 // adding a store in the loop preheader. But the reload is no more expensive.
1099 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +00001100 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +00001101 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +00001102 return false;
1103 } else {
Evan Cheng23128422010-10-19 18:58:51 +00001104 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +00001105 // In low register pressure situation, we can be more aggressive about
1106 // hoisting. Also, favors hoisting long latency instructions even in
1107 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +00001108 // FIXME: If there are long latency loop-invariant instructions inside the
1109 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001110 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +00001111 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1112 const MachineOperand &MO = MI.getOperand(i);
1113 if (!MO.isReg() || MO.isImplicit())
1114 continue;
1115 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001116 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +00001117 continue;
Evan Cheng61560e22011-09-01 01:45:00 +00001118
1119 unsigned RCId, RCCost;
1120 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001121 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +00001122 if (HasHighOperandLatency(MI, i, Reg)) {
1123 ++NumHighLatency;
1124 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001125 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001126
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001127 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001128 if (CI != Cost.end())
1129 CI->second += RCCost;
1130 else
1131 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +00001132 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001133 // Is a virtual register use is a kill, hoisting it out of the loop
1134 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +00001135 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001136 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1137 if (CI != Cost.end())
1138 CI->second -= RCCost;
1139 else
1140 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +00001141 }
1142 }
1143
Evan Cheng134982d2010-10-20 22:03:58 +00001144 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001145 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +00001146 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001147 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +00001148 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001149 }
Evan Cheng0e673912010-10-14 01:16:09 +00001150
Evan Cheng7007e4c2011-10-12 21:33:49 +00001151 // Do not "speculate" in high register pressure situation. If an
Evan Chengfad62872011-10-11 23:48:44 +00001152 // instruction is not guaranteed to be executed in the loop, it's best to be
1153 // conservative.
Evan Cheng7007e4c2011-10-12 21:33:49 +00001154 if (AvoidSpeculation &&
1155 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)))
1156 return false;
1157
1158 // High register pressure situation, only hoist if the instruction is going to
1159 // be remat'ed.
1160 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1161 !MI.isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001162 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001163 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001164
Evan Chengd67705f2011-04-11 21:09:18 +00001165 // If result(s) of this instruction is used by PHIs outside of the loop, then
1166 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001167 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1168 const MachineOperand &MO = MI.getOperand(i);
1169 if (!MO.isReg() || !MO.isDef())
1170 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001171 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001172 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001173 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001174
1175 return true;
1176}
1177
Dan Gohman5c952302009-10-29 17:47:20 +00001178MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001179 // Don't unfold simple loads.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001180 if (MI->canFoldAsLoad())
Evan Chenge95f3192010-10-08 18:59:19 +00001181 return 0;
1182
Dan Gohman5c952302009-10-29 17:47:20 +00001183 // If not, we may be able to unfold a load and hoist that.
1184 // First test whether the instruction is loading from an amenable
1185 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001186 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001187 return 0;
1188
Dan Gohman5c952302009-10-29 17:47:20 +00001189 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001190 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001191 unsigned NewOpc =
1192 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1193 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001194 /*UnfoldStore=*/false,
1195 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001196 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001197 const MCInstrDesc &MID = TII->get(NewOpc);
1198 if (MID.getNumDefs() != 1) return 0;
1199 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001200 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001201 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001202
1203 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001204 SmallVector<MachineInstr *, 2> NewMIs;
1205 bool Success =
1206 TII->unfoldMemoryOperand(MF, MI, Reg,
1207 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1208 NewMIs);
1209 (void)Success;
1210 assert(Success &&
1211 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1212 "succeeded!");
1213 assert(NewMIs.size() == 2 &&
1214 "Unfolded a load into multiple instructions!");
1215 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001216 MachineBasicBlock::iterator Pos = MI;
1217 MBB->insert(Pos, NewMIs[0]);
1218 MBB->insert(Pos, NewMIs[1]);
Dan Gohman5c952302009-10-29 17:47:20 +00001219 // If unfolding produced a load that wasn't loop-invariant or profitable to
1220 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001221 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001222 NewMIs[0]->eraseFromParent();
1223 NewMIs[1]->eraseFromParent();
1224 return 0;
1225 }
Evan Cheng134982d2010-10-20 22:03:58 +00001226
1227 // Update register pressure for the unfolded instruction.
1228 UpdateRegPressure(NewMIs[1]);
1229
Dan Gohman5c952302009-10-29 17:47:20 +00001230 // Otherwise we successfully unfolded a load that we can hoist.
1231 MI->eraseFromParent();
1232 return NewMIs[0];
1233}
1234
Evan Cheng777c6b72009-11-03 21:40:02 +00001235void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1236 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1237 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001238 unsigned Opcode = MI->getOpcode();
1239 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1240 CI = CSEMap.find(Opcode);
1241 if (CI != CSEMap.end())
1242 CI->second.push_back(MI);
1243 else {
1244 std::vector<const MachineInstr*> CSEMIs;
1245 CSEMIs.push_back(MI);
1246 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001247 }
1248 }
1249}
1250
Evan Cheng78e5c112009-11-07 03:52:02 +00001251const MachineInstr*
1252MachineLICM::LookForDuplicate(const MachineInstr *MI,
1253 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001254 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1255 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001256 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001257 return PrevMI;
1258 }
1259 return 0;
1260}
1261
1262bool MachineLICM::EliminateCSE(MachineInstr *MI,
1263 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001264 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1265 // the undef property onto uses.
1266 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001267 return false;
1268
1269 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001270 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001271
1272 // Replace virtual registers defined by MI by their counterparts defined
1273 // by Dup.
Evan Cheng1025cce2011-10-17 19:50:12 +00001274 SmallVector<unsigned, 2> Defs;
Evan Cheng78e5c112009-11-07 03:52:02 +00001275 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1276 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001277
1278 // Physical registers may not differ here.
1279 assert((!MO.isReg() || MO.getReg() == 0 ||
1280 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1281 MO.getReg() == Dup->getOperand(i).getReg()) &&
1282 "Instructions with different phys regs are not identical!");
1283
1284 if (MO.isReg() && MO.isDef() &&
Evan Cheng1025cce2011-10-17 19:50:12 +00001285 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1286 Defs.push_back(i);
1287 }
1288
1289 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1290 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1291 unsigned Idx = Defs[i];
1292 unsigned Reg = MI->getOperand(Idx).getReg();
1293 unsigned DupReg = Dup->getOperand(Idx).getReg();
1294 OrigRCs.push_back(MRI->getRegClass(DupReg));
1295
1296 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1297 // Restore old RCs if more than one defs.
1298 for (unsigned j = 0; j != i; ++j)
1299 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1300 return false;
Dan Gohmane6cd7572010-05-13 20:34:42 +00001301 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001302 }
Evan Cheng1025cce2011-10-17 19:50:12 +00001303
1304 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1305 unsigned Idx = Defs[i];
1306 unsigned Reg = MI->getOperand(Idx).getReg();
1307 unsigned DupReg = Dup->getOperand(Idx).getReg();
1308 MRI->replaceRegWith(Reg, DupReg);
1309 MRI->clearKillFlags(DupReg);
1310 }
1311
Evan Cheng78e5c112009-11-07 03:52:02 +00001312 MI->eraseFromParent();
1313 ++NumCSEed;
1314 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001315 }
1316 return false;
1317}
1318
Evan Cheng7efba852011-10-12 00:09:14 +00001319/// MayCSE - Return true if the given instruction will be CSE'd if it's
1320/// hoisted out of the loop.
1321bool MachineLICM::MayCSE(MachineInstr *MI) {
1322 unsigned Opcode = MI->getOpcode();
1323 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1324 CI = CSEMap.find(Opcode);
1325 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1326 // the undef property onto uses.
1327 if (CI == CSEMap.end() || MI->isImplicitDef())
1328 return false;
1329
1330 return LookForDuplicate(MI, CI->second) != 0;
1331}
1332
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001333/// Hoist - When an instruction is found to use only loop invariant operands
1334/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001335///
Evan Cheng134982d2010-10-20 22:03:58 +00001336bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001337 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001338 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001339 // If not, try unfolding a hoistable load.
1340 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001341 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001342 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001343
Dan Gohmanc475c362009-01-15 22:01:38 +00001344 // Now move the instructions to the predecessor, inserting it before any
1345 // terminator instructions.
1346 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001347 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001348 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001349 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001350 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001351 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001352 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001353 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001354 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001355 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001356
Evan Cheng777c6b72009-11-03 21:40:02 +00001357 // If this is the first instruction being hoisted to the preheader,
1358 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001359 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001360 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001361 FirstInLoop = false;
1362 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001363
Evan Chengaf6949d2009-02-05 08:45:46 +00001364 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001365 unsigned Opcode = MI->getOpcode();
1366 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1367 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001368 if (!EliminateCSE(MI, CI)) {
1369 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001370 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001371
Evan Cheng134982d2010-10-20 22:03:58 +00001372 // Update register pressure for BBs from header to this block.
1373 UpdateBackTraceRegPressure(MI);
1374
Dan Gohmane6cd7572010-05-13 20:34:42 +00001375 // Clear the kill flags of any register this instruction defines,
1376 // since they may need to be live throughout the entire loop
1377 // rather than just live for part of it.
1378 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1379 MachineOperand &MO = MI->getOperand(i);
1380 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001381 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001382 }
1383
Evan Chengaf6949d2009-02-05 08:45:46 +00001384 // Add to the CSE map.
1385 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001386 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001387 else {
1388 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001389 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001390 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001391 }
1392 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001393
Dan Gohmanc475c362009-01-15 22:01:38 +00001394 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001395 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001396
1397 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001398}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001399
1400MachineBasicBlock *MachineLICM::getCurPreheader() {
1401 // Determine the block to which to hoist instructions. If we can't find a
1402 // suitable loop predecessor, we can't do any hoisting.
1403
1404 // If we've tried to get a preheader and failed, don't try again.
1405 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1406 return 0;
1407
1408 if (!CurPreheader) {
1409 CurPreheader = CurLoop->getLoopPreheader();
1410 if (!CurPreheader) {
1411 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1412 if (!Pred) {
1413 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1414 return 0;
1415 }
1416
1417 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1418 if (!CurPreheader) {
1419 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1420 return 0;
1421 }
1422 }
1423 }
1424 return CurPreheader;
1425}