blob: e3b21c4ca577bc0e989b26a585351540b7db2622 [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
Evan Cheng87b75ba2009-11-20 19:55:37 +0000211 /// isLoadFromConstantMemory - Return true if the given instruction is a
212 /// load from constant memory.
213 bool isLoadFromConstantMemory(MachineInstr *MI);
214
Dan Gohman5c952302009-10-29 17:47:20 +0000215 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
216 /// the load itself could be hoisted. Return the unfolded and hoistable
217 /// load, or null if the load couldn't be unfolded or if it wouldn't
218 /// be hoistable.
219 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
220
Evan Cheng78e5c112009-11-07 03:52:02 +0000221 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
222 /// duplicate of MI. Return this instruction if it's found.
223 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
224 std::vector<const MachineInstr*> &PrevMIs);
225
Evan Cheng9fb744e2009-11-05 00:51:13 +0000226 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
227 /// the preheader that compute the same value. If it's found, do a RAU on
228 /// with the definition of the existing instruction rather than hoisting
229 /// the instruction to the preheader.
230 bool EliminateCSE(MachineInstr *MI,
231 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
232
Bill Wendling0f940c92007-12-07 21:42:31 +0000233 /// Hoist - When an instruction is found to only use loop invariant operands
234 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000235 /// It returns true if the instruction is hoisted.
236 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000237
238 /// InitCSEMap - Initialize the CSE map with instructions that are in the
239 /// current loop preheader that may become duplicates of instructions that
240 /// are hoisted out of the loop.
241 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000242
243 /// getCurPreheader - Get the preheader for the current loop, splitting
244 /// a critical edge if needed.
245 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000246 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000247} // end anonymous namespace
248
Dan Gohman844731a2008-05-13 00:00:25 +0000249char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000250INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
251 "Machine Loop Invariant Code Motion", false, false)
252INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
253INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
254INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
255INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000256 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000257
Evan Chengd94671a2010-04-07 00:41:17 +0000258FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
259 return new MachineLICM(PreRegAlloc);
260}
Bill Wendling0f940c92007-12-07 21:42:31 +0000261
Dan Gohman853d3fb2010-06-22 17:25:57 +0000262/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
263/// loop that has a unique predecessor.
264static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000265 // Check whether this loop even has a unique predecessor.
266 if (!CurLoop->getLoopPredecessor())
267 return false;
268 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000269 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000270 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000271 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000272 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000273 return true;
274}
275
Bill Wendling0f940c92007-12-07 21:42:31 +0000276bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000277 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000278 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000279 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000280 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
281 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000282
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000283 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000284 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000285 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000286 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000287 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000288 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000289 MRI = &MF.getRegInfo();
290 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000291 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000292
Evan Cheng0e673912010-10-14 01:16:09 +0000293 if (PreRegAlloc) {
294 // Estimate register pressure during pre-regalloc pass.
295 unsigned NumRC = TRI->getNumRegClasses();
296 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000297 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000298 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000299 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
300 E = TRI->regclass_end(); I != E; ++I)
301 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
302 }
303
Bill Wendling0f940c92007-12-07 21:42:31 +0000304 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000305 MLI = &getAnalysis<MachineLoopInfo>();
306 DT = &getAnalysis<MachineDominatorTree>();
307 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000308
Dan Gohmanaa742602010-07-09 18:49:45 +0000309 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
310 while (!Worklist.empty()) {
311 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000312 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000313
Evan Cheng4038f9c2010-04-08 01:03:47 +0000314 // If this is done before regalloc, only visit outer-most preheader-sporting
315 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000316 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
317 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000318 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000319 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000320
Evan Chengd94671a2010-04-07 00:41:17 +0000321 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000322 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000323 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000324 // CSEMap is initialized for loop header when the first instruction is
325 // being hoisted.
326 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000327 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000328 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000329 CSEMap.clear();
330 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000331 }
332
333 return Changed;
334}
335
Evan Cheng4038f9c2010-04-08 01:03:47 +0000336/// InstructionStoresToFI - Return true if instruction stores to the
337/// specified frame.
338static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
339 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
340 oe = MI->memoperands_end(); o != oe; ++o) {
341 if (!(*o)->isStore() || !(*o)->getValue())
342 continue;
343 if (const FixedStackPseudoSourceValue *Value =
344 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
345 if (Value->getFrameIndex() == FI)
346 return true;
347 }
348 }
349 return false;
350}
351
352/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
353/// gather register def and frame object update information.
354void MachineLICM::ProcessMI(MachineInstr *MI,
355 unsigned *PhysRegDefs,
356 SmallSet<int, 32> &StoredFIs,
357 SmallVector<CandidateInfo, 32> &Candidates) {
358 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000359 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000360 unsigned Def = 0;
361 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
362 const MachineOperand &MO = MI->getOperand(i);
363 if (MO.isFI()) {
364 // Remember if the instruction stores to the frame index.
365 int FI = MO.getIndex();
366 if (!StoredFIs.count(FI) &&
367 MFI->isSpillSlotObjectIndex(FI) &&
368 InstructionStoresToFI(MI, FI))
369 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000370 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000371 continue;
372 }
373
374 if (!MO.isReg())
375 continue;
376 unsigned Reg = MO.getReg();
377 if (!Reg)
378 continue;
379 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
380 "Not expecting virtual register!");
381
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000382 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000383 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000384 // If it's using a non-loop-invariant register, then it's obviously not
385 // safe to hoist.
386 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000387 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000388 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000389
390 if (MO.isImplicit()) {
391 ++PhysRegDefs[Reg];
392 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
393 ++PhysRegDefs[*AS];
394 if (!MO.isDead())
395 // Non-dead implicit def? This cannot be hoisted.
396 RuledOut = true;
397 // No need to check if a dead implicit def is also defined by
398 // another instruction.
399 continue;
400 }
401
402 // FIXME: For now, avoid instructions with multiple defs, unless
403 // it's a dead implicit def.
404 if (Def)
405 RuledOut = true;
406 else
407 Def = Reg;
408
409 // If we have already seen another instruction that defines the same
410 // register, then this is not safe.
411 if (++PhysRegDefs[Reg] > 1)
412 // MI defined register is seen defined by another instruction in
413 // the loop, it cannot be a LICM candidate.
414 RuledOut = true;
415 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
416 if (++PhysRegDefs[*AS] > 1)
417 RuledOut = true;
418 }
419
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000420 // Only consider reloads for now and remats which do not have register
421 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000422 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000423 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000424 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000425 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
426 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000427 }
428}
429
430/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
431/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000432void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000433 unsigned NumRegs = TRI->getNumRegs();
434 unsigned *PhysRegDefs = new unsigned[NumRegs];
435 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
436
Evan Cheng4038f9c2010-04-08 01:03:47 +0000437 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000438 SmallSet<int, 32> StoredFIs;
439
440 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000441 // collect potential LICM candidates.
442 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
443 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
444 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000445 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000446 // FIXME: That means a reload that're reused in successor block(s) will not
447 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000448 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000449 E = BB->livein_end(); I != E; ++I) {
450 unsigned Reg = *I;
451 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000452 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
453 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000454 }
455
456 for (MachineBasicBlock::iterator
457 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000458 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000459 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000460 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000461 }
Evan Chengd94671a2010-04-07 00:41:17 +0000462
463 // Now evaluate whether the potential candidates qualify.
464 // 1. Check if the candidate defined register is defined by another
465 // instruction in the loop.
466 // 2. If the candidate is a load from stack slot (always true for now),
467 // check if the slot is stored anywhere in the loop.
468 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000469 if (Candidates[i].FI != INT_MIN &&
470 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000471 continue;
472
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000473 if (PhysRegDefs[Candidates[i].Def] == 1) {
474 bool Safe = true;
475 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000476 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
477 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000478 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000479 continue;
480 if (PhysRegDefs[MO.getReg()]) {
481 // If it's using a non-loop-invariant register, then it's obviously
482 // not safe to hoist.
483 Safe = false;
484 break;
485 }
486 }
487 if (Safe)
488 HoistPostRA(MI, Candidates[i].Def);
489 }
Evan Chengd94671a2010-04-07 00:41:17 +0000490 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000491
492 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000493}
494
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000495/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
496/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000497void MachineLICM::AddToLiveIns(unsigned Reg) {
498 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000499 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
500 MachineBasicBlock *BB = Blocks[i];
501 if (!BB->isLiveIn(Reg))
502 BB->addLiveIn(Reg);
503 for (MachineBasicBlock::iterator
504 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
505 MachineInstr *MI = &*MII;
506 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
507 MachineOperand &MO = MI->getOperand(i);
508 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
509 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
510 MO.setIsKill(false);
511 }
512 }
513 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000514}
515
516/// HoistPostRA - When an instruction is found to only use loop invariant
517/// operands that is safe to hoist, this instruction is called to do the
518/// dirty work.
519void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000520 MachineBasicBlock *Preheader = getCurPreheader();
521 if (!Preheader) return;
522
Evan Chengd94671a2010-04-07 00:41:17 +0000523 // Now move the instructions to the predecessor, inserting it before any
524 // terminator instructions.
525 DEBUG({
526 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000527 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000528 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000529 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000530 if (MI->getParent()->getBasicBlock())
531 dbgs() << " from MachineBasicBlock "
532 << MI->getParent()->getName();
533 dbgs() << "\n";
534 });
535
536 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000537 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000538 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000539
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000540 // Add register to livein list to all the BBs in the current loop since a
541 // loop invariant must be kept live throughout the whole loop. This is
542 // important to ensure later passes do not scavenge the def register.
543 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000544
545 ++NumPostRAHoisted;
546 Changed = true;
547}
548
Bill Wendling0f940c92007-12-07 21:42:31 +0000549/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
550/// dominated by the specified block, and that are in the current loop) in depth
551/// first order w.r.t the DominatorTree. This allows us to visit definitions
552/// before uses, allowing us to hoist a loop body in one pass without iteration.
553///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000554void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000555 assert(N != 0 && "Null dominator tree node?");
556 MachineBasicBlock *BB = N->getBlock();
557
558 // If this subregion is not in the top level loop at all, exit.
559 if (!CurLoop->contains(BB)) return;
560
Evan Cheng0e673912010-10-14 01:16:09 +0000561 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000562 if (!Preheader)
563 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000564
Evan Cheng23128422010-10-19 18:58:51 +0000565 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000566 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000567 RegSeen.clear();
568 BackTrace.clear();
569 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000570 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000571
Evan Cheng23128422010-10-19 18:58:51 +0000572 // Remember livein register pressure.
573 BackTrace.push_back(RegPressure);
574
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000575 for (MachineBasicBlock::iterator
576 MII = BB->begin(), E = BB->end(); MII != E; ) {
577 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
578 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000579 if (!Hoist(MI, Preheader))
580 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000581 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000582 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000583
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000584 // Don't hoist things out of a large switch statement. This often causes
585 // code to be hoisted that wasn't going to be executed, and increases
586 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000587 if (BB->succ_size() < 25) {
588 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000589 for (unsigned I = 0, E = Children.size(); I != E; ++I)
590 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000591 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000592
Evan Cheng23128422010-10-19 18:58:51 +0000593 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000594}
595
Evan Cheng134982d2010-10-20 22:03:58 +0000596static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
597 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
598}
599
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000600/// InitRegPressure - Find all virtual register references that are liveout of
601/// the preheader to initialize the starting "register pressure". Note this
602/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000603void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000604 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000605
Evan Cheng134982d2010-10-20 22:03:58 +0000606 // If the preheader has only a single predecessor and it ends with a
607 // fallthrough or an unconditional branch, then scan its predecessor for live
608 // defs as well. This happens whenever the preheader is created by splitting
609 // the critical edge from the loop predecessor to the loop header.
610 if (BB->pred_size() == 1) {
611 MachineBasicBlock *TBB = 0, *FBB = 0;
612 SmallVector<MachineOperand, 4> Cond;
613 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
614 InitRegPressure(*BB->pred_begin());
615 }
616
Evan Cheng0e673912010-10-14 01:16:09 +0000617 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
618 MII != E; ++MII) {
619 MachineInstr *MI = &*MII;
620 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
621 const MachineOperand &MO = MI->getOperand(i);
622 if (!MO.isReg() || MO.isImplicit())
623 continue;
624 unsigned Reg = MO.getReg();
625 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
626 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000627
Andrew Trickdc986d22010-10-19 02:50:50 +0000628 bool isNew = RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000629 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
630 EVT VT = *RC->vt_begin();
631 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000632 if (MO.isDef())
633 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
634 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000635 bool isKill = isOperandKill(MO, MRI);
636 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000637 // Haven't seen this, it must be a livein.
638 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Evan Cheng134982d2010-10-20 22:03:58 +0000639 else if (!isNew && isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000640 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
641 }
Evan Cheng0e673912010-10-14 01:16:09 +0000642 }
643 }
644}
645
Evan Cheng134982d2010-10-20 22:03:58 +0000646/// UpdateRegPressure - Update estimate of register pressure after the
647/// specified instruction.
648void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
649 if (MI->isImplicitDef())
650 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000651
Evan Cheng134982d2010-10-20 22:03:58 +0000652 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000653 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
654 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000655 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000656 continue;
657 unsigned Reg = MO.getReg();
658 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
659 continue;
660
Andrew Trickdc986d22010-10-19 02:50:50 +0000661 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000662 if (MO.isDef())
663 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000664 else if (!isNew && isOperandKill(MO, MRI)) {
665 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
666 EVT VT = *RC->vt_begin();
667 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
668 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000669
Evan Cheng134982d2010-10-20 22:03:58 +0000670 if (RCCost > RegPressure[RCId])
671 RegPressure[RCId] = 0;
672 else
Evan Cheng23128422010-10-19 18:58:51 +0000673 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000674 }
Evan Cheng0e673912010-10-14 01:16:09 +0000675 }
Evan Cheng0e673912010-10-14 01:16:09 +0000676
Evan Cheng23128422010-10-19 18:58:51 +0000677 while (!Defs.empty()) {
678 unsigned Reg = Defs.pop_back_val();
Evan Cheng0e673912010-10-14 01:16:09 +0000679 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
680 EVT VT = *RC->vt_begin();
681 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
682 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
683 RegPressure[RCId] += RCCost;
684 }
685}
686
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000687/// IsLICMCandidate - Returns true if the instruction may be a suitable
688/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
689/// not safe to hoist it.
690bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000691 // Check if it's safe to move the instruction.
692 bool DontMoveAcrossStore = true;
693 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000694 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000695
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000696 return true;
697}
698
699/// IsLoopInvariantInst - Returns true if the instruction is loop
700/// invariant. I.e., all virtual register operands are defined outside of the
701/// loop, physical registers aren't accessed explicitly, and there are no side
702/// effects that aren't captured by the operands or other flags.
703///
704bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
705 if (!IsLICMCandidate(I))
706 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000707
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000708 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000709 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
710 const MachineOperand &MO = I.getOperand(i);
711
Dan Gohmand735b802008-10-03 15:45:36 +0000712 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000713 continue;
714
Dan Gohmanc475c362009-01-15 22:01:38 +0000715 unsigned Reg = MO.getReg();
716 if (Reg == 0) continue;
717
718 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000719 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000720 if (MO.isUse()) {
721 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000722 // and we can freely move its uses. Alternatively, if it's allocatable,
723 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000724 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000725 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000726 if (AllocatableSet.test(Reg))
727 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000728 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000729 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
730 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000731 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000732 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000733 if (AllocatableSet.test(AliasReg))
734 return false;
735 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000736 // Otherwise it's safe to move.
737 continue;
738 } else if (!MO.isDead()) {
739 // A def that isn't dead. We can't move it.
740 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000741 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
742 // If the reg is live into the loop, we can't hoist an instruction
743 // which would clobber it.
744 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000745 }
746 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000747
748 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000749 continue;
750
Evan Cheng0e673912010-10-14 01:16:09 +0000751 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000752 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000753
754 // If the loop contains the definition of an operand, then the instruction
755 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000756 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000757 return false;
758 }
759
760 // If we got this far, the instruction is loop invariant!
761 return true;
762}
763
Evan Chengaf6949d2009-02-05 08:45:46 +0000764
765/// HasPHIUses - Return true if the specified register has any PHI use.
Evan Cheng0e673912010-10-14 01:16:09 +0000766static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
767 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
768 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000769 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000770 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000771 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000772 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000773 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000774}
775
Evan Cheng87b75ba2009-11-20 19:55:37 +0000776/// isLoadFromConstantMemory - Return true if the given instruction is a
777/// load from constant memory. Machine LICM will hoist these even if they are
778/// not re-materializable.
779bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
780 if (!MI->getDesc().mayLoad()) return false;
781 if (!MI->hasOneMemOperand()) return false;
782 MachineMemOperand *MMO = *MI->memoperands_begin();
783 if (MMO->isVolatile()) return false;
784 if (!MMO->getValue()) return false;
785 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
786 if (PSV) {
787 MachineFunction &MF = *MI->getParent()->getParent();
788 return PSV->isConstant(MF.getFrameInfo());
789 } else {
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000790 return AA->pointsToConstantMemory(AliasAnalysis::Location(MMO->getValue(),
791 MMO->getSize(),
792 MMO->getTBAAInfo()));
Evan Cheng87b75ba2009-11-20 19:55:37 +0000793 }
794}
795
Evan Cheng23128422010-10-19 18:58:51 +0000796/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
797/// and an use in the current loop, return true if the target considered
798/// it 'high'.
799bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000800 unsigned DefIdx, unsigned Reg) const {
801 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000802 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000803
Evan Cheng0e673912010-10-14 01:16:09 +0000804 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
805 E = MRI->use_nodbg_end(); I != E; ++I) {
806 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000807 if (UseMI->isCopyLike())
808 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000809 if (!CurLoop->contains(UseMI->getParent()))
810 continue;
811 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
812 const MachineOperand &MO = UseMI->getOperand(i);
813 if (!MO.isReg() || !MO.isUse())
814 continue;
815 unsigned MOReg = MO.getReg();
816 if (MOReg != Reg)
817 continue;
818
Evan Cheng23128422010-10-19 18:58:51 +0000819 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
820 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000821 }
822
Evan Cheng23128422010-10-19 18:58:51 +0000823 // Only look at the first in loop use.
824 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000825 }
826
Evan Cheng23128422010-10-19 18:58:51 +0000827 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000828}
829
Evan Chengc8141df2010-10-26 02:08:50 +0000830/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
831/// the operand latency between its def and a use is one or less.
832bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
833 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
834 return true;
835 if (!InstrItins || InstrItins->isEmpty())
836 return false;
837
838 bool isCheap = false;
839 unsigned NumDefs = MI.getDesc().getNumDefs();
840 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
841 MachineOperand &DefMO = MI.getOperand(i);
842 if (!DefMO.isReg() || !DefMO.isDef())
843 continue;
844 --NumDefs;
845 unsigned Reg = DefMO.getReg();
846 if (TargetRegisterInfo::isPhysicalRegister(Reg))
847 continue;
848
849 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
850 return false;
851 isCheap = true;
852 }
853
854 return isCheap;
855}
856
Evan Cheng134982d2010-10-20 22:03:58 +0000857/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000858/// if hoisting an instruction of the given cost matrix can cause high
859/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000860bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
861 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
862 CI != CE; ++CI) {
863 if (CI->second <= 0)
864 continue;
865
866 unsigned RCId = CI->first;
867 for (unsigned i = BackTrace.size(); i != 0; --i) {
868 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000869 if (RP[RCId] + CI->second >= RegLimit[RCId])
870 return true;
871 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000872 }
873
874 return false;
875}
876
Evan Cheng134982d2010-10-20 22:03:58 +0000877/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
878/// current block and update their register pressures to reflect the effect
879/// of hoisting MI from the current block to the preheader.
880void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
881 if (MI->isImplicitDef())
882 return;
883
884 // First compute the 'cost' of the instruction, i.e. its contribution
885 // to register pressure.
886 DenseMap<unsigned, int> Cost;
887 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
888 const MachineOperand &MO = MI->getOperand(i);
889 if (!MO.isReg() || MO.isImplicit())
890 continue;
891 unsigned Reg = MO.getReg();
892 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
893 continue;
894
895 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
896 EVT VT = *RC->vt_begin();
897 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
898 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
899 if (MO.isDef()) {
900 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
901 if (CI != Cost.end())
902 CI->second += RCCost;
903 else
904 Cost.insert(std::make_pair(RCId, RCCost));
905 } else if (isOperandKill(MO, MRI)) {
906 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
907 if (CI != Cost.end())
908 CI->second -= RCCost;
909 else
910 Cost.insert(std::make_pair(RCId, -RCCost));
911 }
912 }
913
914 // Update register pressure of blocks from loop header to current block.
915 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
916 SmallVector<unsigned, 8> &RP = BackTrace[i];
917 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
918 CI != CE; ++CI) {
919 unsigned RCId = CI->first;
920 RP[RCId] += CI->second;
921 }
922 }
923}
924
Evan Cheng45e94d62009-02-04 09:19:56 +0000925/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
926/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000927bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000928 if (MI.isImplicitDef())
929 return true;
930
Evan Cheng23128422010-10-19 18:58:51 +0000931 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
932 // will increase register pressure. It's probably not worth it if the
933 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000934 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
935 // these tend to help performance in low register pressure situation. The
936 // trade off is it may cause spill in high pressure situation. It will end up
937 // adding a store in the loop preheader. But the reload is no more expensive.
938 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000939 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000940 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000941 return false;
942 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000943 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000944 // In low register pressure situation, we can be more aggressive about
945 // hoisting. Also, favors hoisting long latency instructions even in
946 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +0000947 // FIXME: If there are long latency loop-invariant instructions inside the
948 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000949 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000950 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
951 const MachineOperand &MO = MI.getOperand(i);
952 if (!MO.isReg() || MO.isImplicit())
953 continue;
954 unsigned Reg = MO.getReg();
955 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
956 continue;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000957 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000958 if (HasHighOperandLatency(MI, i, Reg)) {
959 ++NumHighLatency;
960 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000961 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000962
963 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
964 EVT VT = *RC->vt_begin();
965 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
966 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
967 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000968 if (CI != Cost.end())
969 CI->second += RCCost;
970 else
971 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +0000972 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000973 // Is a virtual register use is a kill, hoisting it out of the loop
974 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +0000975 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000976 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
977 EVT VT = *RC->vt_begin();
978 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
979 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
980 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
981 if (CI != Cost.end())
982 CI->second -= RCCost;
983 else
984 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000985 }
986 }
987
Evan Cheng134982d2010-10-20 22:03:58 +0000988 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000989 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +0000990 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000991 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000992 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000993 }
Evan Cheng0e673912010-10-14 01:16:09 +0000994
995 // High register pressure situation, only hoist if the instruction is going to
996 // be remat'ed.
997 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
998 !isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000999 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001000 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001001
Evan Chengaf6949d2009-02-05 08:45:46 +00001002 // If result(s) of this instruction is used by PHIs, then don't hoist it.
1003 // The presence of joins makes it difficult for current register allocator
1004 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +00001005 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1006 const MachineOperand &MO = MI.getOperand(i);
1007 if (!MO.isReg() || !MO.isDef())
1008 continue;
Evan Cheng0e673912010-10-14 01:16:09 +00001009 if (HasPHIUses(MO.getReg(), MRI))
Evan Chengaf6949d2009-02-05 08:45:46 +00001010 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001011 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001012
1013 return true;
1014}
1015
Dan Gohman5c952302009-10-29 17:47:20 +00001016MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001017 // Don't unfold simple loads.
1018 if (MI->getDesc().canFoldAsLoad())
1019 return 0;
1020
Dan Gohman5c952302009-10-29 17:47:20 +00001021 // If not, we may be able to unfold a load and hoist that.
1022 // First test whether the instruction is loading from an amenable
1023 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +00001024 if (!isLoadFromConstantMemory(MI))
1025 return 0;
1026
Dan Gohman5c952302009-10-29 17:47:20 +00001027 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001028 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001029 unsigned NewOpc =
1030 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1031 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001032 /*UnfoldStore=*/false,
1033 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001034 if (NewOpc == 0) return 0;
1035 const TargetInstrDesc &TID = TII->get(NewOpc);
1036 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +00001037 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001038 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001039 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001040
1041 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001042 SmallVector<MachineInstr *, 2> NewMIs;
1043 bool Success =
1044 TII->unfoldMemoryOperand(MF, MI, Reg,
1045 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1046 NewMIs);
1047 (void)Success;
1048 assert(Success &&
1049 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1050 "succeeded!");
1051 assert(NewMIs.size() == 2 &&
1052 "Unfolded a load into multiple instructions!");
1053 MachineBasicBlock *MBB = MI->getParent();
1054 MBB->insert(MI, NewMIs[0]);
1055 MBB->insert(MI, NewMIs[1]);
1056 // If unfolding produced a load that wasn't loop-invariant or profitable to
1057 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001058 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001059 NewMIs[0]->eraseFromParent();
1060 NewMIs[1]->eraseFromParent();
1061 return 0;
1062 }
Evan Cheng134982d2010-10-20 22:03:58 +00001063
1064 // Update register pressure for the unfolded instruction.
1065 UpdateRegPressure(NewMIs[1]);
1066
Dan Gohman5c952302009-10-29 17:47:20 +00001067 // Otherwise we successfully unfolded a load that we can hoist.
1068 MI->eraseFromParent();
1069 return NewMIs[0];
1070}
1071
Evan Cheng777c6b72009-11-03 21:40:02 +00001072void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1073 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1074 const MachineInstr *MI = &*I;
1075 // FIXME: For now, only hoist re-materilizable instructions. LICM will
1076 // increase register pressure. We want to make sure it doesn't increase
1077 // spilling.
1078 if (TII->isTriviallyReMaterializable(MI, AA)) {
1079 unsigned Opcode = MI->getOpcode();
1080 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1081 CI = CSEMap.find(Opcode);
1082 if (CI != CSEMap.end())
1083 CI->second.push_back(MI);
1084 else {
1085 std::vector<const MachineInstr*> CSEMIs;
1086 CSEMIs.push_back(MI);
1087 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1088 }
1089 }
1090 }
1091}
1092
Evan Cheng78e5c112009-11-07 03:52:02 +00001093const MachineInstr*
1094MachineLICM::LookForDuplicate(const MachineInstr *MI,
1095 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001096 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1097 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +00001098 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001099 return PrevMI;
1100 }
1101 return 0;
1102}
1103
1104bool MachineLICM::EliminateCSE(MachineInstr *MI,
1105 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001106 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1107 // the undef property onto uses.
1108 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001109 return false;
1110
1111 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001112 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001113
1114 // Replace virtual registers defined by MI by their counterparts defined
1115 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001116 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1117 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001118
1119 // Physical registers may not differ here.
1120 assert((!MO.isReg() || MO.getReg() == 0 ||
1121 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1122 MO.getReg() == Dup->getOperand(i).getReg()) &&
1123 "Instructions with different phys regs are not identical!");
1124
1125 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001126 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001127 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1128 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001129 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001130 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001131 MI->eraseFromParent();
1132 ++NumCSEed;
1133 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001134 }
1135 return false;
1136}
1137
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001138/// Hoist - When an instruction is found to use only loop invariant operands
1139/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001140///
Evan Cheng134982d2010-10-20 22:03:58 +00001141bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001142 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001143 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001144 // If not, try unfolding a hoistable load.
1145 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001146 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001147 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001148
Dan Gohmanc475c362009-01-15 22:01:38 +00001149 // Now move the instructions to the predecessor, inserting it before any
1150 // terminator instructions.
1151 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001152 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001153 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001154 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001155 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001156 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001157 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001158 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001159 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001160 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001161
Evan Cheng777c6b72009-11-03 21:40:02 +00001162 // If this is the first instruction being hoisted to the preheader,
1163 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001164 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001165 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001166 FirstInLoop = false;
1167 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001168
Evan Chengaf6949d2009-02-05 08:45:46 +00001169 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001170 unsigned Opcode = MI->getOpcode();
1171 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1172 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001173 if (!EliminateCSE(MI, CI)) {
1174 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001175 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001176
Evan Cheng134982d2010-10-20 22:03:58 +00001177 // Update register pressure for BBs from header to this block.
1178 UpdateBackTraceRegPressure(MI);
1179
Dan Gohmane6cd7572010-05-13 20:34:42 +00001180 // Clear the kill flags of any register this instruction defines,
1181 // since they may need to be live throughout the entire loop
1182 // rather than just live for part of it.
1183 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1184 MachineOperand &MO = MI->getOperand(i);
1185 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001186 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001187 }
1188
Evan Chengaf6949d2009-02-05 08:45:46 +00001189 // Add to the CSE map.
1190 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001191 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001192 else {
1193 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001194 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001195 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001196 }
1197 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001198
Dan Gohmanc475c362009-01-15 22:01:38 +00001199 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001200 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001201
1202 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001203}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001204
1205MachineBasicBlock *MachineLICM::getCurPreheader() {
1206 // Determine the block to which to hoist instructions. If we can't find a
1207 // suitable loop predecessor, we can't do any hoisting.
1208
1209 // If we've tried to get a preheader and failed, don't try again.
1210 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1211 return 0;
1212
1213 if (!CurPreheader) {
1214 CurPreheader = CurLoop->getLoopPreheader();
1215 if (!CurPreheader) {
1216 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1217 if (!Pred) {
1218 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1219 return 0;
1220 }
1221
1222 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1223 if (!CurPreheader) {
1224 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1225 return 0;
1226 }
1227 }
1228 }
1229 return CurPreheader;
1230}