blob: 8c562cc4454ae55decf59341147ab79dcee7b1fa [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 {
Bill Wendling9258cd32008-01-02 19:32:43 +000063 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000064 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000065 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000066 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000067 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000068 MachineRegisterInfo *MRI;
69 const InstrItineraryData *InstrItins;
Andrew Trick9d41bd52012-02-08 21:23:03 +000070 bool PreRegAlloc;
Bill Wendling12ebf142007-12-11 19:40:06 +000071
Bill Wendling0f940c92007-12-07 21:42:31 +000072 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000073 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000074 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000075 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000076
Bill Wendling0f940c92007-12-07 21:42:31 +000077 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000078 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000079 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000080 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000081 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000082
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +000083 // Exit blocks for CurLoop.
84 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
85
86 bool isExitBlock(const MachineBasicBlock *MBB) const {
87 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
88 ExitBlocks.end();
89 }
90
Evan Cheng0e673912010-10-14 01:16:09 +000091 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000092 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000093 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000094
95 // Register pressure "limit" per register class. If the pressure
96 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000097 SmallVector<unsigned, 8> RegLimit;
98
Evan Cheng03a9fdf2010-10-16 02:20:26 +000099 // Register pressure on path leading from loop preheader to current BB.
100 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
101
Dale Johannesenc46a5f22010-07-29 17:45:24 +0000102 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +0000103 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +0000104
Evan Chengfad62872011-10-11 23:48:44 +0000105 enum {
106 SpeculateFalse = 0,
107 SpeculateTrue = 1,
108 SpeculateUnknown = 2
109 };
110
Devang Patel2e350472011-10-11 18:09:58 +0000111 // If a MBB does not dominate loop exiting blocks then it may not safe
112 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000113 // Tri-state: 0 - false, 1 - true, 2 - unknown
114 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000115
Bill Wendling0f940c92007-12-07 21:42:31 +0000116 public:
117 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000118 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000119 MachineFunctionPass(ID), PreRegAlloc(true) {
120 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
121 }
Evan Chengd94671a2010-04-07 00:41:17 +0000122
123 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000124 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
125 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
126 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000127
128 virtual bool runOnMachineFunction(MachineFunction &MF);
129
Bill Wendling0f940c92007-12-07 21:42:31 +0000130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000131 AU.addRequired<MachineLoopInfo>();
132 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000133 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000134 AU.addPreserved<MachineLoopInfo>();
135 AU.addPreserved<MachineDominatorTree>();
136 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000137 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000138
139 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000140 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000141 RegPressure.clear();
142 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000143 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000144 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
145 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
146 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000147 CSEMap.clear();
148 }
149
Bill Wendling0f940c92007-12-07 21:42:31 +0000150 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000151 /// CandidateInfo - Keep track of information about hoisting candidates.
152 struct CandidateInfo {
153 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000154 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000155 int FI;
156 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
157 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000158 };
159
160 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
161 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000162 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000163
164 /// HoistPostRA - When an instruction is found to only use loop invariant
165 /// operands that is safe to hoist, this instruction is called to do the
166 /// dirty work.
167 void HoistPostRA(MachineInstr *MI, unsigned Def);
168
169 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
170 /// gather register def and frame object update information.
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000171 void ProcessMI(MachineInstr *MI,
172 BitVector &PhysRegDefs,
173 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000174 SmallSet<int, 32> &StoredFIs,
175 SmallVector<CandidateInfo, 32> &Candidates);
176
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000177 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
178 /// current loop.
179 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000180
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000181 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000182 /// candidate for LICM. e.g. If the instruction is a call, then it's
183 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000184 bool IsLICMCandidate(MachineInstr &I);
185
Bill Wendling041b3f82007-12-08 23:58:46 +0000186 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000187 /// invariant. I.e., all virtual register operands are defined outside of
188 /// the loop, physical registers aren't accessed (explicitly or implicitly),
189 /// and the instruction is hoistable.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000190 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000191 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000192
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000193 /// HasLoopPHIUse - Return true if the specified instruction is used by any
194 /// phi node in the current loop.
195 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengd67705f2011-04-11 21:09:18 +0000196
Evan Cheng23128422010-10-19 18:58:51 +0000197 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
198 /// and an use in the current loop, return true if the target considered
199 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000200 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
201 unsigned Reg) const;
202
203 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000204
Evan Cheng134982d2010-10-20 22:03:58 +0000205 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
206 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000207 /// register pressure.
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +0000208 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
Evan Cheng134982d2010-10-20 22:03:58 +0000209
210 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
211 /// the current block and update their register pressures to reflect the
212 /// effect of hoisting MI from the current block to the preheader.
213 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000214
Evan Cheng45e94d62009-02-04 09:19:56 +0000215 /// IsProfitableToHoist - Return true if it is potentially profitable to
216 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000217 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000218
Devang Patel2e350472011-10-11 18:09:58 +0000219 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
220 /// If not then a load from this mbb may not be safe to hoist.
221 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
222
Pete Cooperacde91e2011-12-22 02:05:40 +0000223 void EnterScope(MachineBasicBlock *MBB);
224
225 void ExitScope(MachineBasicBlock *MBB);
226
227 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
228 /// dominator tree node if its a leaf or all of its children are done. Walk
229 /// up the dominator tree to destroy ancestors which are now done.
230 void ExitScopeIfDone(MachineDomTreeNode *Node,
231 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
232 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
233
234 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
235 /// blocks dominated by the specified header block, and that are in the
236 /// current loop) in depth first order w.r.t the DominatorTree. This allows
237 /// us to visit definitions before uses, allowing us to hoist a loop body in
238 /// one pass without iteration.
Bill Wendling0f940c92007-12-07 21:42:31 +0000239 ///
Pete Cooperacde91e2011-12-22 02:05:40 +0000240 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
241 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendling0f940c92007-12-07 21:42:31 +0000242
Evan Cheng61560e22011-09-01 01:45:00 +0000243 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
244 /// index, return the ID and cost of its representative register class by
245 /// reference.
246 void getRegisterClassIDAndCost(const MachineInstr *MI,
247 unsigned Reg, unsigned OpIdx,
248 unsigned &RCId, unsigned &RCCost) const;
249
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000250 /// InitRegPressure - Find all virtual register references that are liveout
251 /// of the preheader to initialize the starting "register pressure". Note
252 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000253 void InitRegPressure(MachineBasicBlock *BB);
254
Evan Cheng134982d2010-10-20 22:03:58 +0000255 /// UpdateRegPressure - Update estimate of register pressure after the
256 /// specified instruction.
257 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000258
Dan Gohman5c952302009-10-29 17:47:20 +0000259 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
260 /// the load itself could be hoisted. Return the unfolded and hoistable
261 /// load, or null if the load couldn't be unfolded or if it wouldn't
262 /// be hoistable.
263 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
264
Evan Cheng78e5c112009-11-07 03:52:02 +0000265 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
266 /// duplicate of MI. Return this instruction if it's found.
267 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
268 std::vector<const MachineInstr*> &PrevMIs);
269
Evan Cheng9fb744e2009-11-05 00:51:13 +0000270 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
271 /// the preheader that compute the same value. If it's found, do a RAU on
272 /// with the definition of the existing instruction rather than hoisting
273 /// the instruction to the preheader.
274 bool EliminateCSE(MachineInstr *MI,
275 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
276
Evan Cheng7efba852011-10-12 00:09:14 +0000277 /// MayCSE - Return true if the given instruction will be CSE'd if it's
278 /// hoisted out of the loop.
279 bool MayCSE(MachineInstr *MI);
280
Bill Wendling0f940c92007-12-07 21:42:31 +0000281 /// Hoist - When an instruction is found to only use loop invariant operands
282 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000283 /// It returns true if the instruction is hoisted.
284 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000285
286 /// InitCSEMap - Initialize the CSE map with instructions that are in the
287 /// current loop preheader that may become duplicates of instructions that
288 /// are hoisted out of the loop.
289 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000290
291 /// getCurPreheader - Get the preheader for the current loop, splitting
292 /// a critical edge if needed.
293 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000294 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000295} // end anonymous namespace
296
Dan Gohman844731a2008-05-13 00:00:25 +0000297char MachineLICM::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000298char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000299INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
300 "Machine Loop Invariant Code Motion", false, false)
301INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
302INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
303INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
304INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000305 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000306
Dan Gohman853d3fb2010-06-22 17:25:57 +0000307/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
308/// loop that has a unique predecessor.
309static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000310 // Check whether this loop even has a unique predecessor.
311 if (!CurLoop->getLoopPredecessor())
312 return false;
313 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000314 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000315 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000316 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000317 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000318 return true;
319}
320
Bill Wendling0f940c92007-12-07 21:42:31 +0000321bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000322 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000323 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000324 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000325 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000326 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000327 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000328 MRI = &MF.getRegInfo();
329 InstrItins = TM->getInstrItineraryData();
Bill Wendling0f940c92007-12-07 21:42:31 +0000330
Andrew Trick9d41bd52012-02-08 21:23:03 +0000331 PreRegAlloc = MRI->isSSA();
332
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000333 if (PreRegAlloc)
334 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
335 else
336 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
337 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
338
Evan Cheng0e673912010-10-14 01:16:09 +0000339 if (PreRegAlloc) {
340 // Estimate register pressure during pre-regalloc pass.
341 unsigned NumRC = TRI->getNumRegClasses();
342 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000343 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000344 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000345 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
346 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000347 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000348 }
349
Bill Wendling0f940c92007-12-07 21:42:31 +0000350 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000351 MLI = &getAnalysis<MachineLoopInfo>();
352 DT = &getAnalysis<MachineDominatorTree>();
353 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000354
Dan Gohmanaa742602010-07-09 18:49:45 +0000355 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
356 while (!Worklist.empty()) {
357 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000358 CurPreheader = 0;
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000359 ExitBlocks.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000360
Evan Cheng4038f9c2010-04-08 01:03:47 +0000361 // If this is done before regalloc, only visit outer-most preheader-sporting
362 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000363 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
364 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000365 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000366 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000367
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000368 CurLoop->getExitBlocks(ExitBlocks);
369
Evan Chengd94671a2010-04-07 00:41:17 +0000370 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000371 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000372 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000373 // CSEMap is initialized for loop header when the first instruction is
374 // being hoisted.
375 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000376 FirstInLoop = true;
Pete Cooperacde91e2011-12-22 02:05:40 +0000377 HoistOutOfLoop(N);
Evan Chengd94671a2010-04-07 00:41:17 +0000378 CSEMap.clear();
379 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000380 }
381
382 return Changed;
383}
384
Evan Cheng4038f9c2010-04-08 01:03:47 +0000385/// InstructionStoresToFI - Return true if instruction stores to the
386/// specified frame.
387static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
388 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
389 oe = MI->memoperands_end(); o != oe; ++o) {
390 if (!(*o)->isStore() || !(*o)->getValue())
391 continue;
392 if (const FixedStackPseudoSourceValue *Value =
393 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
394 if (Value->getFrameIndex() == FI)
395 return true;
396 }
397 }
398 return false;
399}
400
401/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
402/// gather register def and frame object update information.
403void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000404 BitVector &PhysRegDefs,
405 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000406 SmallSet<int, 32> &StoredFIs,
407 SmallVector<CandidateInfo, 32> &Candidates) {
408 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000409 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000410 unsigned Def = 0;
411 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
412 const MachineOperand &MO = MI->getOperand(i);
413 if (MO.isFI()) {
414 // Remember if the instruction stores to the frame index.
415 int FI = MO.getIndex();
416 if (!StoredFIs.count(FI) &&
417 MFI->isSpillSlotObjectIndex(FI) &&
418 InstructionStoresToFI(MI, FI))
419 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000420 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000421 continue;
422 }
423
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000424 // We can't hoist an instruction defining a physreg that is clobbered in
425 // the loop.
426 if (MO.isRegMask()) {
Jakob Stoklund Olesen478a8a02012-02-02 23:52:57 +0000427 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000428 continue;
429 }
430
Evan Cheng4038f9c2010-04-08 01:03:47 +0000431 if (!MO.isReg())
432 continue;
433 unsigned Reg = MO.getReg();
434 if (!Reg)
435 continue;
436 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
437 "Not expecting virtual register!");
438
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000439 if (!MO.isDef()) {
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000440 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000441 // If it's using a non-loop-invariant register, then it's obviously not
442 // safe to hoist.
443 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000444 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000445 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000446
447 if (MO.isImplicit()) {
Craig Toppere4fd9072012-03-04 10:43:23 +0000448 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS)
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000449 PhysRegClobbers.set(*AS);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000450 if (!MO.isDead())
451 // Non-dead implicit def? This cannot be hoisted.
452 RuledOut = true;
453 // No need to check if a dead implicit def is also defined by
454 // another instruction.
455 continue;
456 }
457
458 // FIXME: For now, avoid instructions with multiple defs, unless
459 // it's a dead implicit def.
460 if (Def)
461 RuledOut = true;
462 else
463 Def = Reg;
464
465 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000466 // register, then this is not safe. Two defs is indicated by setting a
467 // PhysRegClobbers bit.
Craig Toppere4fd9072012-03-04 10:43:23 +0000468 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS) {
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000469 if (PhysRegDefs.test(*AS))
470 PhysRegClobbers.set(*AS);
471 if (PhysRegClobbers.test(*AS))
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000472 // MI defined register is seen defined by another instruction in
473 // the loop, it cannot be a LICM candidate.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000474 RuledOut = true;
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000475 PhysRegDefs.set(*AS);
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000476 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000477 }
478
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000479 // Only consider reloads for now and remats which do not have register
480 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000481 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000482 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000483 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000484 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
485 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000486 }
487}
488
489/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
490/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000491void MachineLICM::HoistRegionPostRA() {
Evan Chengd6c23552012-03-27 01:50:58 +0000492 MachineBasicBlock *Preheader = getCurPreheader();
493 if (!Preheader)
494 return;
495
Evan Chengd94671a2010-04-07 00:41:17 +0000496 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000497 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
498 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Chengd94671a2010-04-07 00:41:17 +0000499
Evan Cheng4038f9c2010-04-08 01:03:47 +0000500 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000501 SmallSet<int, 32> StoredFIs;
502
503 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000504 // collect potential LICM candidates.
505 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
506 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
507 MachineBasicBlock *BB = Blocks[i];
Bill Wendlinga2e87912011-10-12 02:58:01 +0000508
509 // If the header of the loop containing this basic block is a landing pad,
510 // then don't try to hoist instructions out of this loop.
511 const MachineLoop *ML = MLI->getLoopFor(BB);
512 if (ML && ML->getHeader()->isLandingPad()) continue;
513
Evan Chengd94671a2010-04-07 00:41:17 +0000514 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000515 // FIXME: That means a reload that're reused in successor block(s) will not
516 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000517 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000518 E = BB->livein_end(); I != E; ++I) {
519 unsigned Reg = *I;
Craig Toppere4fd9072012-03-04 10:43:23 +0000520 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS)
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000521 PhysRegDefs.set(*AS);
Evan Chengd94671a2010-04-07 00:41:17 +0000522 }
523
Evan Chengfad62872011-10-11 23:48:44 +0000524 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000525 for (MachineBasicBlock::iterator
526 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000527 MachineInstr *MI = &*MII;
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000528 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000529 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000530 }
Evan Chengd94671a2010-04-07 00:41:17 +0000531
Evan Chengd6c23552012-03-27 01:50:58 +0000532 // Gather the registers read / clobbered by the terminator.
533 BitVector TermRegs(NumRegs);
534 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
535 if (TI != Preheader->end()) {
536 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
537 const MachineOperand &MO = TI->getOperand(i);
538 if (!MO.isReg())
539 continue;
540 unsigned Reg = MO.getReg();
541 if (!Reg)
542 continue;
543 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS)
544 TermRegs.set(*AS);
545 }
546 }
547
Evan Chengd94671a2010-04-07 00:41:17 +0000548 // Now evaluate whether the potential candidates qualify.
549 // 1. Check if the candidate defined register is defined by another
550 // instruction in the loop.
551 // 2. If the candidate is a load from stack slot (always true for now),
552 // check if the slot is stored anywhere in the loop.
Evan Chengd6c23552012-03-27 01:50:58 +0000553 // 3. Make sure candidate def should not clobber
554 // registers read by the terminator. Similarly its def should not be
555 // clobbered by the terminator.
Evan Chengd94671a2010-04-07 00:41:17 +0000556 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000557 if (Candidates[i].FI != INT_MIN &&
558 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000559 continue;
560
Evan Chengd6c23552012-03-27 01:50:58 +0000561 unsigned Def = Candidates[i].Def;
562 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000563 bool Safe = true;
564 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000565 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
566 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000567 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000568 continue;
Evan Chengd6c23552012-03-27 01:50:58 +0000569 unsigned Reg = MO.getReg();
570 if (PhysRegDefs.test(Reg) ||
571 PhysRegClobbers.test(Reg)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000572 // If it's using a non-loop-invariant register, then it's obviously
573 // not safe to hoist.
574 Safe = false;
575 break;
576 }
577 }
578 if (Safe)
579 HoistPostRA(MI, Candidates[i].Def);
580 }
Evan Chengd94671a2010-04-07 00:41:17 +0000581 }
582}
583
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000584/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
585/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000586void MachineLICM::AddToLiveIns(unsigned Reg) {
587 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000588 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
589 MachineBasicBlock *BB = Blocks[i];
590 if (!BB->isLiveIn(Reg))
591 BB->addLiveIn(Reg);
592 for (MachineBasicBlock::iterator
593 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
594 MachineInstr *MI = &*MII;
595 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
596 MachineOperand &MO = MI->getOperand(i);
597 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
598 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
599 MO.setIsKill(false);
600 }
601 }
602 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000603}
604
605/// HoistPostRA - When an instruction is found to only use loop invariant
606/// operands that is safe to hoist, this instruction is called to do the
607/// dirty work.
608void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000609 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000610
Evan Chengd94671a2010-04-07 00:41:17 +0000611 // Now move the instructions to the predecessor, inserting it before any
612 // terminator instructions.
Jakob Stoklund Olesen39f66602012-01-23 21:01:11 +0000613 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
614 << MI->getParent()->getNumber() << ": " << *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000615
616 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000617 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000618 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000619
Andrew Trick9f17cf62012-02-08 21:23:00 +0000620 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000621 // loop invariant must be kept live throughout the whole loop. This is
622 // important to ensure later passes do not scavenge the def register.
623 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000624
625 ++NumPostRAHoisted;
626 Changed = true;
627}
628
Devang Patel2e350472011-10-11 18:09:58 +0000629// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
630// If not then a load from this mbb may not be safe to hoist.
631bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000632 if (SpeculationState != SpeculateUnknown)
633 return SpeculationState == SpeculateFalse;
Andrew Trick9f17cf62012-02-08 21:23:00 +0000634
Devang Patel2e350472011-10-11 18:09:58 +0000635 if (BB != CurLoop->getHeader()) {
636 // Check loop exiting blocks.
637 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
638 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
639 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
640 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewyckyea3abd52011-10-13 01:09:50 +0000641 SpeculationState = SpeculateTrue;
642 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000643 }
644 }
645
Evan Chengfad62872011-10-11 23:48:44 +0000646 SpeculationState = SpeculateFalse;
647 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000648}
649
Pete Cooperacde91e2011-12-22 02:05:40 +0000650void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
651 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendling0f940c92007-12-07 21:42:31 +0000652
Pete Cooperacde91e2011-12-22 02:05:40 +0000653 // Remember livein register pressure.
654 BackTrace.push_back(RegPressure);
655}
Bill Wendlinga2e87912011-10-12 02:58:01 +0000656
Pete Cooperacde91e2011-12-22 02:05:40 +0000657void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
658 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
659 BackTrace.pop_back();
660}
Bill Wendling0f940c92007-12-07 21:42:31 +0000661
Pete Cooperacde91e2011-12-22 02:05:40 +0000662/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
663/// dominator tree node if its a leaf or all of its children are done. Walk
664/// up the dominator tree to destroy ancestors which are now done.
665void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Cheng75fda5d2012-01-10 22:27:32 +0000666 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
667 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000668 if (OpenChildren[Node])
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000669 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000670
Pete Cooperacde91e2011-12-22 02:05:40 +0000671 // Pop scope.
672 ExitScope(Node->getBlock());
673
674 // Now traverse upwards to pop ancestors whose offsprings are all done.
675 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
676 unsigned Left = --OpenChildren[Parent];
677 if (Left != 0)
678 break;
679 ExitScope(Parent->getBlock());
680 Node = Parent;
681 }
682}
683
684/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
685/// blocks dominated by the specified header block, and that are in the
686/// current loop) in depth first order w.r.t the DominatorTree. This allows
687/// us to visit definitions before uses, allowing us to hoist a loop body in
688/// one pass without iteration.
689///
690void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
691 SmallVector<MachineDomTreeNode*, 32> Scopes;
692 SmallVector<MachineDomTreeNode*, 8> WorkList;
693 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
694 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
695
696 // Perform a DFS walk to determine the order of visit.
697 WorkList.push_back(HeaderN);
698 do {
699 MachineDomTreeNode *Node = WorkList.pop_back_val();
700 assert(Node != 0 && "Null dominator tree node?");
701 MachineBasicBlock *BB = Node->getBlock();
702
703 // If the header of the loop containing this basic block is a landing pad,
704 // then don't try to hoist instructions out of this loop.
705 const MachineLoop *ML = MLI->getLoopFor(BB);
706 if (ML && ML->getHeader()->isLandingPad())
707 continue;
708
709 // If this subregion is not in the top level loop at all, exit.
710 if (!CurLoop->contains(BB))
711 continue;
712
713 Scopes.push_back(Node);
714 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
715 unsigned NumChildren = Children.size();
716
717 // Don't hoist things out of a large switch statement. This often causes
718 // code to be hoisted that wasn't going to be executed, and increases
719 // register pressure in a situation where it's likely to matter.
720 if (BB->succ_size() >= 25)
721 NumChildren = 0;
722
723 OpenChildren[Node] = NumChildren;
724 // Add children in reverse order as then the next popped worklist node is
725 // the first child of this node. This means we ultimately traverse the
726 // DOM tree in exactly the same order as if we'd recursed.
727 for (int i = (int)NumChildren-1; i >= 0; --i) {
728 MachineDomTreeNode *Child = Children[i];
729 ParentMap[Child] = Node;
730 WorkList.push_back(Child);
731 }
732 } while (!WorkList.empty());
733
734 if (Scopes.size() != 0) {
735 MachineBasicBlock *Preheader = getCurPreheader();
736 if (!Preheader)
737 return;
738
Evan Cheng134982d2010-10-20 22:03:58 +0000739 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000740 RegSeen.clear();
741 BackTrace.clear();
742 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000743 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000744
Pete Cooperacde91e2011-12-22 02:05:40 +0000745 // Now perform LICM.
746 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
747 MachineDomTreeNode *Node = Scopes[i];
748 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng23128422010-10-19 18:58:51 +0000749
Pete Cooperacde91e2011-12-22 02:05:40 +0000750 MachineBasicBlock *Preheader = getCurPreheader();
751 if (!Preheader)
752 continue;
753
754 EnterScope(MBB);
755
756 // Process the block
757 SpeculationState = SpeculateUnknown;
758 for (MachineBasicBlock::iterator
759 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
760 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
761 MachineInstr *MI = &*MII;
762 if (!Hoist(MI, Preheader))
763 UpdateRegPressure(MI);
764 MII = NextMII;
765 }
766
767 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
768 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohmanc475c362009-01-15 22:01:38 +0000769 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000770}
771
Evan Cheng134982d2010-10-20 22:03:58 +0000772static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
773 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
774}
775
Evan Cheng61560e22011-09-01 01:45:00 +0000776/// getRegisterClassIDAndCost - For a given MI, register, and the operand
777/// index, return the ID and cost of its representative register class.
778void
779MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
780 unsigned Reg, unsigned OpIdx,
781 unsigned &RCId, unsigned &RCCost) const {
782 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
783 EVT VT = *RC->vt_begin();
Owen Anderson99aa14f2011-11-16 01:02:57 +0000784 if (VT == MVT::Untyped) {
Evan Cheng61560e22011-09-01 01:45:00 +0000785 RCId = RC->getID();
786 RCCost = 1;
787 } else {
788 RCId = TLI->getRepRegClassFor(VT)->getID();
789 RCCost = TLI->getRepRegClassCostFor(VT);
790 }
791}
Andrew Trick9f17cf62012-02-08 21:23:00 +0000792
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000793/// InitRegPressure - Find all virtual register references that are liveout of
794/// the preheader to initialize the starting "register pressure". Note this
795/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000796void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000797 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000798
Evan Cheng134982d2010-10-20 22:03:58 +0000799 // If the preheader has only a single predecessor and it ends with a
800 // fallthrough or an unconditional branch, then scan its predecessor for live
801 // defs as well. This happens whenever the preheader is created by splitting
802 // the critical edge from the loop predecessor to the loop header.
803 if (BB->pred_size() == 1) {
804 MachineBasicBlock *TBB = 0, *FBB = 0;
805 SmallVector<MachineOperand, 4> Cond;
806 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
807 InitRegPressure(*BB->pred_begin());
808 }
809
Evan Cheng0e673912010-10-14 01:16:09 +0000810 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
811 MII != E; ++MII) {
812 MachineInstr *MI = &*MII;
813 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
814 const MachineOperand &MO = MI->getOperand(i);
815 if (!MO.isReg() || MO.isImplicit())
816 continue;
817 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000818 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000819 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000820
Andrew Trickdc986d22010-10-19 02:50:50 +0000821 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000822 unsigned RCId, RCCost;
823 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000824 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000825 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000826 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000827 bool isKill = isOperandKill(MO, MRI);
828 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000829 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000830 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000831 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000832 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000833 }
Evan Cheng0e673912010-10-14 01:16:09 +0000834 }
835 }
836}
837
Evan Cheng134982d2010-10-20 22:03:58 +0000838/// UpdateRegPressure - Update estimate of register pressure after the
839/// specified instruction.
840void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
841 if (MI->isImplicitDef())
842 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000843
Evan Cheng134982d2010-10-20 22:03:58 +0000844 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000845 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
846 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000847 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000848 continue;
849 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000850 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000851 continue;
852
Andrew Trickdc986d22010-10-19 02:50:50 +0000853 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000854 if (MO.isDef())
855 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000856 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000857 unsigned RCId, RCCost;
858 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000859 if (RCCost > RegPressure[RCId])
860 RegPressure[RCId] = 0;
861 else
Evan Cheng23128422010-10-19 18:58:51 +0000862 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000863 }
Evan Cheng0e673912010-10-14 01:16:09 +0000864 }
Evan Cheng0e673912010-10-14 01:16:09 +0000865
Evan Cheng61560e22011-09-01 01:45:00 +0000866 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000867 while (!Defs.empty()) {
868 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000869 unsigned RCId, RCCost;
870 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000871 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000872 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000873 }
874}
875
Andrew Trick9f17cf62012-02-08 21:23:00 +0000876/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel06e16bb2011-10-20 17:42:23 +0000877/// loads from global offset table or constant pool.
878static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000879 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel6c15fec2011-10-17 17:35:01 +0000880 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick9f17cf62012-02-08 21:23:00 +0000881 E = MI.memoperands_end(); I != E; ++I) {
Devang Patel6c15fec2011-10-17 17:35:01 +0000882 if (const Value *V = (*I)->getValue()) {
883 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
Devang Patel06e16bb2011-10-20 17:42:23 +0000884 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
Andrew Trick9f17cf62012-02-08 21:23:00 +0000885 return true;
Devang Patel6c15fec2011-10-17 17:35:01 +0000886 }
887 }
888 return false;
889}
890
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000891/// IsLICMCandidate - Returns true if the instruction may be a suitable
892/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
893/// not safe to hoist it.
894bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000895 // Check if it's safe to move the instruction.
896 bool DontMoveAcrossStore = true;
897 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000898 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000899
900 // If it is load then check if it is guaranteed to execute by making sure that
901 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patele6de9f32011-10-20 17:31:18 +0000902 // the loop which does not execute this load, so we can't hoist it. Loads
903 // from constant memory are not safe to speculate all the time, for example
904 // indexed load from a jump table.
Devang Patel2e350472011-10-11 18:09:58 +0000905 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000906 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel6c15fec2011-10-17 17:35:01 +0000907 !IsGuaranteedToExecute(I.getParent()))
Devang Patel2e350472011-10-11 18:09:58 +0000908 return false;
909
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000910 return true;
911}
912
913/// IsLoopInvariantInst - Returns true if the instruction is loop
914/// invariant. I.e., all virtual register operands are defined outside of the
915/// loop, physical registers aren't accessed explicitly, and there are no side
916/// effects that aren't captured by the operands or other flags.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000917///
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000918bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
919 if (!IsLICMCandidate(I))
920 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000921
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000922 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000923 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
924 const MachineOperand &MO = I.getOperand(i);
925
Dan Gohmand735b802008-10-03 15:45:36 +0000926 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000927 continue;
928
Dan Gohmanc475c362009-01-15 22:01:38 +0000929 unsigned Reg = MO.getReg();
930 if (Reg == 0) continue;
931
932 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000933 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000934 if (MO.isUse()) {
935 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000936 // and we can freely move its uses. Alternatively, if it's allocatable,
937 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000938 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000939 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000940 // Otherwise it's safe to move.
941 continue;
942 } else if (!MO.isDead()) {
943 // A def that isn't dead. We can't move it.
944 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000945 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
946 // If the reg is live into the loop, we can't hoist an instruction
947 // which would clobber it.
948 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000949 }
950 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000951
952 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000953 continue;
954
Evan Cheng0e673912010-10-14 01:16:09 +0000955 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000956 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000957
958 // If the loop contains the definition of an operand, then the instruction
959 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000960 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000961 return false;
962 }
963
964 // If we got this far, the instruction is loop invariant!
965 return true;
966}
967
Evan Chengaf6949d2009-02-05 08:45:46 +0000968
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000969/// HasLoopPHIUse - Return true if the specified instruction is used by a
970/// phi node and hoisting it could cause a copy to be inserted.
971bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
972 SmallVector<const MachineInstr*, 8> Work(1, MI);
973 do {
974 MI = Work.pop_back_val();
975 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
976 if (!MO->isReg() || !MO->isDef())
977 continue;
978 unsigned Reg = MO->getReg();
979 if (!TargetRegisterInfo::isVirtualRegister(Reg))
980 continue;
981 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
982 UE = MRI->use_end(); UI != UE; ++UI) {
983 MachineInstr *UseMI = &*UI;
984 // A PHI may cause a copy to be inserted.
985 if (UseMI->isPHI()) {
986 // A PHI inside the loop causes a copy because the live range of Reg is
987 // extended across the PHI.
988 if (CurLoop->contains(UseMI))
989 return true;
990 // A PHI in an exit block can cause a copy to be inserted if the PHI
991 // has multiple predecessors in the loop with different values.
992 // For now, approximate by rejecting all exit blocks.
993 if (isExitBlock(UseMI->getParent()))
994 return true;
995 continue;
996 }
997 // Look past copies as well.
998 if (UseMI->isCopy() && CurLoop->contains(UseMI))
999 Work.push_back(UseMI);
1000 }
Evan Chengd67705f2011-04-11 21:09:18 +00001001 }
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001002 } while (!Work.empty());
Evan Chengaf6949d2009-02-05 08:45:46 +00001003 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001004}
1005
Evan Cheng23128422010-10-19 18:58:51 +00001006/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1007/// and an use in the current loop, return true if the target considered
1008/// it 'high'.
1009bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +00001010 unsigned DefIdx, unsigned Reg) const {
1011 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +00001012 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001013
Evan Cheng0e673912010-10-14 01:16:09 +00001014 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
1015 E = MRI->use_nodbg_end(); I != E; ++I) {
1016 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +00001017 if (UseMI->isCopyLike())
1018 continue;
Evan Cheng0e673912010-10-14 01:16:09 +00001019 if (!CurLoop->contains(UseMI->getParent()))
1020 continue;
1021 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
1022 const MachineOperand &MO = UseMI->getOperand(i);
1023 if (!MO.isReg() || !MO.isUse())
1024 continue;
1025 unsigned MOReg = MO.getReg();
1026 if (MOReg != Reg)
1027 continue;
1028
Evan Cheng23128422010-10-19 18:58:51 +00001029 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
1030 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001031 }
1032
Evan Cheng23128422010-10-19 18:58:51 +00001033 // Only look at the first in loop use.
1034 break;
Evan Cheng0e673912010-10-14 01:16:09 +00001035 }
1036
Evan Cheng23128422010-10-19 18:58:51 +00001037 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001038}
1039
Evan Chengc8141df2010-10-26 02:08:50 +00001040/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1041/// the operand latency between its def and a use is one or less.
1042bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001043 if (MI.isAsCheapAsAMove() || MI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +00001044 return true;
1045 if (!InstrItins || InstrItins->isEmpty())
1046 return false;
1047
1048 bool isCheap = false;
1049 unsigned NumDefs = MI.getDesc().getNumDefs();
1050 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1051 MachineOperand &DefMO = MI.getOperand(i);
1052 if (!DefMO.isReg() || !DefMO.isDef())
1053 continue;
1054 --NumDefs;
1055 unsigned Reg = DefMO.getReg();
1056 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1057 continue;
1058
1059 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1060 return false;
1061 isCheap = true;
1062 }
1063
1064 return isCheap;
1065}
1066
Evan Cheng134982d2010-10-20 22:03:58 +00001067/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001068/// if hoisting an instruction of the given cost matrix can cause high
1069/// register pressure.
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001070bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1071 bool CheapInstr) {
Evan Cheng134982d2010-10-20 22:03:58 +00001072 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1073 CI != CE; ++CI) {
Andrew Trick9f17cf62012-02-08 21:23:00 +00001074 if (CI->second <= 0)
Evan Cheng134982d2010-10-20 22:03:58 +00001075 continue;
1076
1077 unsigned RCId = CI->first;
Pete Cooper3cfecf52011-12-22 02:13:25 +00001078 unsigned Limit = RegLimit[RCId];
1079 int Cost = CI->second;
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001080
1081 // Don't hoist cheap instructions if they would increase register pressure,
1082 // even if we're under the limit.
1083 if (CheapInstr)
1084 return true;
1085
Evan Cheng134982d2010-10-20 22:03:58 +00001086 for (unsigned i = BackTrace.size(); i != 0; --i) {
1087 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Pete Cooper3cfecf52011-12-22 02:13:25 +00001088 if (RP[RCId] + Cost >= Limit)
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001089 return true;
1090 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001091 }
1092
1093 return false;
1094}
1095
Evan Cheng134982d2010-10-20 22:03:58 +00001096/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1097/// current block and update their register pressures to reflect the effect
1098/// of hoisting MI from the current block to the preheader.
1099void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1100 if (MI->isImplicitDef())
1101 return;
1102
1103 // First compute the 'cost' of the instruction, i.e. its contribution
1104 // to register pressure.
1105 DenseMap<unsigned, int> Cost;
1106 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1107 const MachineOperand &MO = MI->getOperand(i);
1108 if (!MO.isReg() || MO.isImplicit())
1109 continue;
1110 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001111 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +00001112 continue;
1113
Evan Cheng61560e22011-09-01 01:45:00 +00001114 unsigned RCId, RCCost;
1115 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +00001116 if (MO.isDef()) {
1117 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1118 if (CI != Cost.end())
1119 CI->second += RCCost;
1120 else
1121 Cost.insert(std::make_pair(RCId, RCCost));
1122 } else if (isOperandKill(MO, MRI)) {
1123 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1124 if (CI != Cost.end())
1125 CI->second -= RCCost;
1126 else
1127 Cost.insert(std::make_pair(RCId, -RCCost));
1128 }
1129 }
1130
1131 // Update register pressure of blocks from loop header to current block.
1132 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1133 SmallVector<unsigned, 8> &RP = BackTrace[i];
1134 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1135 CI != CE; ++CI) {
1136 unsigned RCId = CI->first;
1137 RP[RCId] += CI->second;
1138 }
1139 }
1140}
1141
Evan Cheng45e94d62009-02-04 09:19:56 +00001142/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1143/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +00001144bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +00001145 if (MI.isImplicitDef())
1146 return true;
1147
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001148 // Besides removing computation from the loop, hoisting an instruction has
1149 // these effects:
1150 //
1151 // - The value defined by the instruction becomes live across the entire
1152 // loop. This increases register pressure in the loop.
1153 //
1154 // - If the value is used by a PHI in the loop, a copy will be required for
1155 // lowering the PHI after extending the live range.
1156 //
1157 // - When hoisting the last use of a value in the loop, that value no longer
1158 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng61560e22011-09-01 01:45:00 +00001159
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001160 bool CheapInstr = IsCheapInstruction(MI);
1161 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001162
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001163 // Don't hoist a cheap instruction if it would create a copy in the loop.
1164 if (CheapInstr && CreatesCopy) {
1165 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1166 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001167 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001168
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001169 // Rematerializable instructions should always be hoisted since the register
1170 // allocator can just pull them down again when needed.
1171 if (TII->isTriviallyReMaterializable(&MI, AA))
1172 return true;
1173
1174 // Estimate register pressure to determine whether to LICM the instruction.
1175 // In low register pressure situation, we can be more aggressive about
1176 // hoisting. Also, favors hoisting long latency instructions even in
1177 // moderately high pressure situation.
1178 // Cheap instructions will only be hoisted if they don't increase register
1179 // pressure at all.
1180 // FIXME: If there are long latency loop-invariant instructions inside the
1181 // loop at this point, why didn't the optimizer's LICM hoist them?
1182 DenseMap<unsigned, int> Cost;
1183 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1184 const MachineOperand &MO = MI.getOperand(i);
1185 if (!MO.isReg() || MO.isImplicit())
1186 continue;
1187 unsigned Reg = MO.getReg();
1188 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1189 continue;
1190
1191 unsigned RCId, RCCost;
1192 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1193 if (MO.isDef()) {
1194 if (HasHighOperandLatency(MI, i, Reg)) {
1195 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1196 ++NumHighLatency;
1197 return true;
1198 }
1199 Cost[RCId] += RCCost;
1200 } else if (isOperandKill(MO, MRI)) {
1201 // Is a virtual register use is a kill, hoisting it out of the loop
1202 // may actually reduce register pressure or be register pressure
1203 // neutral.
1204 Cost[RCId] -= RCCost;
1205 }
1206 }
1207
1208 // Visit BBs from header to current BB, if hoisting this doesn't cause
1209 // high register pressure, then it's safe to proceed.
1210 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1211 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1212 ++NumLowRP;
1213 return true;
1214 }
1215
1216 // Don't risk increasing register pressure if it would create copies.
1217 if (CreatesCopy) {
1218 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001219 return false;
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001220 }
1221
1222 // Do not "speculate" in high register pressure situation. If an
1223 // instruction is not guaranteed to be executed in the loop, it's best to be
1224 // conservative.
1225 if (AvoidSpeculation &&
1226 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1227 DEBUG(dbgs() << "Won't speculate: " << MI);
1228 return false;
1229 }
1230
1231 // High register pressure situation, only hoist if the instruction is going
1232 // to be remat'ed.
1233 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1234 !MI.isInvariantLoad(AA)) {
1235 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1236 return false;
1237 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001238
1239 return true;
1240}
1241
Dan Gohman5c952302009-10-29 17:47:20 +00001242MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001243 // Don't unfold simple loads.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001244 if (MI->canFoldAsLoad())
Evan Chenge95f3192010-10-08 18:59:19 +00001245 return 0;
1246
Dan Gohman5c952302009-10-29 17:47:20 +00001247 // If not, we may be able to unfold a load and hoist that.
1248 // First test whether the instruction is loading from an amenable
1249 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001250 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001251 return 0;
1252
Dan Gohman5c952302009-10-29 17:47:20 +00001253 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001254 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001255 unsigned NewOpc =
1256 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1257 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001258 /*UnfoldStore=*/false,
1259 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001260 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001261 const MCInstrDesc &MID = TII->get(NewOpc);
1262 if (MID.getNumDefs() != 1) return 0;
1263 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001264 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001265 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001266
1267 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001268 SmallVector<MachineInstr *, 2> NewMIs;
1269 bool Success =
1270 TII->unfoldMemoryOperand(MF, MI, Reg,
1271 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1272 NewMIs);
1273 (void)Success;
1274 assert(Success &&
1275 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1276 "succeeded!");
1277 assert(NewMIs.size() == 2 &&
1278 "Unfolded a load into multiple instructions!");
1279 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001280 MachineBasicBlock::iterator Pos = MI;
1281 MBB->insert(Pos, NewMIs[0]);
1282 MBB->insert(Pos, NewMIs[1]);
Dan Gohman5c952302009-10-29 17:47:20 +00001283 // If unfolding produced a load that wasn't loop-invariant or profitable to
1284 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001285 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001286 NewMIs[0]->eraseFromParent();
1287 NewMIs[1]->eraseFromParent();
1288 return 0;
1289 }
Evan Cheng134982d2010-10-20 22:03:58 +00001290
1291 // Update register pressure for the unfolded instruction.
1292 UpdateRegPressure(NewMIs[1]);
1293
Dan Gohman5c952302009-10-29 17:47:20 +00001294 // Otherwise we successfully unfolded a load that we can hoist.
1295 MI->eraseFromParent();
1296 return NewMIs[0];
1297}
1298
Evan Cheng777c6b72009-11-03 21:40:02 +00001299void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1300 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1301 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001302 unsigned Opcode = MI->getOpcode();
1303 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1304 CI = CSEMap.find(Opcode);
1305 if (CI != CSEMap.end())
1306 CI->second.push_back(MI);
1307 else {
1308 std::vector<const MachineInstr*> CSEMIs;
1309 CSEMIs.push_back(MI);
1310 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001311 }
1312 }
1313}
1314
Evan Cheng78e5c112009-11-07 03:52:02 +00001315const MachineInstr*
1316MachineLICM::LookForDuplicate(const MachineInstr *MI,
1317 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001318 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1319 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001320 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001321 return PrevMI;
1322 }
1323 return 0;
1324}
1325
1326bool MachineLICM::EliminateCSE(MachineInstr *MI,
1327 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001328 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1329 // the undef property onto uses.
1330 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001331 return false;
1332
1333 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001334 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001335
1336 // Replace virtual registers defined by MI by their counterparts defined
1337 // by Dup.
Evan Cheng1025cce2011-10-17 19:50:12 +00001338 SmallVector<unsigned, 2> Defs;
Evan Cheng78e5c112009-11-07 03:52:02 +00001339 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1340 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001341
1342 // Physical registers may not differ here.
1343 assert((!MO.isReg() || MO.getReg() == 0 ||
1344 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1345 MO.getReg() == Dup->getOperand(i).getReg()) &&
1346 "Instructions with different phys regs are not identical!");
1347
1348 if (MO.isReg() && MO.isDef() &&
Evan Cheng1025cce2011-10-17 19:50:12 +00001349 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1350 Defs.push_back(i);
1351 }
1352
1353 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1354 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1355 unsigned Idx = Defs[i];
1356 unsigned Reg = MI->getOperand(Idx).getReg();
1357 unsigned DupReg = Dup->getOperand(Idx).getReg();
1358 OrigRCs.push_back(MRI->getRegClass(DupReg));
1359
1360 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1361 // Restore old RCs if more than one defs.
1362 for (unsigned j = 0; j != i; ++j)
1363 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1364 return false;
Dan Gohmane6cd7572010-05-13 20:34:42 +00001365 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001366 }
Evan Cheng1025cce2011-10-17 19:50:12 +00001367
1368 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1369 unsigned Idx = Defs[i];
1370 unsigned Reg = MI->getOperand(Idx).getReg();
1371 unsigned DupReg = Dup->getOperand(Idx).getReg();
1372 MRI->replaceRegWith(Reg, DupReg);
1373 MRI->clearKillFlags(DupReg);
1374 }
1375
Evan Cheng78e5c112009-11-07 03:52:02 +00001376 MI->eraseFromParent();
1377 ++NumCSEed;
1378 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001379 }
1380 return false;
1381}
1382
Evan Cheng7efba852011-10-12 00:09:14 +00001383/// MayCSE - Return true if the given instruction will be CSE'd if it's
1384/// hoisted out of the loop.
1385bool MachineLICM::MayCSE(MachineInstr *MI) {
1386 unsigned Opcode = MI->getOpcode();
1387 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1388 CI = CSEMap.find(Opcode);
1389 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1390 // the undef property onto uses.
1391 if (CI == CSEMap.end() || MI->isImplicitDef())
1392 return false;
1393
1394 return LookForDuplicate(MI, CI->second) != 0;
1395}
1396
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001397/// Hoist - When an instruction is found to use only loop invariant operands
1398/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001399///
Evan Cheng134982d2010-10-20 22:03:58 +00001400bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001401 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001402 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001403 // If not, try unfolding a hoistable load.
1404 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001405 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001406 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001407
Dan Gohmanc475c362009-01-15 22:01:38 +00001408 // Now move the instructions to the predecessor, inserting it before any
1409 // terminator instructions.
1410 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001411 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001412 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001413 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001414 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001415 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001416 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001417 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001418 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001419 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001420
Evan Cheng777c6b72009-11-03 21:40:02 +00001421 // If this is the first instruction being hoisted to the preheader,
1422 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001423 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001424 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001425 FirstInLoop = false;
1426 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001427
Evan Chengaf6949d2009-02-05 08:45:46 +00001428 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001429 unsigned Opcode = MI->getOpcode();
1430 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1431 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001432 if (!EliminateCSE(MI, CI)) {
1433 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001434 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001435
Evan Cheng134982d2010-10-20 22:03:58 +00001436 // Update register pressure for BBs from header to this block.
1437 UpdateBackTraceRegPressure(MI);
1438
Dan Gohmane6cd7572010-05-13 20:34:42 +00001439 // Clear the kill flags of any register this instruction defines,
1440 // since they may need to be live throughout the entire loop
1441 // rather than just live for part of it.
1442 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1443 MachineOperand &MO = MI->getOperand(i);
1444 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001445 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001446 }
1447
Evan Chengaf6949d2009-02-05 08:45:46 +00001448 // Add to the CSE map.
1449 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001450 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001451 else {
1452 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001453 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001454 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001455 }
1456 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001457
Dan Gohmanc475c362009-01-15 22:01:38 +00001458 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001459 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001460
1461 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001462}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001463
1464MachineBasicBlock *MachineLICM::getCurPreheader() {
1465 // Determine the block to which to hoist instructions. If we can't find a
1466 // suitable loop predecessor, we can't do any hoisting.
1467
1468 // If we've tried to get a preheader and failed, don't try again.
1469 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1470 return 0;
1471
1472 if (!CurPreheader) {
1473 CurPreheader = CurLoop->getLoopPreheader();
1474 if (!CurPreheader) {
1475 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1476 if (!Pred) {
1477 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1478 return 0;
1479 }
1480
1481 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1482 if (!CurPreheader) {
1483 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1484 return 0;
1485 }
1486 }
1487 }
1488 return CurPreheader;
1489}