blob: 443fc2d97bdf591464d26f1918250b9e75a7d464 [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"
Chris Lattnerac695822008-01-04 06:41:45 +000040#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000041#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000042
43using namespace llvm;
44
Evan Cheng03a9fdf2010-10-16 02:20:26 +000045STATISTIC(NumHoisted,
46 "Number of machine instructions hoisted out of loops");
47STATISTIC(NumLowRP,
48 "Number of instructions hoisted in low reg pressure situation");
49STATISTIC(NumHighLatency,
50 "Number of high latency instructions hoisted");
51STATISTIC(NumCSEed,
52 "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.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000082 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000083 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000084
85 // Register pressure "limit" per register class. If the pressure
86 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000087 SmallVector<unsigned, 8> RegLimit;
88
Evan Cheng03a9fdf2010-10-16 02:20:26 +000089 // Register pressure on path leading from loop preheader to current BB.
90 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
91
Dale Johannesenc46a5f22010-07-29 17:45:24 +000092 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000093 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000094
Bill Wendling0f940c92007-12-07 21:42:31 +000095 public:
96 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000097 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +000098 MachineFunctionPass(ID), PreRegAlloc(true) {
99 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
100 }
Evan Chengd94671a2010-04-07 00:41:17 +0000101
102 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000103 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
104 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
105 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000106
107 virtual bool runOnMachineFunction(MachineFunction &MF);
108
Dan Gohman72241702008-12-18 01:37:56 +0000109 const char *getPassName() const { return "Machine Instruction LICM"; }
110
Bill Wendling0f940c92007-12-07 21:42:31 +0000111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000112 AU.addRequired<MachineLoopInfo>();
113 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000114 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000115 AU.addPreserved<MachineLoopInfo>();
116 AU.addPreserved<MachineDominatorTree>();
117 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000118 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000119
120 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000121 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000122 RegPressure.clear();
123 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000124 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000125 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
126 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
127 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000128 CSEMap.clear();
129 }
130
Bill Wendling0f940c92007-12-07 21:42:31 +0000131 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000132 /// CandidateInfo - Keep track of information about hoisting candidates.
133 struct CandidateInfo {
134 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000135 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000136 int FI;
137 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
138 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000139 };
140
141 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
142 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000143 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000144
145 /// HoistPostRA - When an instruction is found to only use loop invariant
146 /// operands that is safe to hoist, this instruction is called to do the
147 /// dirty work.
148 void HoistPostRA(MachineInstr *MI, unsigned Def);
149
150 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
151 /// gather register def and frame object update information.
152 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
153 SmallSet<int, 32> &StoredFIs,
154 SmallVector<CandidateInfo, 32> &Candidates);
155
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000156 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
157 /// current loop.
158 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000159
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000160 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000161 /// candidate for LICM. e.g. If the instruction is a call, then it's
162 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000163 bool IsLICMCandidate(MachineInstr &I);
164
Bill Wendling041b3f82007-12-08 23:58:46 +0000165 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000166 /// invariant. I.e., all virtual register operands are defined outside of
167 /// the loop, physical registers aren't accessed (explicitly or implicitly),
168 /// and the instruction is hoistable.
169 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000170 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000171
Evan Cheng23128422010-10-19 18:58:51 +0000172 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
173 /// and an use in the current loop, return true if the target considered
174 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000175 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
176 unsigned Reg) const;
177
178 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000179
Evan Cheng134982d2010-10-20 22:03:58 +0000180 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
181 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000182 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000183 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
184
185 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
186 /// the current block and update their register pressures to reflect the
187 /// effect of hoisting MI from the current block to the preheader.
188 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000189
Evan Cheng45e94d62009-02-04 09:19:56 +0000190 /// IsProfitableToHoist - Return true if it is potentially profitable to
191 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000192 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000193
Bill Wendling0f940c92007-12-07 21:42:31 +0000194 /// HoistRegion - Walk the specified region of the CFG (defined by all
195 /// blocks dominated by the specified block, and that are in the current
196 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
197 /// visit definitions before uses, allowing us to hoist a loop body in one
198 /// pass without iteration.
199 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000200 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000201
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000202 /// InitRegPressure - Find all virtual register references that are liveout
203 /// of the preheader to initialize the starting "register pressure". Note
204 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000205 void InitRegPressure(MachineBasicBlock *BB);
206
Evan Cheng134982d2010-10-20 22:03:58 +0000207 /// UpdateRegPressure - Update estimate of register pressure after the
208 /// specified instruction.
209 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000210
Dan Gohman5c952302009-10-29 17:47:20 +0000211 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
212 /// the load itself could be hoisted. Return the unfolded and hoistable
213 /// load, or null if the load couldn't be unfolded or if it wouldn't
214 /// be hoistable.
215 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
216
Evan Cheng78e5c112009-11-07 03:52:02 +0000217 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
218 /// duplicate of MI. Return this instruction if it's found.
219 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
220 std::vector<const MachineInstr*> &PrevMIs);
221
Evan Cheng9fb744e2009-11-05 00:51:13 +0000222 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
223 /// the preheader that compute the same value. If it's found, do a RAU on
224 /// with the definition of the existing instruction rather than hoisting
225 /// the instruction to the preheader.
226 bool EliminateCSE(MachineInstr *MI,
227 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
228
Bill Wendling0f940c92007-12-07 21:42:31 +0000229 /// Hoist - When an instruction is found to only use loop invariant operands
230 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000231 /// It returns true if the instruction is hoisted.
232 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000233
234 /// InitCSEMap - Initialize the CSE map with instructions that are in the
235 /// current loop preheader that may become duplicates of instructions that
236 /// are hoisted out of the loop.
237 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000238
239 /// getCurPreheader - Get the preheader for the current loop, splitting
240 /// a critical edge if needed.
241 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000242 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000243} // end anonymous namespace
244
Dan Gohman844731a2008-05-13 00:00:25 +0000245char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000246INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
247 "Machine Loop Invariant Code Motion", false, false)
248INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
249INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
250INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
251INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000252 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000253
Evan Chengd94671a2010-04-07 00:41:17 +0000254FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
255 return new MachineLICM(PreRegAlloc);
256}
Bill Wendling0f940c92007-12-07 21:42:31 +0000257
Dan Gohman853d3fb2010-06-22 17:25:57 +0000258/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
259/// loop that has a unique predecessor.
260static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000261 // Check whether this loop even has a unique predecessor.
262 if (!CurLoop->getLoopPredecessor())
263 return false;
264 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000265 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000266 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000267 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000268 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000269 return true;
270}
271
Bill Wendling0f940c92007-12-07 21:42:31 +0000272bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000273 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000274 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000275 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000276 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
277 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000278
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000279 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000280 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000281 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000282 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000283 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000284 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000285 MRI = &MF.getRegInfo();
286 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000287 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000288
Evan Cheng0e673912010-10-14 01:16:09 +0000289 if (PreRegAlloc) {
290 // Estimate register pressure during pre-regalloc pass.
291 unsigned NumRC = TRI->getNumRegClasses();
292 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000293 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000294 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000295 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
296 E = TRI->regclass_end(); I != E; ++I)
297 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
298 }
299
Bill Wendling0f940c92007-12-07 21:42:31 +0000300 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000301 MLI = &getAnalysis<MachineLoopInfo>();
302 DT = &getAnalysis<MachineDominatorTree>();
303 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000304
Dan Gohmanaa742602010-07-09 18:49:45 +0000305 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
306 while (!Worklist.empty()) {
307 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000308 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000309
Evan Cheng4038f9c2010-04-08 01:03:47 +0000310 // If this is done before regalloc, only visit outer-most preheader-sporting
311 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000312 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
313 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000314 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000315 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000316
Evan Chengd94671a2010-04-07 00:41:17 +0000317 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000318 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000319 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000320 // CSEMap is initialized for loop header when the first instruction is
321 // being hoisted.
322 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000323 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000324 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000325 CSEMap.clear();
326 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000327 }
328
329 return Changed;
330}
331
Evan Cheng4038f9c2010-04-08 01:03:47 +0000332/// InstructionStoresToFI - Return true if instruction stores to the
333/// specified frame.
334static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
335 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
336 oe = MI->memoperands_end(); o != oe; ++o) {
337 if (!(*o)->isStore() || !(*o)->getValue())
338 continue;
339 if (const FixedStackPseudoSourceValue *Value =
340 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
341 if (Value->getFrameIndex() == FI)
342 return true;
343 }
344 }
345 return false;
346}
347
348/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
349/// gather register def and frame object update information.
350void MachineLICM::ProcessMI(MachineInstr *MI,
351 unsigned *PhysRegDefs,
352 SmallSet<int, 32> &StoredFIs,
353 SmallVector<CandidateInfo, 32> &Candidates) {
354 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000355 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000356 unsigned Def = 0;
357 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
358 const MachineOperand &MO = MI->getOperand(i);
359 if (MO.isFI()) {
360 // Remember if the instruction stores to the frame index.
361 int FI = MO.getIndex();
362 if (!StoredFIs.count(FI) &&
363 MFI->isSpillSlotObjectIndex(FI) &&
364 InstructionStoresToFI(MI, FI))
365 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000366 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000367 continue;
368 }
369
370 if (!MO.isReg())
371 continue;
372 unsigned Reg = MO.getReg();
373 if (!Reg)
374 continue;
375 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
376 "Not expecting virtual register!");
377
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000378 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000379 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000380 // If it's using a non-loop-invariant register, then it's obviously not
381 // safe to hoist.
382 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000383 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000384 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000385
386 if (MO.isImplicit()) {
387 ++PhysRegDefs[Reg];
388 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
389 ++PhysRegDefs[*AS];
390 if (!MO.isDead())
391 // Non-dead implicit def? This cannot be hoisted.
392 RuledOut = true;
393 // No need to check if a dead implicit def is also defined by
394 // another instruction.
395 continue;
396 }
397
398 // FIXME: For now, avoid instructions with multiple defs, unless
399 // it's a dead implicit def.
400 if (Def)
401 RuledOut = true;
402 else
403 Def = Reg;
404
405 // If we have already seen another instruction that defines the same
406 // register, then this is not safe.
407 if (++PhysRegDefs[Reg] > 1)
408 // MI defined register is seen defined by another instruction in
409 // the loop, it cannot be a LICM candidate.
410 RuledOut = true;
411 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
412 if (++PhysRegDefs[*AS] > 1)
413 RuledOut = true;
414 }
415
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000416 // Only consider reloads for now and remats which do not have register
417 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000418 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000419 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000420 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000421 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
422 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000423 }
424}
425
426/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
427/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000428void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000429 unsigned NumRegs = TRI->getNumRegs();
430 unsigned *PhysRegDefs = new unsigned[NumRegs];
431 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
432
Evan Cheng4038f9c2010-04-08 01:03:47 +0000433 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000434 SmallSet<int, 32> StoredFIs;
435
436 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000437 // collect potential LICM candidates.
438 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
439 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
440 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000441 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000442 // FIXME: That means a reload that're reused in successor block(s) will not
443 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000444 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000445 E = BB->livein_end(); I != E; ++I) {
446 unsigned Reg = *I;
447 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000448 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
449 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000450 }
451
452 for (MachineBasicBlock::iterator
453 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000454 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000455 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000456 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000457 }
Evan Chengd94671a2010-04-07 00:41:17 +0000458
459 // Now evaluate whether the potential candidates qualify.
460 // 1. Check if the candidate defined register is defined by another
461 // instruction in the loop.
462 // 2. If the candidate is a load from stack slot (always true for now),
463 // check if the slot is stored anywhere in the loop.
464 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000465 if (Candidates[i].FI != INT_MIN &&
466 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000467 continue;
468
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000469 if (PhysRegDefs[Candidates[i].Def] == 1) {
470 bool Safe = true;
471 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000472 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
473 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000474 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000475 continue;
476 if (PhysRegDefs[MO.getReg()]) {
477 // If it's using a non-loop-invariant register, then it's obviously
478 // not safe to hoist.
479 Safe = false;
480 break;
481 }
482 }
483 if (Safe)
484 HoistPostRA(MI, Candidates[i].Def);
485 }
Evan Chengd94671a2010-04-07 00:41:17 +0000486 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000487
488 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000489}
490
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000491/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
492/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000493void MachineLICM::AddToLiveIns(unsigned Reg) {
494 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000495 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
496 MachineBasicBlock *BB = Blocks[i];
497 if (!BB->isLiveIn(Reg))
498 BB->addLiveIn(Reg);
499 for (MachineBasicBlock::iterator
500 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
501 MachineInstr *MI = &*MII;
502 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = MI->getOperand(i);
504 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
505 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
506 MO.setIsKill(false);
507 }
508 }
509 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000510}
511
512/// HoistPostRA - When an instruction is found to only use loop invariant
513/// operands that is safe to hoist, this instruction is called to do the
514/// dirty work.
515void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000516 MachineBasicBlock *Preheader = getCurPreheader();
517 if (!Preheader) return;
518
Evan Chengd94671a2010-04-07 00:41:17 +0000519 // Now move the instructions to the predecessor, inserting it before any
520 // terminator instructions.
521 DEBUG({
522 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000523 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000524 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000525 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000526 if (MI->getParent()->getBasicBlock())
527 dbgs() << " from MachineBasicBlock "
528 << MI->getParent()->getName();
529 dbgs() << "\n";
530 });
531
532 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000533 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000534 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000535
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000536 // Add register to livein list to all the BBs in the current loop since a
537 // loop invariant must be kept live throughout the whole loop. This is
538 // important to ensure later passes do not scavenge the def register.
539 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000540
541 ++NumPostRAHoisted;
542 Changed = true;
543}
544
Bill Wendling0f940c92007-12-07 21:42:31 +0000545/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
546/// dominated by the specified block, and that are in the current loop) in depth
547/// first order w.r.t the DominatorTree. This allows us to visit definitions
548/// before uses, allowing us to hoist a loop body in one pass without iteration.
549///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000550void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000551 assert(N != 0 && "Null dominator tree node?");
552 MachineBasicBlock *BB = N->getBlock();
553
554 // If this subregion is not in the top level loop at all, exit.
555 if (!CurLoop->contains(BB)) return;
556
Evan Cheng0e673912010-10-14 01:16:09 +0000557 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000558 if (!Preheader)
559 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000560
Evan Cheng23128422010-10-19 18:58:51 +0000561 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000562 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000563 RegSeen.clear();
564 BackTrace.clear();
565 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000566 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000567
Evan Cheng23128422010-10-19 18:58:51 +0000568 // Remember livein register pressure.
569 BackTrace.push_back(RegPressure);
570
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000571 for (MachineBasicBlock::iterator
572 MII = BB->begin(), E = BB->end(); MII != E; ) {
573 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
574 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000575 if (!Hoist(MI, Preheader))
576 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000577 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000578 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000579
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000580 // Don't hoist things out of a large switch statement. This often causes
581 // code to be hoisted that wasn't going to be executed, and increases
582 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000583 if (BB->succ_size() < 25) {
584 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000585 for (unsigned I = 0, E = Children.size(); I != E; ++I)
586 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000587 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000588
Evan Cheng23128422010-10-19 18:58:51 +0000589 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000590}
591
Evan Cheng134982d2010-10-20 22:03:58 +0000592static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
593 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
594}
595
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000596/// InitRegPressure - Find all virtual register references that are liveout of
597/// the preheader to initialize the starting "register pressure". Note this
598/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000599void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000600 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000601
Evan Cheng134982d2010-10-20 22:03:58 +0000602 // If the preheader has only a single predecessor and it ends with a
603 // fallthrough or an unconditional branch, then scan its predecessor for live
604 // defs as well. This happens whenever the preheader is created by splitting
605 // the critical edge from the loop predecessor to the loop header.
606 if (BB->pred_size() == 1) {
607 MachineBasicBlock *TBB = 0, *FBB = 0;
608 SmallVector<MachineOperand, 4> Cond;
609 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
610 InitRegPressure(*BB->pred_begin());
611 }
612
Evan Cheng0e673912010-10-14 01:16:09 +0000613 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
614 MII != E; ++MII) {
615 MachineInstr *MI = &*MII;
616 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
617 const MachineOperand &MO = MI->getOperand(i);
618 if (!MO.isReg() || MO.isImplicit())
619 continue;
620 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000621 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000622 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000623
Andrew Trickdc986d22010-10-19 02:50:50 +0000624 bool isNew = RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000625 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
626 EVT VT = *RC->vt_begin();
627 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000628 if (MO.isDef())
629 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
630 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000631 bool isKill = isOperandKill(MO, MRI);
632 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000633 // Haven't seen this, it must be a livein.
634 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Evan Cheng134982d2010-10-20 22:03:58 +0000635 else if (!isNew && isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000636 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
637 }
Evan Cheng0e673912010-10-14 01:16:09 +0000638 }
639 }
640}
641
Evan Cheng134982d2010-10-20 22:03:58 +0000642/// UpdateRegPressure - Update estimate of register pressure after the
643/// specified instruction.
644void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
645 if (MI->isImplicitDef())
646 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000647
Evan Cheng134982d2010-10-20 22:03:58 +0000648 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000649 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
650 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000651 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000652 continue;
653 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000654 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000655 continue;
656
Andrew Trickdc986d22010-10-19 02:50:50 +0000657 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000658 if (MO.isDef())
659 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000660 else if (!isNew && isOperandKill(MO, MRI)) {
661 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
662 EVT VT = *RC->vt_begin();
663 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
664 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000665
Evan Cheng134982d2010-10-20 22:03:58 +0000666 if (RCCost > RegPressure[RCId])
667 RegPressure[RCId] = 0;
668 else
Evan Cheng23128422010-10-19 18:58:51 +0000669 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000670 }
Evan Cheng0e673912010-10-14 01:16:09 +0000671 }
Evan Cheng0e673912010-10-14 01:16:09 +0000672
Evan Cheng23128422010-10-19 18:58:51 +0000673 while (!Defs.empty()) {
674 unsigned Reg = Defs.pop_back_val();
Evan Cheng0e673912010-10-14 01:16:09 +0000675 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
676 EVT VT = *RC->vt_begin();
677 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
678 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
679 RegPressure[RCId] += RCCost;
680 }
681}
682
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000683/// IsLICMCandidate - Returns true if the instruction may be a suitable
684/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
685/// not safe to hoist it.
686bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000687 // Check if it's safe to move the instruction.
688 bool DontMoveAcrossStore = true;
689 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000690 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000691
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000692 return true;
693}
694
695/// IsLoopInvariantInst - Returns true if the instruction is loop
696/// invariant. I.e., all virtual register operands are defined outside of the
697/// loop, physical registers aren't accessed explicitly, and there are no side
698/// effects that aren't captured by the operands or other flags.
699///
700bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
701 if (!IsLICMCandidate(I))
702 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000703
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000704 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000705 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
706 const MachineOperand &MO = I.getOperand(i);
707
Dan Gohmand735b802008-10-03 15:45:36 +0000708 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000709 continue;
710
Dan Gohmanc475c362009-01-15 22:01:38 +0000711 unsigned Reg = MO.getReg();
712 if (Reg == 0) continue;
713
714 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000715 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000716 if (MO.isUse()) {
717 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000718 // and we can freely move its uses. Alternatively, if it's allocatable,
719 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000720 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000721 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000722 if (AllocatableSet.test(Reg))
723 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000724 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000725 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
726 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000727 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000728 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000729 if (AllocatableSet.test(AliasReg))
730 return false;
731 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000732 // Otherwise it's safe to move.
733 continue;
734 } else if (!MO.isDead()) {
735 // A def that isn't dead. We can't move it.
736 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000737 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
738 // If the reg is live into the loop, we can't hoist an instruction
739 // which would clobber it.
740 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000741 }
742 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000743
744 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000745 continue;
746
Evan Cheng0e673912010-10-14 01:16:09 +0000747 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000748 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000749
750 // If the loop contains the definition of an operand, then the instruction
751 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000752 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000753 return false;
754 }
755
756 // If we got this far, the instruction is loop invariant!
757 return true;
758}
759
Evan Chengaf6949d2009-02-05 08:45:46 +0000760
761/// HasPHIUses - Return true if the specified register has any PHI use.
Evan Cheng0e673912010-10-14 01:16:09 +0000762static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
763 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
764 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000765 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000766 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000767 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000768 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000769 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000770}
771
Evan Cheng87b75ba2009-11-20 19:55:37 +0000772
Evan Cheng23128422010-10-19 18:58:51 +0000773/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
774/// and an use in the current loop, return true if the target considered
775/// it 'high'.
776bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000777 unsigned DefIdx, unsigned Reg) const {
778 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000779 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000780
Evan Cheng0e673912010-10-14 01:16:09 +0000781 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
782 E = MRI->use_nodbg_end(); I != E; ++I) {
783 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000784 if (UseMI->isCopyLike())
785 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000786 if (!CurLoop->contains(UseMI->getParent()))
787 continue;
788 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
789 const MachineOperand &MO = UseMI->getOperand(i);
790 if (!MO.isReg() || !MO.isUse())
791 continue;
792 unsigned MOReg = MO.getReg();
793 if (MOReg != Reg)
794 continue;
795
Evan Cheng23128422010-10-19 18:58:51 +0000796 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
797 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000798 }
799
Evan Cheng23128422010-10-19 18:58:51 +0000800 // Only look at the first in loop use.
801 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000802 }
803
Evan Cheng23128422010-10-19 18:58:51 +0000804 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000805}
806
Evan Chengc8141df2010-10-26 02:08:50 +0000807/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
808/// the operand latency between its def and a use is one or less.
809bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
810 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
811 return true;
812 if (!InstrItins || InstrItins->isEmpty())
813 return false;
814
815 bool isCheap = false;
816 unsigned NumDefs = MI.getDesc().getNumDefs();
817 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
818 MachineOperand &DefMO = MI.getOperand(i);
819 if (!DefMO.isReg() || !DefMO.isDef())
820 continue;
821 --NumDefs;
822 unsigned Reg = DefMO.getReg();
823 if (TargetRegisterInfo::isPhysicalRegister(Reg))
824 continue;
825
826 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
827 return false;
828 isCheap = true;
829 }
830
831 return isCheap;
832}
833
Evan Cheng134982d2010-10-20 22:03:58 +0000834/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000835/// if hoisting an instruction of the given cost matrix can cause high
836/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000837bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
838 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
839 CI != CE; ++CI) {
840 if (CI->second <= 0)
841 continue;
842
843 unsigned RCId = CI->first;
844 for (unsigned i = BackTrace.size(); i != 0; --i) {
845 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000846 if (RP[RCId] + CI->second >= RegLimit[RCId])
847 return true;
848 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000849 }
850
851 return false;
852}
853
Evan Cheng134982d2010-10-20 22:03:58 +0000854/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
855/// current block and update their register pressures to reflect the effect
856/// of hoisting MI from the current block to the preheader.
857void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
858 if (MI->isImplicitDef())
859 return;
860
861 // First compute the 'cost' of the instruction, i.e. its contribution
862 // to register pressure.
863 DenseMap<unsigned, int> Cost;
864 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
865 const MachineOperand &MO = MI->getOperand(i);
866 if (!MO.isReg() || MO.isImplicit())
867 continue;
868 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000869 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000870 continue;
871
872 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
873 EVT VT = *RC->vt_begin();
874 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
875 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
876 if (MO.isDef()) {
877 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
878 if (CI != Cost.end())
879 CI->second += RCCost;
880 else
881 Cost.insert(std::make_pair(RCId, RCCost));
882 } else if (isOperandKill(MO, MRI)) {
883 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
884 if (CI != Cost.end())
885 CI->second -= RCCost;
886 else
887 Cost.insert(std::make_pair(RCId, -RCCost));
888 }
889 }
890
891 // Update register pressure of blocks from loop header to current block.
892 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
893 SmallVector<unsigned, 8> &RP = BackTrace[i];
894 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
895 CI != CE; ++CI) {
896 unsigned RCId = CI->first;
897 RP[RCId] += CI->second;
898 }
899 }
900}
901
Evan Cheng45e94d62009-02-04 09:19:56 +0000902/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
903/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000904bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000905 if (MI.isImplicitDef())
906 return true;
907
Evan Cheng23128422010-10-19 18:58:51 +0000908 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
909 // will increase register pressure. It's probably not worth it if the
910 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000911 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
912 // these tend to help performance in low register pressure situation. The
913 // trade off is it may cause spill in high pressure situation. It will end up
914 // adding a store in the loop preheader. But the reload is no more expensive.
915 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000916 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000917 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000918 return false;
919 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000920 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000921 // In low register pressure situation, we can be more aggressive about
922 // hoisting. Also, favors hoisting long latency instructions even in
923 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +0000924 // FIXME: If there are long latency loop-invariant instructions inside the
925 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000926 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000927 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
928 const MachineOperand &MO = MI.getOperand(i);
929 if (!MO.isReg() || MO.isImplicit())
930 continue;
931 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000932 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000933 continue;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000934 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000935 if (HasHighOperandLatency(MI, i, Reg)) {
936 ++NumHighLatency;
937 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000938 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000939
940 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
941 EVT VT = *RC->vt_begin();
942 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
943 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
944 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000945 if (CI != Cost.end())
946 CI->second += RCCost;
947 else
948 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +0000949 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000950 // Is a virtual register use is a kill, hoisting it out of the loop
951 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +0000952 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000953 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
954 EVT VT = *RC->vt_begin();
955 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
956 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
957 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
958 if (CI != Cost.end())
959 CI->second -= RCCost;
960 else
961 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000962 }
963 }
964
Evan Cheng134982d2010-10-20 22:03:58 +0000965 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000966 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +0000967 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000968 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000969 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000970 }
Evan Cheng0e673912010-10-14 01:16:09 +0000971
972 // High register pressure situation, only hoist if the instruction is going to
973 // be remat'ed.
974 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
Evan Cheng9fe20092011-01-20 08:34:58 +0000975 !MI.isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000976 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000977 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000978
Evan Chengaf6949d2009-02-05 08:45:46 +0000979 // If result(s) of this instruction is used by PHIs, then don't hoist it.
980 // The presence of joins makes it difficult for current register allocator
981 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000982 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
983 const MachineOperand &MO = MI.getOperand(i);
984 if (!MO.isReg() || !MO.isDef())
985 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000986 if (HasPHIUses(MO.getReg(), MRI))
Evan Chengaf6949d2009-02-05 08:45:46 +0000987 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000988 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000989
990 return true;
991}
992
Dan Gohman5c952302009-10-29 17:47:20 +0000993MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +0000994 // Don't unfold simple loads.
995 if (MI->getDesc().canFoldAsLoad())
996 return 0;
997
Dan Gohman5c952302009-10-29 17:47:20 +0000998 // If not, we may be able to unfold a load and hoist that.
999 // First test whether the instruction is loading from an amenable
1000 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001001 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001002 return 0;
1003
Dan Gohman5c952302009-10-29 17:47:20 +00001004 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001005 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001006 unsigned NewOpc =
1007 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1008 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001009 /*UnfoldStore=*/false,
1010 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001011 if (NewOpc == 0) return 0;
1012 const TargetInstrDesc &TID = TII->get(NewOpc);
1013 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +00001014 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001015 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001016 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001017
1018 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001019 SmallVector<MachineInstr *, 2> NewMIs;
1020 bool Success =
1021 TII->unfoldMemoryOperand(MF, MI, Reg,
1022 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1023 NewMIs);
1024 (void)Success;
1025 assert(Success &&
1026 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1027 "succeeded!");
1028 assert(NewMIs.size() == 2 &&
1029 "Unfolded a load into multiple instructions!");
1030 MachineBasicBlock *MBB = MI->getParent();
1031 MBB->insert(MI, NewMIs[0]);
1032 MBB->insert(MI, NewMIs[1]);
1033 // If unfolding produced a load that wasn't loop-invariant or profitable to
1034 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001035 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001036 NewMIs[0]->eraseFromParent();
1037 NewMIs[1]->eraseFromParent();
1038 return 0;
1039 }
Evan Cheng134982d2010-10-20 22:03:58 +00001040
1041 // Update register pressure for the unfolded instruction.
1042 UpdateRegPressure(NewMIs[1]);
1043
Dan Gohman5c952302009-10-29 17:47:20 +00001044 // Otherwise we successfully unfolded a load that we can hoist.
1045 MI->eraseFromParent();
1046 return NewMIs[0];
1047}
1048
Evan Cheng777c6b72009-11-03 21:40:02 +00001049void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1050 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1051 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001052 unsigned Opcode = MI->getOpcode();
1053 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1054 CI = CSEMap.find(Opcode);
1055 if (CI != CSEMap.end())
1056 CI->second.push_back(MI);
1057 else {
1058 std::vector<const MachineInstr*> CSEMIs;
1059 CSEMIs.push_back(MI);
1060 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001061 }
1062 }
1063}
1064
Evan Cheng78e5c112009-11-07 03:52:02 +00001065const MachineInstr*
1066MachineLICM::LookForDuplicate(const MachineInstr *MI,
1067 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001068 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1069 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001070 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001071 return PrevMI;
1072 }
1073 return 0;
1074}
1075
1076bool MachineLICM::EliminateCSE(MachineInstr *MI,
1077 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001078 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1079 // the undef property onto uses.
1080 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001081 return false;
1082
1083 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001084 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001085
1086 // Replace virtual registers defined by MI by their counterparts defined
1087 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001088 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1089 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001090
1091 // Physical registers may not differ here.
1092 assert((!MO.isReg() || MO.getReg() == 0 ||
1093 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1094 MO.getReg() == Dup->getOperand(i).getReg()) &&
1095 "Instructions with different phys regs are not identical!");
1096
1097 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001098 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001099 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1100 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001101 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001102 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001103 MI->eraseFromParent();
1104 ++NumCSEed;
1105 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001106 }
1107 return false;
1108}
1109
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001110/// Hoist - When an instruction is found to use only loop invariant operands
1111/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001112///
Evan Cheng134982d2010-10-20 22:03:58 +00001113bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001114 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001115 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001116 // If not, try unfolding a hoistable load.
1117 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001118 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001119 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001120
Dan Gohmanc475c362009-01-15 22:01:38 +00001121 // Now move the instructions to the predecessor, inserting it before any
1122 // terminator instructions.
1123 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001124 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001125 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001126 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001127 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001128 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001129 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001130 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001131 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001132 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001133
Evan Cheng777c6b72009-11-03 21:40:02 +00001134 // If this is the first instruction being hoisted to the preheader,
1135 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001136 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001137 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001138 FirstInLoop = false;
1139 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001140
Evan Chengaf6949d2009-02-05 08:45:46 +00001141 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001142 unsigned Opcode = MI->getOpcode();
1143 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1144 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001145 if (!EliminateCSE(MI, CI)) {
1146 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001147 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001148
Evan Cheng134982d2010-10-20 22:03:58 +00001149 // Update register pressure for BBs from header to this block.
1150 UpdateBackTraceRegPressure(MI);
1151
Dan Gohmane6cd7572010-05-13 20:34:42 +00001152 // Clear the kill flags of any register this instruction defines,
1153 // since they may need to be live throughout the entire loop
1154 // rather than just live for part of it.
1155 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1156 MachineOperand &MO = MI->getOperand(i);
1157 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001158 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001159 }
1160
Evan Chengaf6949d2009-02-05 08:45:46 +00001161 // Add to the CSE map.
1162 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001163 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001164 else {
1165 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001166 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001167 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001168 }
1169 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001170
Dan Gohmanc475c362009-01-15 22:01:38 +00001171 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001172 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001173
1174 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001175}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001176
1177MachineBasicBlock *MachineLICM::getCurPreheader() {
1178 // Determine the block to which to hoist instructions. If we can't find a
1179 // suitable loop predecessor, we can't do any hoisting.
1180
1181 // If we've tried to get a preheader and failed, don't try again.
1182 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1183 return 0;
1184
1185 if (!CurPreheader) {
1186 CurPreheader = CurLoop->getLoopPreheader();
1187 if (!CurPreheader) {
1188 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1189 if (!Pred) {
1190 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1191 return 0;
1192 }
1193
1194 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1195 if (!CurPreheader) {
1196 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1197 return 0;
1198 }
1199 }
1200 }
1201 return CurPreheader;
1202}