blob: a55b3e652d9b67603f0f8a49a1e75e9453f6032e [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 Cheng0e673912010-10-14 01:16:09 +000031#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000032#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000033#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng0e673912010-10-14 01:16:09 +000034#include "llvm/Target/TargetInstrItineraries.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 Cheng0e673912010-10-14 01:16:09 +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 +000043
44using namespace llvm;
45
Evan Cheng0e673912010-10-14 01:16:09 +000046static cl::opt<bool>
47TrackRegPressure("rp-aware-machine-licm",
48 cl::desc("Register pressure aware machine LICM"),
49 cl::init(false), cl::Hidden);
50
Bill Wendling041b3f82007-12-08 23:58:46 +000051STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000052STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000053STATISTIC(NumPostRAHoisted,
54 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000055
Bill Wendling0f940c92007-12-07 21:42:31 +000056namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000057 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000058 bool PreRegAlloc;
59
Bill Wendling9258cd32008-01-02 19:32:43 +000060 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000061 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000062 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000063 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000064 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000065 MachineRegisterInfo *MRI;
66 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000067
Bill Wendling0f940c92007-12-07 21:42:31 +000068 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000069 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000070 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000071 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000074 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000075 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000076 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000077 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000078
Evan Chengd94671a2010-04-07 00:41:17 +000079 BitVector AllocatableSet;
80
Evan Cheng0e673912010-10-14 01:16:09 +000081 // Track 'estimated' register pressure.
82 SmallVector<unsigned, 8> RegPressure;
83 SmallVector<unsigned, 8> RegLimit;
84
Dale Johannesenc46a5f22010-07-29 17:45:24 +000085 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000086 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000087
Bill Wendling0f940c92007-12-07 21:42:31 +000088 public:
89 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000090 MachineLICM() :
Owen Anderson90c579d2010-08-06 18:33:48 +000091 MachineFunctionPass(ID), PreRegAlloc(true) {}
Evan Chengd94671a2010-04-07 00:41:17 +000092
93 explicit MachineLICM(bool PreRA) :
Owen Anderson90c579d2010-08-06 18:33:48 +000094 MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000095
96 virtual bool runOnMachineFunction(MachineFunction &MF);
97
Dan Gohman72241702008-12-18 01:37:56 +000098 const char *getPassName() const { return "Machine Instruction LICM"; }
99
Bill Wendling0f940c92007-12-07 21:42:31 +0000100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesCFG();
102 AU.addRequired<MachineLoopInfo>();
103 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000104 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000105 AU.addPreserved<MachineLoopInfo>();
106 AU.addPreserved<MachineDominatorTree>();
107 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000108 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000109
110 virtual void releaseMemory() {
Evan Cheng0e673912010-10-14 01:16:09 +0000111 RegPressure.clear();
112 RegLimit.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000113 CSEMap.clear();
114 }
115
Bill Wendling0f940c92007-12-07 21:42:31 +0000116 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000117 /// CandidateInfo - Keep track of information about hoisting candidates.
118 struct CandidateInfo {
119 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000120 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000121 int FI;
122 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
123 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000124 };
125
126 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
127 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000128 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000129
130 /// HoistPostRA - When an instruction is found to only use loop invariant
131 /// operands that is safe to hoist, this instruction is called to do the
132 /// dirty work.
133 void HoistPostRA(MachineInstr *MI, unsigned Def);
134
135 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
136 /// gather register def and frame object update information.
137 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
138 SmallSet<int, 32> &StoredFIs,
139 SmallVector<CandidateInfo, 32> &Candidates);
140
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000141 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
142 /// current loop.
143 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000144
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000145 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000146 /// candidate for LICM. e.g. If the instruction is a call, then it's
147 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000148 bool IsLICMCandidate(MachineInstr &I);
149
Bill Wendling041b3f82007-12-08 23:58:46 +0000150 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000151 /// invariant. I.e., all virtual register operands are defined outside of
152 /// the loop, physical registers aren't accessed (explicitly or implicitly),
153 /// and the instruction is hoistable.
154 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000155 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000156
Evan Cheng0e673912010-10-14 01:16:09 +0000157 /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
158 /// and an use in the current loop.
159 int ComputeOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
160
Evan Cheng45e94d62009-02-04 09:19:56 +0000161 /// IsProfitableToHoist - Return true if it is potentially profitable to
162 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000163 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000164
Bill Wendling0f940c92007-12-07 21:42:31 +0000165 /// HoistRegion - Walk the specified region of the CFG (defined by all
166 /// blocks dominated by the specified block, and that are in the current
167 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
168 /// visit definitions before uses, allowing us to hoist a loop body in one
169 /// pass without iteration.
170 ///
171 void HoistRegion(MachineDomTreeNode *N);
172
Evan Cheng0e673912010-10-14 01:16:09 +0000173 /// InitRegPressure - Find all virtual register references that are livein
174 /// to the block to initialize the starting "register pressure". Note this
175 /// does not count live through (livein but not used) registers.
176 void InitRegPressure(MachineBasicBlock *BB);
177
178 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
179 /// register pressure before and after executing a specifi instruction.
180 void UpdateRegPressureBefore(const MachineInstr *MI);
181 void UpdateRegPressureAfter(const MachineInstr *MI);
182
Evan Cheng87b75ba2009-11-20 19:55:37 +0000183 /// isLoadFromConstantMemory - Return true if the given instruction is a
184 /// load from constant memory.
185 bool isLoadFromConstantMemory(MachineInstr *MI);
186
Dan Gohman5c952302009-10-29 17:47:20 +0000187 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
188 /// the load itself could be hoisted. Return the unfolded and hoistable
189 /// load, or null if the load couldn't be unfolded or if it wouldn't
190 /// be hoistable.
191 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
192
Evan Cheng78e5c112009-11-07 03:52:02 +0000193 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
194 /// duplicate of MI. Return this instruction if it's found.
195 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
196 std::vector<const MachineInstr*> &PrevMIs);
197
Evan Cheng9fb744e2009-11-05 00:51:13 +0000198 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
199 /// the preheader that compute the same value. If it's found, do a RAU on
200 /// with the definition of the existing instruction rather than hoisting
201 /// the instruction to the preheader.
202 bool EliminateCSE(MachineInstr *MI,
203 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
204
Bill Wendling0f940c92007-12-07 21:42:31 +0000205 /// Hoist - When an instruction is found to only use loop invariant operands
206 /// that is safe to hoist, this instruction is called to do the dirty work.
207 ///
Evan Cheng0e673912010-10-14 01:16:09 +0000208 void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000209
210 /// InitCSEMap - Initialize the CSE map with instructions that are in the
211 /// current loop preheader that may become duplicates of instructions that
212 /// are hoisted out of the loop.
213 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000214
215 /// getCurPreheader - Get the preheader for the current loop, splitting
216 /// a critical edge if needed.
217 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000218 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000219} // end anonymous namespace
220
Dan Gohman844731a2008-05-13 00:00:25 +0000221char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000222INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
223 "Machine Loop Invariant Code Motion", false, false)
224INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
225INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
226INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
227INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000228 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000229
Evan Chengd94671a2010-04-07 00:41:17 +0000230FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
231 return new MachineLICM(PreRegAlloc);
232}
Bill Wendling0f940c92007-12-07 21:42:31 +0000233
Dan Gohman853d3fb2010-06-22 17:25:57 +0000234/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
235/// loop that has a unique predecessor.
236static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000237 // Check whether this loop even has a unique predecessor.
238 if (!CurLoop->getLoopPredecessor())
239 return false;
240 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000241 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000242 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000243 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000244 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000245 return true;
246}
247
Bill Wendling0f940c92007-12-07 21:42:31 +0000248bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000249 if (PreRegAlloc)
250 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
251 else
252 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000253
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000254 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000255 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000256 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000257 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000258 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000259 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000260 MRI = &MF.getRegInfo();
261 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000262 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000263
Evan Cheng0e673912010-10-14 01:16:09 +0000264 if (PreRegAlloc) {
265 // Estimate register pressure during pre-regalloc pass.
266 unsigned NumRC = TRI->getNumRegClasses();
267 RegPressure.resize(NumRC);
268 RegLimit.resize(NumRC);
269 std::fill(RegPressure.begin(), RegPressure.end(), 0);
270 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
271 E = TRI->regclass_end(); I != E; ++I)
272 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
273 }
274
Bill Wendling0f940c92007-12-07 21:42:31 +0000275 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000276 MLI = &getAnalysis<MachineLoopInfo>();
277 DT = &getAnalysis<MachineDominatorTree>();
278 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000279
Dan Gohmanaa742602010-07-09 18:49:45 +0000280 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
281 while (!Worklist.empty()) {
282 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000283 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000284
Evan Cheng4038f9c2010-04-08 01:03:47 +0000285 // If this is done before regalloc, only visit outer-most preheader-sporting
286 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000287 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
288 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000289 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000290 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000291
Evan Chengd94671a2010-04-07 00:41:17 +0000292 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000293 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000294 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000295 // CSEMap is initialized for loop header when the first instruction is
296 // being hoisted.
297 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000298 FirstInLoop = true;
Evan Chengd94671a2010-04-07 00:41:17 +0000299 HoistRegion(N);
300 CSEMap.clear();
301 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000302 }
303
304 return Changed;
305}
306
Evan Cheng4038f9c2010-04-08 01:03:47 +0000307/// InstructionStoresToFI - Return true if instruction stores to the
308/// specified frame.
309static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
310 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
311 oe = MI->memoperands_end(); o != oe; ++o) {
312 if (!(*o)->isStore() || !(*o)->getValue())
313 continue;
314 if (const FixedStackPseudoSourceValue *Value =
315 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
316 if (Value->getFrameIndex() == FI)
317 return true;
318 }
319 }
320 return false;
321}
322
323/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
324/// gather register def and frame object update information.
325void MachineLICM::ProcessMI(MachineInstr *MI,
326 unsigned *PhysRegDefs,
327 SmallSet<int, 32> &StoredFIs,
328 SmallVector<CandidateInfo, 32> &Candidates) {
329 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000330 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000331 unsigned Def = 0;
332 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
333 const MachineOperand &MO = MI->getOperand(i);
334 if (MO.isFI()) {
335 // Remember if the instruction stores to the frame index.
336 int FI = MO.getIndex();
337 if (!StoredFIs.count(FI) &&
338 MFI->isSpillSlotObjectIndex(FI) &&
339 InstructionStoresToFI(MI, FI))
340 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000341 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000342 continue;
343 }
344
345 if (!MO.isReg())
346 continue;
347 unsigned Reg = MO.getReg();
348 if (!Reg)
349 continue;
350 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
351 "Not expecting virtual register!");
352
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000353 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000354 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000355 // If it's using a non-loop-invariant register, then it's obviously not
356 // safe to hoist.
357 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000358 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000359 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000360
361 if (MO.isImplicit()) {
362 ++PhysRegDefs[Reg];
363 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
364 ++PhysRegDefs[*AS];
365 if (!MO.isDead())
366 // Non-dead implicit def? This cannot be hoisted.
367 RuledOut = true;
368 // No need to check if a dead implicit def is also defined by
369 // another instruction.
370 continue;
371 }
372
373 // FIXME: For now, avoid instructions with multiple defs, unless
374 // it's a dead implicit def.
375 if (Def)
376 RuledOut = true;
377 else
378 Def = Reg;
379
380 // If we have already seen another instruction that defines the same
381 // register, then this is not safe.
382 if (++PhysRegDefs[Reg] > 1)
383 // MI defined register is seen defined by another instruction in
384 // the loop, it cannot be a LICM candidate.
385 RuledOut = true;
386 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
387 if (++PhysRegDefs[*AS] > 1)
388 RuledOut = true;
389 }
390
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000391 // Only consider reloads for now and remats which do not have register
392 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000393 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000394 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000395 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000396 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
397 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000398 }
399}
400
401/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
402/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000403void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000404 unsigned NumRegs = TRI->getNumRegs();
405 unsigned *PhysRegDefs = new unsigned[NumRegs];
406 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
407
Evan Cheng4038f9c2010-04-08 01:03:47 +0000408 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000409 SmallSet<int, 32> StoredFIs;
410
411 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000412 // collect potential LICM candidates.
413 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
414 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
415 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000416 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000417 // FIXME: That means a reload that're reused in successor block(s) will not
418 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000419 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000420 E = BB->livein_end(); I != E; ++I) {
421 unsigned Reg = *I;
422 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000423 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
424 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000425 }
426
427 for (MachineBasicBlock::iterator
428 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000429 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000430 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000431 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000432 }
Evan Chengd94671a2010-04-07 00:41:17 +0000433
434 // Now evaluate whether the potential candidates qualify.
435 // 1. Check if the candidate defined register is defined by another
436 // instruction in the loop.
437 // 2. If the candidate is a load from stack slot (always true for now),
438 // check if the slot is stored anywhere in the loop.
439 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000440 if (Candidates[i].FI != INT_MIN &&
441 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000442 continue;
443
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000444 if (PhysRegDefs[Candidates[i].Def] == 1) {
445 bool Safe = true;
446 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000447 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
448 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000449 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000450 continue;
451 if (PhysRegDefs[MO.getReg()]) {
452 // If it's using a non-loop-invariant register, then it's obviously
453 // not safe to hoist.
454 Safe = false;
455 break;
456 }
457 }
458 if (Safe)
459 HoistPostRA(MI, Candidates[i].Def);
460 }
Evan Chengd94671a2010-04-07 00:41:17 +0000461 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000462
463 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000464}
465
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000466/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
467/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000468void MachineLICM::AddToLiveIns(unsigned Reg) {
469 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000470 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
471 MachineBasicBlock *BB = Blocks[i];
472 if (!BB->isLiveIn(Reg))
473 BB->addLiveIn(Reg);
474 for (MachineBasicBlock::iterator
475 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
476 MachineInstr *MI = &*MII;
477 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
478 MachineOperand &MO = MI->getOperand(i);
479 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
480 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
481 MO.setIsKill(false);
482 }
483 }
484 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000485}
486
487/// HoistPostRA - When an instruction is found to only use loop invariant
488/// operands that is safe to hoist, this instruction is called to do the
489/// dirty work.
490void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000491 MachineBasicBlock *Preheader = getCurPreheader();
492 if (!Preheader) return;
493
Evan Chengd94671a2010-04-07 00:41:17 +0000494 // Now move the instructions to the predecessor, inserting it before any
495 // terminator instructions.
496 DEBUG({
497 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000498 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000499 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000500 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000501 if (MI->getParent()->getBasicBlock())
502 dbgs() << " from MachineBasicBlock "
503 << MI->getParent()->getName();
504 dbgs() << "\n";
505 });
506
507 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000508 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000509 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000510
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000511 // Add register to livein list to all the BBs in the current loop since a
512 // loop invariant must be kept live throughout the whole loop. This is
513 // important to ensure later passes do not scavenge the def register.
514 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000515
516 ++NumPostRAHoisted;
517 Changed = true;
518}
519
Bill Wendling0f940c92007-12-07 21:42:31 +0000520/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
521/// dominated by the specified block, and that are in the current loop) in depth
522/// first order w.r.t the DominatorTree. This allows us to visit definitions
523/// before uses, allowing us to hoist a loop body in one pass without iteration.
524///
525void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
526 assert(N != 0 && "Null dominator tree node?");
527 MachineBasicBlock *BB = N->getBlock();
528
529 // If this subregion is not in the top level loop at all, exit.
530 if (!CurLoop->contains(BB)) return;
531
Evan Cheng0e673912010-10-14 01:16:09 +0000532 MachineBasicBlock *Preheader = getCurPreheader();
533 if (Preheader) {
534 if (TrackRegPressure)
535 InitRegPressure(BB);
536
537 for (MachineBasicBlock::iterator
538 MII = BB->begin(), E = BB->end(); MII != E; ) {
539 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
540 MachineInstr *MI = &*MII;
541
542 if (TrackRegPressure)
543 UpdateRegPressureBefore(MI);
544 Hoist(MI, Preheader);
545 if (TrackRegPressure)
546 UpdateRegPressureAfter(MI);
547
548 MII = NextMII;
549 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000550 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000551
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000552 // Don't hoist things out of a large switch statement. This often causes
553 // code to be hoisted that wasn't going to be executed, and increases
554 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000555 if (BB->succ_size() < 25) {
556 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000557 for (unsigned I = 0, E = Children.size(); I != E; ++I)
558 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000559 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000560}
561
Evan Cheng0e673912010-10-14 01:16:09 +0000562/// InitRegPressure - Find all virtual register references that are livein to
563/// the block to initialize the starting "register pressure". Note this does
564/// not count live through (livein but not used) registers.
565void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
566 SmallSet<unsigned, 16> Seen;
567
568 std::fill(RegPressure.begin(), RegPressure.end(), 0);
569 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
570 MII != E; ++MII) {
571 MachineInstr *MI = &*MII;
572 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
573 const MachineOperand &MO = MI->getOperand(i);
574 if (!MO.isReg() || MO.isImplicit())
575 continue;
576 unsigned Reg = MO.getReg();
577 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
578 continue;
579 if (!Seen.insert(Reg))
580 continue;
581
582 // Must be a livein.
583 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
584 EVT VT = *RC->vt_begin();
585 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
586 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
587 }
588 }
589}
590
591/// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
592/// register pressure before and after executing a specifi instruction.
593void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI) {
594 if (MI->isImplicitDef() || MI->isPHI())
595 return;
596
597 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
598 const MachineOperand &MO = MI->getOperand(i);
599 if (!MO.isReg() || MO.isImplicit() || !MO.isUse() || !MO.isKill())
600 continue;
601 unsigned Reg = MO.getReg();
602 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
603 continue;
604
605 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
606 EVT VT = *RC->vt_begin();
607 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
608 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
609
610 assert(RCCost <= RegPressure[RCId]);
611 RegPressure[RCId] -= RCCost;
612 }
613}
614
615void MachineLICM::UpdateRegPressureAfter(const MachineInstr *MI) {
616 if (MI->isImplicitDef() || MI->isPHI())
617 return;
618
619 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
620 const MachineOperand &MO = MI->getOperand(i);
621 if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
622 continue;
623 unsigned Reg = MO.getReg();
624 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
625 continue;
626
627 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
628 EVT VT = *RC->vt_begin();
629 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
630 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
631 RegPressure[RCId] += RCCost;
632 }
633}
634
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000635/// IsLICMCandidate - Returns true if the instruction may be a suitable
636/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
637/// not safe to hoist it.
638bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000639 // Check if it's safe to move the instruction.
640 bool DontMoveAcrossStore = true;
641 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000642 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000643
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000644 return true;
645}
646
647/// IsLoopInvariantInst - Returns true if the instruction is loop
648/// invariant. I.e., all virtual register operands are defined outside of the
649/// loop, physical registers aren't accessed explicitly, and there are no side
650/// effects that aren't captured by the operands or other flags.
651///
652bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
653 if (!IsLICMCandidate(I))
654 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000655
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000656 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000657 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
658 const MachineOperand &MO = I.getOperand(i);
659
Dan Gohmand735b802008-10-03 15:45:36 +0000660 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000661 continue;
662
Dan Gohmanc475c362009-01-15 22:01:38 +0000663 unsigned Reg = MO.getReg();
664 if (Reg == 0) continue;
665
666 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000667 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000668 if (MO.isUse()) {
669 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000670 // and we can freely move its uses. Alternatively, if it's allocatable,
671 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000672 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000673 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000674 if (AllocatableSet.test(Reg))
675 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000676 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000677 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
678 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000679 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000680 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000681 if (AllocatableSet.test(AliasReg))
682 return false;
683 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000684 // Otherwise it's safe to move.
685 continue;
686 } else if (!MO.isDead()) {
687 // A def that isn't dead. We can't move it.
688 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000689 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
690 // If the reg is live into the loop, we can't hoist an instruction
691 // which would clobber it.
692 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000693 }
694 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000695
696 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000697 continue;
698
Evan Cheng0e673912010-10-14 01:16:09 +0000699 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000700 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000701
702 // If the loop contains the definition of an operand, then the instruction
703 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000704 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000705 return false;
706 }
707
708 // If we got this far, the instruction is loop invariant!
709 return true;
710}
711
Evan Chengaf6949d2009-02-05 08:45:46 +0000712
713/// HasPHIUses - Return true if the specified register has any PHI use.
Evan Cheng0e673912010-10-14 01:16:09 +0000714static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
715 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
716 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000717 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000718 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000719 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000720 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000721 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000722}
723
Evan Cheng87b75ba2009-11-20 19:55:37 +0000724/// isLoadFromConstantMemory - Return true if the given instruction is a
725/// load from constant memory. Machine LICM will hoist these even if they are
726/// not re-materializable.
727bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
728 if (!MI->getDesc().mayLoad()) return false;
729 if (!MI->hasOneMemOperand()) return false;
730 MachineMemOperand *MMO = *MI->memoperands_begin();
731 if (MMO->isVolatile()) return false;
732 if (!MMO->getValue()) return false;
733 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
734 if (PSV) {
735 MachineFunction &MF = *MI->getParent()->getParent();
736 return PSV->isConstant(MF.getFrameInfo());
737 } else {
738 return AA->pointsToConstantMemory(MMO->getValue());
739 }
740}
741
Evan Cheng0e673912010-10-14 01:16:09 +0000742/// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
743/// and an use in the current loop.
744int MachineLICM::ComputeOperandLatency(MachineInstr &MI,
745 unsigned DefIdx, unsigned Reg) {
746 if (MRI->use_nodbg_empty(Reg))
747 // No use? Return arbitrary large number!
748 return 300;
749
750 int Latency = -1;
751 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
752 E = MRI->use_nodbg_end(); I != E; ++I) {
753 MachineInstr *UseMI = &*I;
754 if (!CurLoop->contains(UseMI->getParent()))
755 continue;
756 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
757 const MachineOperand &MO = UseMI->getOperand(i);
758 if (!MO.isReg() || !MO.isUse())
759 continue;
760 unsigned MOReg = MO.getReg();
761 if (MOReg != Reg)
762 continue;
763
764 int UseCycle = TII->getOperandLatency(InstrItins, &MI, DefIdx, UseMI, i);
765 Latency = std::max(Latency, UseCycle);
766 }
767
768 if (Latency != -1)
769 break;
770 }
771
772 if (Latency == -1)
773 Latency = InstrItins->getOperandCycle(MI.getDesc().getSchedClass(), DefIdx);
774
775 return Latency;
776}
777
Evan Cheng45e94d62009-02-04 09:19:56 +0000778/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
779/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000780bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000781 if (MI.isImplicitDef())
782 return true;
783
Evan Cheng45e94d62009-02-04 09:19:56 +0000784 // FIXME: For now, only hoist re-materilizable instructions. LICM will
785 // increase register pressure. We want to make sure it doesn't increase
786 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000787 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
788 // these tend to help performance in low register pressure situation. The
789 // trade off is it may cause spill in high pressure situation. It will end up
790 // adding a store in the loop preheader. But the reload is no more expensive.
791 // The side benefit is these loads are frequently CSE'ed.
Evan Cheng0e673912010-10-14 01:16:09 +0000792 if (!TrackRegPressure || MI.getDesc().isAsCheapAsAMove()) {
793 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
794 !isLoadFromConstantMemory(&MI))
795 return false;
796 } else {
797 // In low register pressure situation, we can be more aggressive about
798 // hoisting. Also, favors hoisting long latency instructions even in
799 // moderately high pressure situation.
800 int Delta = 0;
801 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
802 const MachineOperand &MO = MI.getOperand(i);
803 if (!MO.isReg() || MO.isImplicit())
804 continue;
805 unsigned Reg = MO.getReg();
806 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
807 continue;
808 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
809 EVT VT = *RC->vt_begin();
810 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
811 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
812
813 if (MO.isUse()) {
814 if (RegPressure[RCId] >= RegLimit[RCId]) {
815 // Hoisting this instruction may actually reduce register pressure
816 // in the loop.
817 int Pressure = RegPressure[RCId] - RCCost;
818 assert(Pressure >= 0);
819 Delta -= (int)RegLimit[RCId] - Pressure;
820 }
821 } else {
822 if (InstrItins && !InstrItins->isEmpty()) {
823 int Cycle = ComputeOperandLatency(MI, i, Reg);
824 if (Cycle > 3)
825 // FIXME: Target specific high latency limit?
826 return true;
827 }
828 if (RegPressure[RCId] >= RegLimit[RCId])
829 Delta += RCCost;
830 else {
831 int Pressure = RegPressure[RCId] + RCCost;
832 if (Pressure > (int)RegLimit[RCId])
833 Delta += Pressure - RegLimit[RCId];
834 }
835 }
836 }
837
838 if (Delta >= 0)
839 return true;
840
841 // High register pressure situation, only hoist if the instruction is going to
842 // be remat'ed.
843 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
844 !isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000845 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000846 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000847
Evan Chengaf6949d2009-02-05 08:45:46 +0000848 // If result(s) of this instruction is used by PHIs, then don't hoist it.
849 // The presence of joins makes it difficult for current register allocator
850 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000851 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
852 const MachineOperand &MO = MI.getOperand(i);
853 if (!MO.isReg() || !MO.isDef())
854 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000855 if (HasPHIUses(MO.getReg(), MRI))
Evan Chengaf6949d2009-02-05 08:45:46 +0000856 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000857 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000858
859 return true;
860}
861
Dan Gohman5c952302009-10-29 17:47:20 +0000862MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +0000863 // Don't unfold simple loads.
864 if (MI->getDesc().canFoldAsLoad())
865 return 0;
866
Dan Gohman5c952302009-10-29 17:47:20 +0000867 // If not, we may be able to unfold a load and hoist that.
868 // First test whether the instruction is loading from an amenable
869 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000870 if (!isLoadFromConstantMemory(MI))
871 return 0;
872
Dan Gohman5c952302009-10-29 17:47:20 +0000873 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000874 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000875 unsigned NewOpc =
876 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
877 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000878 /*UnfoldStore=*/false,
879 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000880 if (NewOpc == 0) return 0;
881 const TargetInstrDesc &TID = TII->get(NewOpc);
882 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000883 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000884 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +0000885 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000886
887 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000888 SmallVector<MachineInstr *, 2> NewMIs;
889 bool Success =
890 TII->unfoldMemoryOperand(MF, MI, Reg,
891 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
892 NewMIs);
893 (void)Success;
894 assert(Success &&
895 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
896 "succeeded!");
897 assert(NewMIs.size() == 2 &&
898 "Unfolded a load into multiple instructions!");
899 MachineBasicBlock *MBB = MI->getParent();
900 MBB->insert(MI, NewMIs[0]);
901 MBB->insert(MI, NewMIs[1]);
902 // If unfolding produced a load that wasn't loop-invariant or profitable to
903 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000904 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000905 NewMIs[0]->eraseFromParent();
906 NewMIs[1]->eraseFromParent();
907 return 0;
908 }
909 // Otherwise we successfully unfolded a load that we can hoist.
910 MI->eraseFromParent();
911 return NewMIs[0];
912}
913
Evan Cheng777c6b72009-11-03 21:40:02 +0000914void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
915 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
916 const MachineInstr *MI = &*I;
917 // FIXME: For now, only hoist re-materilizable instructions. LICM will
918 // increase register pressure. We want to make sure it doesn't increase
919 // spilling.
920 if (TII->isTriviallyReMaterializable(MI, AA)) {
921 unsigned Opcode = MI->getOpcode();
922 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
923 CI = CSEMap.find(Opcode);
924 if (CI != CSEMap.end())
925 CI->second.push_back(MI);
926 else {
927 std::vector<const MachineInstr*> CSEMIs;
928 CSEMIs.push_back(MI);
929 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
930 }
931 }
932 }
933}
934
Evan Cheng78e5c112009-11-07 03:52:02 +0000935const MachineInstr*
936MachineLICM::LookForDuplicate(const MachineInstr *MI,
937 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000938 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
939 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000940 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000941 return PrevMI;
942 }
943 return 0;
944}
945
946bool MachineLICM::EliminateCSE(MachineInstr *MI,
947 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +0000948 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
949 // the undef property onto uses.
950 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +0000951 return false;
952
953 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000954 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000955
956 // Replace virtual registers defined by MI by their counterparts defined
957 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000958 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
959 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000960
961 // Physical registers may not differ here.
962 assert((!MO.isReg() || MO.getReg() == 0 ||
963 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
964 MO.getReg() == Dup->getOperand(i).getReg()) &&
965 "Instructions with different phys regs are not identical!");
966
967 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +0000968 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +0000969 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
970 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +0000971 }
Evan Cheng9fb744e2009-11-05 00:51:13 +0000972 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000973 MI->eraseFromParent();
974 ++NumCSEed;
975 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000976 }
977 return false;
978}
979
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000980/// Hoist - When an instruction is found to use only loop invariant operands
981/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000982///
Evan Cheng0e673912010-10-14 01:16:09 +0000983void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000984 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000985 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000986 // If not, try unfolding a hoistable load.
987 MI = ExtractHoistableLoad(MI);
988 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000989 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000990
Dan Gohmanc475c362009-01-15 22:01:38 +0000991 // Now move the instructions to the predecessor, inserting it before any
992 // terminator instructions.
993 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000994 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000995 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000996 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000997 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000998 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000999 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001000 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001001 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001002 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001003
Evan Cheng777c6b72009-11-03 21:40:02 +00001004 // If this is the first instruction being hoisted to the preheader,
1005 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001006 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001007 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001008 FirstInLoop = false;
1009 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001010
Evan Chengaf6949d2009-02-05 08:45:46 +00001011 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001012 unsigned Opcode = MI->getOpcode();
1013 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1014 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001015 if (!EliminateCSE(MI, CI)) {
1016 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001017 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001018
Dan Gohmane6cd7572010-05-13 20:34:42 +00001019 // Clear the kill flags of any register this instruction defines,
1020 // since they may need to be live throughout the entire loop
1021 // rather than just live for part of it.
1022 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1023 MachineOperand &MO = MI->getOperand(i);
1024 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001025 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001026 }
1027
Evan Chengaf6949d2009-02-05 08:45:46 +00001028 // Add to the CSE map.
1029 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001030 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001031 else {
1032 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001033 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001034 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001035 }
1036 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001037
Dan Gohmanc475c362009-01-15 22:01:38 +00001038 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001039 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001040}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001041
1042MachineBasicBlock *MachineLICM::getCurPreheader() {
1043 // Determine the block to which to hoist instructions. If we can't find a
1044 // suitable loop predecessor, we can't do any hoisting.
1045
1046 // If we've tried to get a preheader and failed, don't try again.
1047 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1048 return 0;
1049
1050 if (!CurPreheader) {
1051 CurPreheader = CurLoop->getLoopPreheader();
1052 if (!CurPreheader) {
1053 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1054 if (!Pred) {
1055 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1056 return 0;
1057 }
1058
1059 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1060 if (!CurPreheader) {
1061 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1062 return 0;
1063 }
1064 }
1065 }
1066 return CurPreheader;
1067}