blob: d310f252e28b181dfbff24ba9e29c45c1abf3a06 [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// This pass does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
Bill Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
Chris Lattnerac695822008-01-04 06:41:45 +000024#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000025#include "llvm/CodeGen/MachineDominators.h"
Evan Chengd94671a2010-04-07 00:41:17 +000026#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Evan Chengab8be962011-06-29 01:14:12 +000031#include "llvm/MC/MCInstrItineraries.h"
Evan Cheng0e673912010-10-14 01:16:09 +000032#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000033#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000034#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000035#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000036#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000037#include "llvm/ADT/DenseMap.h"
Evan Chengd94671a2010-04-07 00:41:17 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000039#include "llvm/ADT/Statistic.h"
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 +000042using namespace llvm;
43
Evan Cheng03a9fdf2010-10-16 02:20:26 +000044STATISTIC(NumHoisted,
45 "Number of machine instructions hoisted out of loops");
46STATISTIC(NumLowRP,
47 "Number of instructions hoisted in low reg pressure situation");
48STATISTIC(NumHighLatency,
49 "Number of high latency instructions hoisted");
50STATISTIC(NumCSEed,
51 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000052STATISTIC(NumPostRAHoisted,
53 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000054
Bill Wendling0f940c92007-12-07 21:42:31 +000055namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000056 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000057 bool PreRegAlloc;
58
Bill Wendling9258cd32008-01-02 19:32:43 +000059 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000060 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000061 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000062 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000063 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000064 MachineRegisterInfo *MRI;
65 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000066
Bill Wendling0f940c92007-12-07 21:42:31 +000067 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000068 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000069 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000070 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000071
Bill Wendling0f940c92007-12-07 21:42:31 +000072 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000073 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000074 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000075 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000076 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000077
Evan Chengd94671a2010-04-07 00:41:17 +000078 BitVector AllocatableSet;
79
Evan Cheng0e673912010-10-14 01:16:09 +000080 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000081 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000082 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000083
84 // Register pressure "limit" per register class. If the pressure
85 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000086 SmallVector<unsigned, 8> RegLimit;
87
Evan Cheng03a9fdf2010-10-16 02:20:26 +000088 // Register pressure on path leading from loop preheader to current BB.
89 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
90
Dale Johannesenc46a5f22010-07-29 17:45:24 +000091 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000092 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000093
Bill Wendling0f940c92007-12-07 21:42:31 +000094 public:
95 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000096 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +000097 MachineFunctionPass(ID), PreRegAlloc(true) {
98 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
99 }
Evan Chengd94671a2010-04-07 00:41:17 +0000100
101 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000102 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
103 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
104 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000105
106 virtual bool runOnMachineFunction(MachineFunction &MF);
107
Dan Gohman72241702008-12-18 01:37:56 +0000108 const char *getPassName() const { return "Machine Instruction LICM"; }
109
Bill Wendling0f940c92007-12-07 21:42:31 +0000110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000111 AU.addRequired<MachineLoopInfo>();
112 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000113 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000114 AU.addPreserved<MachineLoopInfo>();
115 AU.addPreserved<MachineDominatorTree>();
116 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000117 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000118
119 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000120 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000121 RegPressure.clear();
122 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000123 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000124 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
125 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
126 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000127 CSEMap.clear();
128 }
129
Bill Wendling0f940c92007-12-07 21:42:31 +0000130 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000131 /// CandidateInfo - Keep track of information about hoisting candidates.
132 struct CandidateInfo {
133 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000134 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000135 int FI;
136 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
137 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000138 };
139
140 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
141 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000142 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000143
144 /// HoistPostRA - When an instruction is found to only use loop invariant
145 /// operands that is safe to hoist, this instruction is called to do the
146 /// dirty work.
147 void HoistPostRA(MachineInstr *MI, unsigned Def);
148
149 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
150 /// gather register def and frame object update information.
151 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
152 SmallSet<int, 32> &StoredFIs,
153 SmallVector<CandidateInfo, 32> &Candidates);
154
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000155 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
156 /// current loop.
157 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000158
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000159 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000160 /// candidate for LICM. e.g. If the instruction is a call, then it's
161 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000162 bool IsLICMCandidate(MachineInstr &I);
163
Bill Wendling041b3f82007-12-08 23:58:46 +0000164 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000165 /// invariant. I.e., all virtual register operands are defined outside of
166 /// the loop, physical registers aren't accessed (explicitly or implicitly),
167 /// and the instruction is hoistable.
168 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000169 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000170
Evan Chengd67705f2011-04-11 21:09:18 +0000171 /// HasAnyPHIUse - Return true if the specified register is used by any
172 /// phi node.
173 bool HasAnyPHIUse(unsigned Reg) const;
174
Evan Cheng23128422010-10-19 18:58:51 +0000175 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
176 /// and an use in the current loop, return true if the target considered
177 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000178 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
179 unsigned Reg) const;
180
181 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000182
Evan Cheng134982d2010-10-20 22:03:58 +0000183 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
184 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000185 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000186 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
187
188 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
189 /// the current block and update their register pressures to reflect the
190 /// effect of hoisting MI from the current block to the preheader.
191 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000192
Evan Cheng45e94d62009-02-04 09:19:56 +0000193 /// IsProfitableToHoist - Return true if it is potentially profitable to
194 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000195 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000196
Bill Wendling0f940c92007-12-07 21:42:31 +0000197 /// HoistRegion - Walk the specified region of the CFG (defined by all
198 /// blocks dominated by the specified block, and that are in the current
199 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
200 /// visit definitions before uses, allowing us to hoist a loop body in one
201 /// pass without iteration.
202 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000203 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000204
Evan Cheng61560e22011-09-01 01:45:00 +0000205 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
206 /// index, return the ID and cost of its representative register class by
207 /// reference.
208 void getRegisterClassIDAndCost(const MachineInstr *MI,
209 unsigned Reg, unsigned OpIdx,
210 unsigned &RCId, unsigned &RCCost) const;
211
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000212 /// InitRegPressure - Find all virtual register references that are liveout
213 /// of the preheader to initialize the starting "register pressure". Note
214 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000215 void InitRegPressure(MachineBasicBlock *BB);
216
Evan Cheng134982d2010-10-20 22:03:58 +0000217 /// UpdateRegPressure - Update estimate of register pressure after the
218 /// specified instruction.
219 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000220
Dan Gohman5c952302009-10-29 17:47:20 +0000221 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
222 /// the load itself could be hoisted. Return the unfolded and hoistable
223 /// load, or null if the load couldn't be unfolded or if it wouldn't
224 /// be hoistable.
225 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
226
Evan Cheng78e5c112009-11-07 03:52:02 +0000227 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
228 /// duplicate of MI. Return this instruction if it's found.
229 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
230 std::vector<const MachineInstr*> &PrevMIs);
231
Evan Cheng9fb744e2009-11-05 00:51:13 +0000232 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
233 /// the preheader that compute the same value. If it's found, do a RAU on
234 /// with the definition of the existing instruction rather than hoisting
235 /// the instruction to the preheader.
236 bool EliminateCSE(MachineInstr *MI,
237 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
238
Bill Wendling0f940c92007-12-07 21:42:31 +0000239 /// Hoist - When an instruction is found to only use loop invariant operands
240 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000241 /// It returns true if the instruction is hoisted.
242 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000243
244 /// InitCSEMap - Initialize the CSE map with instructions that are in the
245 /// current loop preheader that may become duplicates of instructions that
246 /// are hoisted out of the loop.
247 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000248
249 /// getCurPreheader - Get the preheader for the current loop, splitting
250 /// a critical edge if needed.
251 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000252 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000253} // end anonymous namespace
254
Dan Gohman844731a2008-05-13 00:00:25 +0000255char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000256INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
257 "Machine Loop Invariant Code Motion", false, false)
258INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
259INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
260INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
261INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000262 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000263
Evan Chengd94671a2010-04-07 00:41:17 +0000264FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
265 return new MachineLICM(PreRegAlloc);
266}
Bill Wendling0f940c92007-12-07 21:42:31 +0000267
Dan Gohman853d3fb2010-06-22 17:25:57 +0000268/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
269/// loop that has a unique predecessor.
270static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000271 // Check whether this loop even has a unique predecessor.
272 if (!CurLoop->getLoopPredecessor())
273 return false;
274 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000275 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000276 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000277 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000278 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000279 return true;
280}
281
Bill Wendling0f940c92007-12-07 21:42:31 +0000282bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000283 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000284 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000285 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000286 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
287 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000288
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000289 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000290 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000291 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000292 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000293 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000294 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000295 MRI = &MF.getRegInfo();
296 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000297 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000298
Evan Cheng0e673912010-10-14 01:16:09 +0000299 if (PreRegAlloc) {
300 // Estimate register pressure during pre-regalloc pass.
301 unsigned NumRC = TRI->getNumRegClasses();
302 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000303 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000304 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000305 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
306 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000307 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000308 }
309
Bill Wendling0f940c92007-12-07 21:42:31 +0000310 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000311 MLI = &getAnalysis<MachineLoopInfo>();
312 DT = &getAnalysis<MachineDominatorTree>();
313 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000314
Dan Gohmanaa742602010-07-09 18:49:45 +0000315 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
316 while (!Worklist.empty()) {
317 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000318 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000319
Evan Cheng4038f9c2010-04-08 01:03:47 +0000320 // If this is done before regalloc, only visit outer-most preheader-sporting
321 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000322 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
323 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000324 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000325 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000326
Evan Chengd94671a2010-04-07 00:41:17 +0000327 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000328 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000329 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000330 // CSEMap is initialized for loop header when the first instruction is
331 // being hoisted.
332 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000333 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000334 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000335 CSEMap.clear();
336 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000337 }
338
339 return Changed;
340}
341
Evan Cheng4038f9c2010-04-08 01:03:47 +0000342/// InstructionStoresToFI - Return true if instruction stores to the
343/// specified frame.
344static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
345 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
346 oe = MI->memoperands_end(); o != oe; ++o) {
347 if (!(*o)->isStore() || !(*o)->getValue())
348 continue;
349 if (const FixedStackPseudoSourceValue *Value =
350 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
351 if (Value->getFrameIndex() == FI)
352 return true;
353 }
354 }
355 return false;
356}
357
358/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
359/// gather register def and frame object update information.
360void MachineLICM::ProcessMI(MachineInstr *MI,
361 unsigned *PhysRegDefs,
362 SmallSet<int, 32> &StoredFIs,
363 SmallVector<CandidateInfo, 32> &Candidates) {
364 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000365 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000366 unsigned Def = 0;
367 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
368 const MachineOperand &MO = MI->getOperand(i);
369 if (MO.isFI()) {
370 // Remember if the instruction stores to the frame index.
371 int FI = MO.getIndex();
372 if (!StoredFIs.count(FI) &&
373 MFI->isSpillSlotObjectIndex(FI) &&
374 InstructionStoresToFI(MI, FI))
375 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000376 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000377 continue;
378 }
379
380 if (!MO.isReg())
381 continue;
382 unsigned Reg = MO.getReg();
383 if (!Reg)
384 continue;
385 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
386 "Not expecting virtual register!");
387
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000388 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000389 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000390 // If it's using a non-loop-invariant register, then it's obviously not
391 // safe to hoist.
392 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000393 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000394 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000395
396 if (MO.isImplicit()) {
397 ++PhysRegDefs[Reg];
398 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
399 ++PhysRegDefs[*AS];
400 if (!MO.isDead())
401 // Non-dead implicit def? This cannot be hoisted.
402 RuledOut = true;
403 // No need to check if a dead implicit def is also defined by
404 // another instruction.
405 continue;
406 }
407
408 // FIXME: For now, avoid instructions with multiple defs, unless
409 // it's a dead implicit def.
410 if (Def)
411 RuledOut = true;
412 else
413 Def = Reg;
414
415 // If we have already seen another instruction that defines the same
416 // register, then this is not safe.
417 if (++PhysRegDefs[Reg] > 1)
418 // MI defined register is seen defined by another instruction in
419 // the loop, it cannot be a LICM candidate.
420 RuledOut = true;
421 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
422 if (++PhysRegDefs[*AS] > 1)
423 RuledOut = true;
424 }
425
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000426 // Only consider reloads for now and remats which do not have register
427 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000428 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000429 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000430 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000431 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
432 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000433 }
434}
435
436/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
437/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000438void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000439 unsigned NumRegs = TRI->getNumRegs();
440 unsigned *PhysRegDefs = new unsigned[NumRegs];
441 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
442
Evan Cheng4038f9c2010-04-08 01:03:47 +0000443 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000444 SmallSet<int, 32> StoredFIs;
445
446 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000447 // collect potential LICM candidates.
448 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
449 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
450 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000451 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000452 // FIXME: That means a reload that're reused in successor block(s) will not
453 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000454 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000455 E = BB->livein_end(); I != E; ++I) {
456 unsigned Reg = *I;
457 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000458 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
459 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000460 }
461
462 for (MachineBasicBlock::iterator
463 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000464 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000465 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000466 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000467 }
Evan Chengd94671a2010-04-07 00:41:17 +0000468
469 // Now evaluate whether the potential candidates qualify.
470 // 1. Check if the candidate defined register is defined by another
471 // instruction in the loop.
472 // 2. If the candidate is a load from stack slot (always true for now),
473 // check if the slot is stored anywhere in the loop.
474 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000475 if (Candidates[i].FI != INT_MIN &&
476 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000477 continue;
478
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000479 if (PhysRegDefs[Candidates[i].Def] == 1) {
480 bool Safe = true;
481 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000482 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
483 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000484 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000485 continue;
486 if (PhysRegDefs[MO.getReg()]) {
487 // If it's using a non-loop-invariant register, then it's obviously
488 // not safe to hoist.
489 Safe = false;
490 break;
491 }
492 }
493 if (Safe)
494 HoistPostRA(MI, Candidates[i].Def);
495 }
Evan Chengd94671a2010-04-07 00:41:17 +0000496 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000497
498 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000499}
500
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000501/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
502/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000503void MachineLICM::AddToLiveIns(unsigned Reg) {
504 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000505 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
506 MachineBasicBlock *BB = Blocks[i];
507 if (!BB->isLiveIn(Reg))
508 BB->addLiveIn(Reg);
509 for (MachineBasicBlock::iterator
510 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
511 MachineInstr *MI = &*MII;
512 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
513 MachineOperand &MO = MI->getOperand(i);
514 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
515 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
516 MO.setIsKill(false);
517 }
518 }
519 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000520}
521
522/// HoistPostRA - When an instruction is found to only use loop invariant
523/// operands that is safe to hoist, this instruction is called to do the
524/// dirty work.
525void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000526 MachineBasicBlock *Preheader = getCurPreheader();
527 if (!Preheader) return;
528
Evan Chengd94671a2010-04-07 00:41:17 +0000529 // Now move the instructions to the predecessor, inserting it before any
530 // terminator instructions.
531 DEBUG({
532 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000533 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000534 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000535 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000536 if (MI->getParent()->getBasicBlock())
537 dbgs() << " from MachineBasicBlock "
538 << MI->getParent()->getName();
539 dbgs() << "\n";
540 });
541
542 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000543 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000544 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000545
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000546 // Add register to livein list to all the BBs in the current loop since a
547 // loop invariant must be kept live throughout the whole loop. This is
548 // important to ensure later passes do not scavenge the def register.
549 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000550
551 ++NumPostRAHoisted;
552 Changed = true;
553}
554
Bill Wendling0f940c92007-12-07 21:42:31 +0000555/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
556/// dominated by the specified block, and that are in the current loop) in depth
557/// first order w.r.t the DominatorTree. This allows us to visit definitions
558/// before uses, allowing us to hoist a loop body in one pass without iteration.
559///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000560void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000561 assert(N != 0 && "Null dominator tree node?");
562 MachineBasicBlock *BB = N->getBlock();
563
564 // If this subregion is not in the top level loop at all, exit.
565 if (!CurLoop->contains(BB)) return;
566
Evan Cheng0e673912010-10-14 01:16:09 +0000567 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000568 if (!Preheader)
569 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000570
Evan Cheng23128422010-10-19 18:58:51 +0000571 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000572 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000573 RegSeen.clear();
574 BackTrace.clear();
575 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000576 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000577
Evan Cheng23128422010-10-19 18:58:51 +0000578 // Remember livein register pressure.
579 BackTrace.push_back(RegPressure);
580
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000581 for (MachineBasicBlock::iterator
582 MII = BB->begin(), E = BB->end(); MII != E; ) {
583 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
584 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000585 if (!Hoist(MI, Preheader))
586 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000587 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000588 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000589
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000590 // Don't hoist things out of a large switch statement. This often causes
591 // code to be hoisted that wasn't going to be executed, and increases
592 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000593 if (BB->succ_size() < 25) {
594 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000595 for (unsigned I = 0, E = Children.size(); I != E; ++I)
596 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000597 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000598
Evan Cheng23128422010-10-19 18:58:51 +0000599 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000600}
601
Evan Cheng134982d2010-10-20 22:03:58 +0000602static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
603 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
604}
605
Evan Cheng61560e22011-09-01 01:45:00 +0000606/// getRegisterClassIDAndCost - For a given MI, register, and the operand
607/// index, return the ID and cost of its representative register class.
608void
609MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
610 unsigned Reg, unsigned OpIdx,
611 unsigned &RCId, unsigned &RCCost) const {
612 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
613 EVT VT = *RC->vt_begin();
614 if (VT == MVT::untyped) {
615 RCId = RC->getID();
616 RCCost = 1;
617 } else {
618 RCId = TLI->getRepRegClassFor(VT)->getID();
619 RCCost = TLI->getRepRegClassCostFor(VT);
620 }
621}
622
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000623/// InitRegPressure - Find all virtual register references that are liveout of
624/// the preheader to initialize the starting "register pressure". Note this
625/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000626void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000627 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000628
Evan Cheng134982d2010-10-20 22:03:58 +0000629 // If the preheader has only a single predecessor and it ends with a
630 // fallthrough or an unconditional branch, then scan its predecessor for live
631 // defs as well. This happens whenever the preheader is created by splitting
632 // the critical edge from the loop predecessor to the loop header.
633 if (BB->pred_size() == 1) {
634 MachineBasicBlock *TBB = 0, *FBB = 0;
635 SmallVector<MachineOperand, 4> Cond;
636 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
637 InitRegPressure(*BB->pred_begin());
638 }
639
Evan Cheng0e673912010-10-14 01:16:09 +0000640 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
641 MII != E; ++MII) {
642 MachineInstr *MI = &*MII;
643 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
644 const MachineOperand &MO = MI->getOperand(i);
645 if (!MO.isReg() || MO.isImplicit())
646 continue;
647 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000648 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000649 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000650
Andrew Trickdc986d22010-10-19 02:50:50 +0000651 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000652 unsigned RCId, RCCost;
653 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000654 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000655 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000656 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000657 bool isKill = isOperandKill(MO, MRI);
658 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000659 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000660 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000661 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000662 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000663 }
Evan Cheng0e673912010-10-14 01:16:09 +0000664 }
665 }
666}
667
Evan Cheng134982d2010-10-20 22:03:58 +0000668/// UpdateRegPressure - Update estimate of register pressure after the
669/// specified instruction.
670void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
671 if (MI->isImplicitDef())
672 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000673
Evan Cheng134982d2010-10-20 22:03:58 +0000674 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000675 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
676 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000677 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000678 continue;
679 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000680 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000681 continue;
682
Andrew Trickdc986d22010-10-19 02:50:50 +0000683 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000684 if (MO.isDef())
685 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000686 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000687 unsigned RCId, RCCost;
688 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000689 if (RCCost > RegPressure[RCId])
690 RegPressure[RCId] = 0;
691 else
Evan Cheng23128422010-10-19 18:58:51 +0000692 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000693 }
Evan Cheng0e673912010-10-14 01:16:09 +0000694 }
Evan Cheng0e673912010-10-14 01:16:09 +0000695
Evan Cheng61560e22011-09-01 01:45:00 +0000696 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000697 while (!Defs.empty()) {
698 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000699 unsigned RCId, RCCost;
700 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000701 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000702 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000703 }
704}
705
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000706/// IsLICMCandidate - Returns true if the instruction may be a suitable
707/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
708/// not safe to hoist it.
709bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000710 // Check if it's safe to move the instruction.
711 bool DontMoveAcrossStore = true;
712 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000713 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000714
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000715 return true;
716}
717
718/// IsLoopInvariantInst - Returns true if the instruction is loop
719/// invariant. I.e., all virtual register operands are defined outside of the
720/// loop, physical registers aren't accessed explicitly, and there are no side
721/// effects that aren't captured by the operands or other flags.
722///
723bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
724 if (!IsLICMCandidate(I))
725 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000726
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000727 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000728 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
729 const MachineOperand &MO = I.getOperand(i);
730
Dan Gohmand735b802008-10-03 15:45:36 +0000731 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000732 continue;
733
Dan Gohmanc475c362009-01-15 22:01:38 +0000734 unsigned Reg = MO.getReg();
735 if (Reg == 0) continue;
736
737 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000738 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000739 if (MO.isUse()) {
740 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000741 // and we can freely move its uses. Alternatively, if it's allocatable,
742 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000743 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000744 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000745 if (AllocatableSet.test(Reg))
746 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000747 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000748 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
749 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000750 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000751 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000752 if (AllocatableSet.test(AliasReg))
753 return false;
754 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000755 // Otherwise it's safe to move.
756 continue;
757 } else if (!MO.isDead()) {
758 // A def that isn't dead. We can't move it.
759 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000760 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
761 // If the reg is live into the loop, we can't hoist an instruction
762 // which would clobber it.
763 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000764 }
765 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000766
767 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000768 continue;
769
Evan Cheng0e673912010-10-14 01:16:09 +0000770 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000771 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000772
773 // If the loop contains the definition of an operand, then the instruction
774 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000775 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000776 return false;
777 }
778
779 // If we got this far, the instruction is loop invariant!
780 return true;
781}
782
Evan Chengaf6949d2009-02-05 08:45:46 +0000783
Evan Chengd67705f2011-04-11 21:09:18 +0000784/// HasAnyPHIUse - Return true if the specified register is used by any
785/// phi node.
786bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000787 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
788 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000789 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000790 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000791 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000792 // Look pass copies as well.
793 if (UseMI->isCopy()) {
794 unsigned Def = UseMI->getOperand(0).getReg();
795 if (TargetRegisterInfo::isVirtualRegister(Def) &&
796 HasAnyPHIUse(Def))
797 return true;
798 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000799 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000800 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000801}
802
Evan Cheng23128422010-10-19 18:58:51 +0000803/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
804/// and an use in the current loop, return true if the target considered
805/// it 'high'.
806bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000807 unsigned DefIdx, unsigned Reg) const {
808 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000809 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000810
Evan Cheng0e673912010-10-14 01:16:09 +0000811 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
812 E = MRI->use_nodbg_end(); I != E; ++I) {
813 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000814 if (UseMI->isCopyLike())
815 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000816 if (!CurLoop->contains(UseMI->getParent()))
817 continue;
818 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
819 const MachineOperand &MO = UseMI->getOperand(i);
820 if (!MO.isReg() || !MO.isUse())
821 continue;
822 unsigned MOReg = MO.getReg();
823 if (MOReg != Reg)
824 continue;
825
Evan Cheng23128422010-10-19 18:58:51 +0000826 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
827 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000828 }
829
Evan Cheng23128422010-10-19 18:58:51 +0000830 // Only look at the first in loop use.
831 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000832 }
833
Evan Cheng23128422010-10-19 18:58:51 +0000834 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000835}
836
Evan Chengc8141df2010-10-26 02:08:50 +0000837/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
838/// the operand latency between its def and a use is one or less.
839bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
840 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
841 return true;
842 if (!InstrItins || InstrItins->isEmpty())
843 return false;
844
845 bool isCheap = false;
846 unsigned NumDefs = MI.getDesc().getNumDefs();
847 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
848 MachineOperand &DefMO = MI.getOperand(i);
849 if (!DefMO.isReg() || !DefMO.isDef())
850 continue;
851 --NumDefs;
852 unsigned Reg = DefMO.getReg();
853 if (TargetRegisterInfo::isPhysicalRegister(Reg))
854 continue;
855
856 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
857 return false;
858 isCheap = true;
859 }
860
861 return isCheap;
862}
863
Evan Cheng134982d2010-10-20 22:03:58 +0000864/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000865/// if hoisting an instruction of the given cost matrix can cause high
866/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000867bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
868 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
869 CI != CE; ++CI) {
870 if (CI->second <= 0)
871 continue;
872
873 unsigned RCId = CI->first;
874 for (unsigned i = BackTrace.size(); i != 0; --i) {
875 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000876 if (RP[RCId] + CI->second >= RegLimit[RCId])
877 return true;
878 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000879 }
880
881 return false;
882}
883
Evan Cheng134982d2010-10-20 22:03:58 +0000884/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
885/// current block and update their register pressures to reflect the effect
886/// of hoisting MI from the current block to the preheader.
887void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
888 if (MI->isImplicitDef())
889 return;
890
891 // First compute the 'cost' of the instruction, i.e. its contribution
892 // to register pressure.
893 DenseMap<unsigned, int> Cost;
894 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
895 const MachineOperand &MO = MI->getOperand(i);
896 if (!MO.isReg() || MO.isImplicit())
897 continue;
898 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000899 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000900 continue;
901
Evan Cheng61560e22011-09-01 01:45:00 +0000902 unsigned RCId, RCCost;
903 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000904 if (MO.isDef()) {
905 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
906 if (CI != Cost.end())
907 CI->second += RCCost;
908 else
909 Cost.insert(std::make_pair(RCId, RCCost));
910 } else if (isOperandKill(MO, MRI)) {
911 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
912 if (CI != Cost.end())
913 CI->second -= RCCost;
914 else
915 Cost.insert(std::make_pair(RCId, -RCCost));
916 }
917 }
918
919 // Update register pressure of blocks from loop header to current block.
920 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
921 SmallVector<unsigned, 8> &RP = BackTrace[i];
922 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
923 CI != CE; ++CI) {
924 unsigned RCId = CI->first;
925 RP[RCId] += CI->second;
926 }
927 }
928}
929
Evan Cheng45e94d62009-02-04 09:19:56 +0000930/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
931/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000932bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000933 if (MI.isImplicitDef())
934 return true;
935
Evan Cheng23128422010-10-19 18:58:51 +0000936 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
937 // will increase register pressure. It's probably not worth it if the
938 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000939 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
940 // these tend to help performance in low register pressure situation. The
941 // trade off is it may cause spill in high pressure situation. It will end up
942 // adding a store in the loop preheader. But the reload is no more expensive.
943 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000944 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000945 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000946 return false;
947 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000948 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000949 // In low register pressure situation, we can be more aggressive about
950 // hoisting. Also, favors hoisting long latency instructions even in
951 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +0000952 // FIXME: If there are long latency loop-invariant instructions inside the
953 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000954 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000955 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
956 const MachineOperand &MO = MI.getOperand(i);
957 if (!MO.isReg() || MO.isImplicit())
958 continue;
959 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000960 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000961 continue;
Evan Cheng61560e22011-09-01 01:45:00 +0000962
963 unsigned RCId, RCCost;
964 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000965 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000966 if (HasHighOperandLatency(MI, i, Reg)) {
967 ++NumHighLatency;
968 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000969 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000970
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000971 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000972 if (CI != Cost.end())
973 CI->second += RCCost;
974 else
975 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +0000976 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000977 // Is a virtual register use is a kill, hoisting it out of the loop
978 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +0000979 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000980 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) &&
Evan Cheng9fe20092011-01-20 08:34:58 +0000998 !MI.isInvariantLoad(AA))
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 Chengd67705f2011-04-11 21:09:18 +00001002 // If result(s) of this instruction is used by PHIs outside of the loop, then
1003 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001004 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1005 const MachineOperand &MO = MI.getOperand(i);
1006 if (!MO.isReg() || !MO.isDef())
1007 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001008 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001009 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001010 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001011
1012 return true;
1013}
1014
Dan Gohman5c952302009-10-29 17:47:20 +00001015MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001016 // Don't unfold simple loads.
1017 if (MI->getDesc().canFoldAsLoad())
1018 return 0;
1019
Dan Gohman5c952302009-10-29 17:47:20 +00001020 // If not, we may be able to unfold a load and hoist that.
1021 // First test whether the instruction is loading from an amenable
1022 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001023 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001024 return 0;
1025
Dan Gohman5c952302009-10-29 17:47:20 +00001026 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001027 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001028 unsigned NewOpc =
1029 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1030 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001031 /*UnfoldStore=*/false,
1032 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001033 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001034 const MCInstrDesc &MID = TII->get(NewOpc);
1035 if (MID.getNumDefs() != 1) return 0;
1036 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001037 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001038 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001039
1040 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001041 SmallVector<MachineInstr *, 2> NewMIs;
1042 bool Success =
1043 TII->unfoldMemoryOperand(MF, MI, Reg,
1044 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1045 NewMIs);
1046 (void)Success;
1047 assert(Success &&
1048 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1049 "succeeded!");
1050 assert(NewMIs.size() == 2 &&
1051 "Unfolded a load into multiple instructions!");
1052 MachineBasicBlock *MBB = MI->getParent();
1053 MBB->insert(MI, NewMIs[0]);
1054 MBB->insert(MI, NewMIs[1]);
1055 // If unfolding produced a load that wasn't loop-invariant or profitable to
1056 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001057 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001058 NewMIs[0]->eraseFromParent();
1059 NewMIs[1]->eraseFromParent();
1060 return 0;
1061 }
Evan Cheng134982d2010-10-20 22:03:58 +00001062
1063 // Update register pressure for the unfolded instruction.
1064 UpdateRegPressure(NewMIs[1]);
1065
Dan Gohman5c952302009-10-29 17:47:20 +00001066 // Otherwise we successfully unfolded a load that we can hoist.
1067 MI->eraseFromParent();
1068 return NewMIs[0];
1069}
1070
Evan Cheng777c6b72009-11-03 21:40:02 +00001071void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1072 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1073 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001074 unsigned Opcode = MI->getOpcode();
1075 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1076 CI = CSEMap.find(Opcode);
1077 if (CI != CSEMap.end())
1078 CI->second.push_back(MI);
1079 else {
1080 std::vector<const MachineInstr*> CSEMIs;
1081 CSEMIs.push_back(MI);
1082 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001083 }
1084 }
1085}
1086
Evan Cheng78e5c112009-11-07 03:52:02 +00001087const MachineInstr*
1088MachineLICM::LookForDuplicate(const MachineInstr *MI,
1089 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001090 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1091 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001092 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001093 return PrevMI;
1094 }
1095 return 0;
1096}
1097
1098bool MachineLICM::EliminateCSE(MachineInstr *MI,
1099 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001100 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1101 // the undef property onto uses.
1102 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001103 return false;
1104
1105 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001106 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001107
1108 // Replace virtual registers defined by MI by their counterparts defined
1109 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001110 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1111 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001112
1113 // Physical registers may not differ here.
1114 assert((!MO.isReg() || MO.getReg() == 0 ||
1115 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1116 MO.getReg() == Dup->getOperand(i).getReg()) &&
1117 "Instructions with different phys regs are not identical!");
1118
1119 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001120 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001121 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1122 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001123 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001124 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001125 MI->eraseFromParent();
1126 ++NumCSEed;
1127 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001128 }
1129 return false;
1130}
1131
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001132/// Hoist - When an instruction is found to use only loop invariant operands
1133/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001134///
Evan Cheng134982d2010-10-20 22:03:58 +00001135bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001136 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001137 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001138 // If not, try unfolding a hoistable load.
1139 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001140 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001141 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001142
Dan Gohmanc475c362009-01-15 22:01:38 +00001143 // Now move the instructions to the predecessor, inserting it before any
1144 // terminator instructions.
1145 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001146 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001147 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001148 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001149 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001150 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001151 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001152 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001153 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001154 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001155
Evan Cheng777c6b72009-11-03 21:40:02 +00001156 // If this is the first instruction being hoisted to the preheader,
1157 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001158 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001159 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001160 FirstInLoop = false;
1161 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001162
Evan Chengaf6949d2009-02-05 08:45:46 +00001163 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001164 unsigned Opcode = MI->getOpcode();
1165 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1166 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001167 if (!EliminateCSE(MI, CI)) {
1168 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001169 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001170
Evan Cheng134982d2010-10-20 22:03:58 +00001171 // Update register pressure for BBs from header to this block.
1172 UpdateBackTraceRegPressure(MI);
1173
Dan Gohmane6cd7572010-05-13 20:34:42 +00001174 // Clear the kill flags of any register this instruction defines,
1175 // since they may need to be live throughout the entire loop
1176 // rather than just live for part of it.
1177 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1178 MachineOperand &MO = MI->getOperand(i);
1179 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001180 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001181 }
1182
Evan Chengaf6949d2009-02-05 08:45:46 +00001183 // Add to the CSE map.
1184 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001185 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001186 else {
1187 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001188 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001189 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001190 }
1191 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001192
Dan Gohmanc475c362009-01-15 22:01:38 +00001193 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001194 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001195
1196 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001197}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001198
1199MachineBasicBlock *MachineLICM::getCurPreheader() {
1200 // Determine the block to which to hoist instructions. If we can't find a
1201 // suitable loop predecessor, we can't do any hoisting.
1202
1203 // If we've tried to get a preheader and failed, don't try again.
1204 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1205 return 0;
1206
1207 if (!CurPreheader) {
1208 CurPreheader = CurLoop->getLoopPreheader();
1209 if (!CurPreheader) {
1210 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1211 if (!Pred) {
1212 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1213 return 0;
1214 }
1215
1216 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1217 if (!CurPreheader) {
1218 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1219 return 0;
1220 }
1221 }
1222 }
1223 return CurPreheader;
1224}