blob: bd25b2c6b6ad48c22ad7a22a2793367d08b3cf9e [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
Devang Patel9ac743a2011-10-10 19:09:20 +0000171 /// IsGuaranteedToExecute - check to make sure that the MI dominates
172 /// all of the exit blocks. If it doesn't, then there is a path out of the
173 /// loop which does not execute this instruction, so we can't hoist it.
174 bool IsGuaranteedToExecute(MachineInstr *MI);
175
Evan Chengd67705f2011-04-11 21:09:18 +0000176 /// HasAnyPHIUse - Return true if the specified register is used by any
177 /// phi node.
178 bool HasAnyPHIUse(unsigned Reg) const;
179
Evan Cheng23128422010-10-19 18:58:51 +0000180 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
181 /// and an use in the current loop, return true if the target considered
182 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000183 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
184 unsigned Reg) const;
185
186 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000187
Evan Cheng134982d2010-10-20 22:03:58 +0000188 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
189 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000190 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000191 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
192
193 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
194 /// the current block and update their register pressures to reflect the
195 /// effect of hoisting MI from the current block to the preheader.
196 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000197
Evan Cheng45e94d62009-02-04 09:19:56 +0000198 /// IsProfitableToHoist - Return true if it is potentially profitable to
199 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000200 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000201
Bill Wendling0f940c92007-12-07 21:42:31 +0000202 /// HoistRegion - Walk the specified region of the CFG (defined by all
203 /// blocks dominated by the specified block, and that are in the current
204 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
205 /// visit definitions before uses, allowing us to hoist a loop body in one
206 /// pass without iteration.
207 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000208 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000209
Evan Cheng61560e22011-09-01 01:45:00 +0000210 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
211 /// index, return the ID and cost of its representative register class by
212 /// reference.
213 void getRegisterClassIDAndCost(const MachineInstr *MI,
214 unsigned Reg, unsigned OpIdx,
215 unsigned &RCId, unsigned &RCCost) const;
216
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000217 /// InitRegPressure - Find all virtual register references that are liveout
218 /// of the preheader to initialize the starting "register pressure". Note
219 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000220 void InitRegPressure(MachineBasicBlock *BB);
221
Evan Cheng134982d2010-10-20 22:03:58 +0000222 /// UpdateRegPressure - Update estimate of register pressure after the
223 /// specified instruction.
224 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000225
Dan Gohman5c952302009-10-29 17:47:20 +0000226 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
227 /// the load itself could be hoisted. Return the unfolded and hoistable
228 /// load, or null if the load couldn't be unfolded or if it wouldn't
229 /// be hoistable.
230 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
231
Evan Cheng78e5c112009-11-07 03:52:02 +0000232 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
233 /// duplicate of MI. Return this instruction if it's found.
234 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
235 std::vector<const MachineInstr*> &PrevMIs);
236
Evan Cheng9fb744e2009-11-05 00:51:13 +0000237 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
238 /// the preheader that compute the same value. If it's found, do a RAU on
239 /// with the definition of the existing instruction rather than hoisting
240 /// the instruction to the preheader.
241 bool EliminateCSE(MachineInstr *MI,
242 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
243
Bill Wendling0f940c92007-12-07 21:42:31 +0000244 /// Hoist - When an instruction is found to only use loop invariant operands
245 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000246 /// It returns true if the instruction is hoisted.
247 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000248
249 /// InitCSEMap - Initialize the CSE map with instructions that are in the
250 /// current loop preheader that may become duplicates of instructions that
251 /// are hoisted out of the loop.
252 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000253
254 /// getCurPreheader - Get the preheader for the current loop, splitting
255 /// a critical edge if needed.
256 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000257 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000258} // end anonymous namespace
259
Dan Gohman844731a2008-05-13 00:00:25 +0000260char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000261INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
262 "Machine Loop Invariant Code Motion", false, false)
263INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
264INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
265INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
266INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000267 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000268
Evan Chengd94671a2010-04-07 00:41:17 +0000269FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
270 return new MachineLICM(PreRegAlloc);
271}
Bill Wendling0f940c92007-12-07 21:42:31 +0000272
Dan Gohman853d3fb2010-06-22 17:25:57 +0000273/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
274/// loop that has a unique predecessor.
275static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000276 // Check whether this loop even has a unique predecessor.
277 if (!CurLoop->getLoopPredecessor())
278 return false;
279 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000280 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000281 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000282 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000283 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000284 return true;
285}
286
Bill Wendling0f940c92007-12-07 21:42:31 +0000287bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000288 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000289 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000290 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000291 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
292 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000293
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000294 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000295 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000296 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000297 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000298 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000299 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000300 MRI = &MF.getRegInfo();
301 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000302 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000303
Evan Cheng0e673912010-10-14 01:16:09 +0000304 if (PreRegAlloc) {
305 // Estimate register pressure during pre-regalloc pass.
306 unsigned NumRC = TRI->getNumRegClasses();
307 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000308 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000309 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000310 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
311 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000312 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000313 }
314
Bill Wendling0f940c92007-12-07 21:42:31 +0000315 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000316 MLI = &getAnalysis<MachineLoopInfo>();
317 DT = &getAnalysis<MachineDominatorTree>();
318 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000319
Dan Gohmanaa742602010-07-09 18:49:45 +0000320 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
321 while (!Worklist.empty()) {
322 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000323 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000324
Evan Cheng4038f9c2010-04-08 01:03:47 +0000325 // If this is done before regalloc, only visit outer-most preheader-sporting
326 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000327 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
328 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000329 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000330 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000331
Evan Chengd94671a2010-04-07 00:41:17 +0000332 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000333 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000334 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000335 // CSEMap is initialized for loop header when the first instruction is
336 // being hoisted.
337 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000338 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000339 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000340 CSEMap.clear();
341 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000342 }
343
344 return Changed;
345}
346
Evan Cheng4038f9c2010-04-08 01:03:47 +0000347/// InstructionStoresToFI - Return true if instruction stores to the
348/// specified frame.
349static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
350 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
351 oe = MI->memoperands_end(); o != oe; ++o) {
352 if (!(*o)->isStore() || !(*o)->getValue())
353 continue;
354 if (const FixedStackPseudoSourceValue *Value =
355 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
356 if (Value->getFrameIndex() == FI)
357 return true;
358 }
359 }
360 return false;
361}
362
363/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
364/// gather register def and frame object update information.
365void MachineLICM::ProcessMI(MachineInstr *MI,
366 unsigned *PhysRegDefs,
367 SmallSet<int, 32> &StoredFIs,
368 SmallVector<CandidateInfo, 32> &Candidates) {
369 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000370 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000371 unsigned Def = 0;
372 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
373 const MachineOperand &MO = MI->getOperand(i);
374 if (MO.isFI()) {
375 // Remember if the instruction stores to the frame index.
376 int FI = MO.getIndex();
377 if (!StoredFIs.count(FI) &&
378 MFI->isSpillSlotObjectIndex(FI) &&
379 InstructionStoresToFI(MI, FI))
380 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000381 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000382 continue;
383 }
384
385 if (!MO.isReg())
386 continue;
387 unsigned Reg = MO.getReg();
388 if (!Reg)
389 continue;
390 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
391 "Not expecting virtual register!");
392
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000393 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000394 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000395 // If it's using a non-loop-invariant register, then it's obviously not
396 // safe to hoist.
397 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000398 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000399 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000400
401 if (MO.isImplicit()) {
402 ++PhysRegDefs[Reg];
403 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
404 ++PhysRegDefs[*AS];
405 if (!MO.isDead())
406 // Non-dead implicit def? This cannot be hoisted.
407 RuledOut = true;
408 // No need to check if a dead implicit def is also defined by
409 // another instruction.
410 continue;
411 }
412
413 // FIXME: For now, avoid instructions with multiple defs, unless
414 // it's a dead implicit def.
415 if (Def)
416 RuledOut = true;
417 else
418 Def = Reg;
419
420 // If we have already seen another instruction that defines the same
421 // register, then this is not safe.
422 if (++PhysRegDefs[Reg] > 1)
423 // MI defined register is seen defined by another instruction in
424 // the loop, it cannot be a LICM candidate.
425 RuledOut = true;
426 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
427 if (++PhysRegDefs[*AS] > 1)
428 RuledOut = true;
429 }
430
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000431 // Only consider reloads for now and remats which do not have register
432 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000433 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000434 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000435 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000436 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
437 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000438 }
439}
440
441/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
442/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000443void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000444 unsigned NumRegs = TRI->getNumRegs();
445 unsigned *PhysRegDefs = new unsigned[NumRegs];
446 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
447
Evan Cheng4038f9c2010-04-08 01:03:47 +0000448 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000449 SmallSet<int, 32> StoredFIs;
450
451 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000452 // collect potential LICM candidates.
453 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
454 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
455 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000456 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000457 // FIXME: That means a reload that're reused in successor block(s) will not
458 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000459 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000460 E = BB->livein_end(); I != E; ++I) {
461 unsigned Reg = *I;
462 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000463 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
464 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000465 }
466
467 for (MachineBasicBlock::iterator
468 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000469 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000470 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000471 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000472 }
Evan Chengd94671a2010-04-07 00:41:17 +0000473
474 // Now evaluate whether the potential candidates qualify.
475 // 1. Check if the candidate defined register is defined by another
476 // instruction in the loop.
477 // 2. If the candidate is a load from stack slot (always true for now),
478 // check if the slot is stored anywhere in the loop.
479 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000480 if (Candidates[i].FI != INT_MIN &&
481 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000482 continue;
483
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000484 if (PhysRegDefs[Candidates[i].Def] == 1) {
485 bool Safe = true;
486 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000487 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
488 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000489 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000490 continue;
491 if (PhysRegDefs[MO.getReg()]) {
492 // If it's using a non-loop-invariant register, then it's obviously
493 // not safe to hoist.
494 Safe = false;
495 break;
496 }
497 }
498 if (Safe)
499 HoistPostRA(MI, Candidates[i].Def);
500 }
Evan Chengd94671a2010-04-07 00:41:17 +0000501 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000502
503 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000504}
505
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000506/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
507/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000508void MachineLICM::AddToLiveIns(unsigned Reg) {
509 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000510 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
511 MachineBasicBlock *BB = Blocks[i];
512 if (!BB->isLiveIn(Reg))
513 BB->addLiveIn(Reg);
514 for (MachineBasicBlock::iterator
515 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
516 MachineInstr *MI = &*MII;
517 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
518 MachineOperand &MO = MI->getOperand(i);
519 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
520 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
521 MO.setIsKill(false);
522 }
523 }
524 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000525}
526
527/// HoistPostRA - When an instruction is found to only use loop invariant
528/// operands that is safe to hoist, this instruction is called to do the
529/// dirty work.
530void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000531 MachineBasicBlock *Preheader = getCurPreheader();
532 if (!Preheader) return;
533
Evan Chengd94671a2010-04-07 00:41:17 +0000534 // Now move the instructions to the predecessor, inserting it before any
535 // terminator instructions.
536 DEBUG({
537 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000538 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000539 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000540 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000541 if (MI->getParent()->getBasicBlock())
542 dbgs() << " from MachineBasicBlock "
543 << MI->getParent()->getName();
544 dbgs() << "\n";
545 });
546
547 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000548 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000549 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000550
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000551 // Add register to livein list to all the BBs in the current loop since a
552 // loop invariant must be kept live throughout the whole loop. This is
553 // important to ensure later passes do not scavenge the def register.
554 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000555
556 ++NumPostRAHoisted;
557 Changed = true;
558}
559
Bill Wendling0f940c92007-12-07 21:42:31 +0000560/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
561/// dominated by the specified block, and that are in the current loop) in depth
562/// first order w.r.t the DominatorTree. This allows us to visit definitions
563/// before uses, allowing us to hoist a loop body in one pass without iteration.
564///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000565void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000566 assert(N != 0 && "Null dominator tree node?");
567 MachineBasicBlock *BB = N->getBlock();
568
569 // If this subregion is not in the top level loop at all, exit.
570 if (!CurLoop->contains(BB)) return;
571
Evan Cheng0e673912010-10-14 01:16:09 +0000572 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000573 if (!Preheader)
574 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000575
Evan Cheng23128422010-10-19 18:58:51 +0000576 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000577 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000578 RegSeen.clear();
579 BackTrace.clear();
580 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000581 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000582
Evan Cheng23128422010-10-19 18:58:51 +0000583 // Remember livein register pressure.
584 BackTrace.push_back(RegPressure);
585
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000586 for (MachineBasicBlock::iterator
587 MII = BB->begin(), E = BB->end(); MII != E; ) {
588 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
589 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000590 if (!Hoist(MI, Preheader))
591 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000592 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000593 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000594
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000595 // Don't hoist things out of a large switch statement. This often causes
596 // code to be hoisted that wasn't going to be executed, and increases
597 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000598 if (BB->succ_size() < 25) {
599 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000600 for (unsigned I = 0, E = Children.size(); I != E; ++I)
601 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000602 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000603
Evan Cheng23128422010-10-19 18:58:51 +0000604 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000605}
606
Evan Cheng134982d2010-10-20 22:03:58 +0000607static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
608 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
609}
610
Evan Cheng61560e22011-09-01 01:45:00 +0000611/// getRegisterClassIDAndCost - For a given MI, register, and the operand
612/// index, return the ID and cost of its representative register class.
613void
614MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
615 unsigned Reg, unsigned OpIdx,
616 unsigned &RCId, unsigned &RCCost) const {
617 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
618 EVT VT = *RC->vt_begin();
619 if (VT == MVT::untyped) {
620 RCId = RC->getID();
621 RCCost = 1;
622 } else {
623 RCId = TLI->getRepRegClassFor(VT)->getID();
624 RCCost = TLI->getRepRegClassCostFor(VT);
625 }
626}
627
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000628/// InitRegPressure - Find all virtual register references that are liveout of
629/// the preheader to initialize the starting "register pressure". Note this
630/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000631void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000632 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000633
Evan Cheng134982d2010-10-20 22:03:58 +0000634 // If the preheader has only a single predecessor and it ends with a
635 // fallthrough or an unconditional branch, then scan its predecessor for live
636 // defs as well. This happens whenever the preheader is created by splitting
637 // the critical edge from the loop predecessor to the loop header.
638 if (BB->pred_size() == 1) {
639 MachineBasicBlock *TBB = 0, *FBB = 0;
640 SmallVector<MachineOperand, 4> Cond;
641 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
642 InitRegPressure(*BB->pred_begin());
643 }
644
Evan Cheng0e673912010-10-14 01:16:09 +0000645 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
646 MII != E; ++MII) {
647 MachineInstr *MI = &*MII;
648 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
649 const MachineOperand &MO = MI->getOperand(i);
650 if (!MO.isReg() || MO.isImplicit())
651 continue;
652 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000653 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000654 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000655
Andrew Trickdc986d22010-10-19 02:50:50 +0000656 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000657 unsigned RCId, RCCost;
658 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000659 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000660 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000661 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000662 bool isKill = isOperandKill(MO, MRI);
663 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000664 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000665 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000666 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000667 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000668 }
Evan Cheng0e673912010-10-14 01:16:09 +0000669 }
670 }
671}
672
Evan Cheng134982d2010-10-20 22:03:58 +0000673/// UpdateRegPressure - Update estimate of register pressure after the
674/// specified instruction.
675void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
676 if (MI->isImplicitDef())
677 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000678
Evan Cheng134982d2010-10-20 22:03:58 +0000679 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000680 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
681 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000682 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000683 continue;
684 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000685 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000686 continue;
687
Andrew Trickdc986d22010-10-19 02:50:50 +0000688 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000689 if (MO.isDef())
690 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000691 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000692 unsigned RCId, RCCost;
693 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000694 if (RCCost > RegPressure[RCId])
695 RegPressure[RCId] = 0;
696 else
Evan Cheng23128422010-10-19 18:58:51 +0000697 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000698 }
Evan Cheng0e673912010-10-14 01:16:09 +0000699 }
Evan Cheng0e673912010-10-14 01:16:09 +0000700
Evan Cheng61560e22011-09-01 01:45:00 +0000701 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000702 while (!Defs.empty()) {
703 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000704 unsigned RCId, RCCost;
705 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000706 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000707 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000708 }
709}
710
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000711/// IsLICMCandidate - Returns true if the instruction may be a suitable
712/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
713/// not safe to hoist it.
714bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000715 // Check if it's safe to move the instruction.
716 bool DontMoveAcrossStore = true;
717 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000718 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000719
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000720 return true;
721}
722
723/// IsLoopInvariantInst - Returns true if the instruction is loop
724/// invariant. I.e., all virtual register operands are defined outside of the
725/// loop, physical registers aren't accessed explicitly, and there are no side
726/// effects that aren't captured by the operands or other flags.
727///
728bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
729 if (!IsLICMCandidate(I))
730 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000731
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000732 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000733 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
734 const MachineOperand &MO = I.getOperand(i);
735
Dan Gohmand735b802008-10-03 15:45:36 +0000736 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000737 continue;
738
Dan Gohmanc475c362009-01-15 22:01:38 +0000739 unsigned Reg = MO.getReg();
740 if (Reg == 0) continue;
741
742 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000743 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000744 if (MO.isUse()) {
745 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000746 // and we can freely move its uses. Alternatively, if it's allocatable,
747 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000748 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000749 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000750 if (AllocatableSet.test(Reg))
751 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000752 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000753 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
754 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000755 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000756 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000757 if (AllocatableSet.test(AliasReg))
758 return false;
759 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000760 // Otherwise it's safe to move.
761 continue;
762 } else if (!MO.isDead()) {
763 // A def that isn't dead. We can't move it.
764 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000765 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
766 // If the reg is live into the loop, we can't hoist an instruction
767 // which would clobber it.
768 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000769 }
770 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000771
772 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000773 continue;
774
Evan Cheng0e673912010-10-14 01:16:09 +0000775 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000776 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000777
778 // If the loop contains the definition of an operand, then the instruction
779 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000780 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000781 return false;
782 }
783
784 // If we got this far, the instruction is loop invariant!
785 return true;
786}
787
Evan Chengaf6949d2009-02-05 08:45:46 +0000788
Evan Chengd67705f2011-04-11 21:09:18 +0000789/// HasAnyPHIUse - Return true if the specified register is used by any
790/// phi node.
791bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000792 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
793 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000794 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000795 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000796 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000797 // Look pass copies as well.
798 if (UseMI->isCopy()) {
799 unsigned Def = UseMI->getOperand(0).getReg();
800 if (TargetRegisterInfo::isVirtualRegister(Def) &&
801 HasAnyPHIUse(Def))
802 return true;
803 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000804 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000805 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000806}
807
Evan Cheng23128422010-10-19 18:58:51 +0000808/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
809/// and an use in the current loop, return true if the target considered
810/// it 'high'.
811bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000812 unsigned DefIdx, unsigned Reg) const {
813 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000814 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000815
Evan Cheng0e673912010-10-14 01:16:09 +0000816 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
817 E = MRI->use_nodbg_end(); I != E; ++I) {
818 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000819 if (UseMI->isCopyLike())
820 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000821 if (!CurLoop->contains(UseMI->getParent()))
822 continue;
823 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
824 const MachineOperand &MO = UseMI->getOperand(i);
825 if (!MO.isReg() || !MO.isUse())
826 continue;
827 unsigned MOReg = MO.getReg();
828 if (MOReg != Reg)
829 continue;
830
Evan Cheng23128422010-10-19 18:58:51 +0000831 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
832 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000833 }
834
Evan Cheng23128422010-10-19 18:58:51 +0000835 // Only look at the first in loop use.
836 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000837 }
838
Evan Cheng23128422010-10-19 18:58:51 +0000839 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000840}
841
Evan Chengc8141df2010-10-26 02:08:50 +0000842/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
843/// the operand latency between its def and a use is one or less.
844bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
845 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
846 return true;
847 if (!InstrItins || InstrItins->isEmpty())
848 return false;
849
850 bool isCheap = false;
851 unsigned NumDefs = MI.getDesc().getNumDefs();
852 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
853 MachineOperand &DefMO = MI.getOperand(i);
854 if (!DefMO.isReg() || !DefMO.isDef())
855 continue;
856 --NumDefs;
857 unsigned Reg = DefMO.getReg();
858 if (TargetRegisterInfo::isPhysicalRegister(Reg))
859 continue;
860
861 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
862 return false;
863 isCheap = true;
864 }
865
866 return isCheap;
867}
868
Evan Cheng134982d2010-10-20 22:03:58 +0000869/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000870/// if hoisting an instruction of the given cost matrix can cause high
871/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000872bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
873 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
874 CI != CE; ++CI) {
875 if (CI->second <= 0)
876 continue;
877
878 unsigned RCId = CI->first;
879 for (unsigned i = BackTrace.size(); i != 0; --i) {
880 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000881 if (RP[RCId] + CI->second >= RegLimit[RCId])
882 return true;
883 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000884 }
885
886 return false;
887}
888
Evan Cheng134982d2010-10-20 22:03:58 +0000889/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
890/// current block and update their register pressures to reflect the effect
891/// of hoisting MI from the current block to the preheader.
892void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
893 if (MI->isImplicitDef())
894 return;
895
896 // First compute the 'cost' of the instruction, i.e. its contribution
897 // to register pressure.
898 DenseMap<unsigned, int> Cost;
899 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
900 const MachineOperand &MO = MI->getOperand(i);
901 if (!MO.isReg() || MO.isImplicit())
902 continue;
903 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000904 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000905 continue;
906
Evan Cheng61560e22011-09-01 01:45:00 +0000907 unsigned RCId, RCCost;
908 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000909 if (MO.isDef()) {
910 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
911 if (CI != Cost.end())
912 CI->second += RCCost;
913 else
914 Cost.insert(std::make_pair(RCId, RCCost));
915 } else if (isOperandKill(MO, MRI)) {
916 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
917 if (CI != Cost.end())
918 CI->second -= RCCost;
919 else
920 Cost.insert(std::make_pair(RCId, -RCCost));
921 }
922 }
923
924 // Update register pressure of blocks from loop header to current block.
925 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
926 SmallVector<unsigned, 8> &RP = BackTrace[i];
927 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
928 CI != CE; ++CI) {
929 unsigned RCId = CI->first;
930 RP[RCId] += CI->second;
931 }
932 }
933}
934
Evan Cheng45e94d62009-02-04 09:19:56 +0000935/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
936/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000937bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000938 if (MI.isImplicitDef())
939 return true;
940
Evan Cheng23128422010-10-19 18:58:51 +0000941 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
942 // will increase register pressure. It's probably not worth it if the
943 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000944 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
945 // these tend to help performance in low register pressure situation. The
946 // trade off is it may cause spill in high pressure situation. It will end up
947 // adding a store in the loop preheader. But the reload is no more expensive.
948 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000949 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000950 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000951 return false;
952 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000953 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000954 // In low register pressure situation, we can be more aggressive about
955 // hoisting. Also, favors hoisting long latency instructions even in
956 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +0000957 // FIXME: If there are long latency loop-invariant instructions inside the
958 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000959 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000960 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
961 const MachineOperand &MO = MI.getOperand(i);
962 if (!MO.isReg() || MO.isImplicit())
963 continue;
964 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000965 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000966 continue;
Evan Cheng61560e22011-09-01 01:45:00 +0000967
968 unsigned RCId, RCCost;
969 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000970 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000971 if (HasHighOperandLatency(MI, i, Reg)) {
972 ++NumHighLatency;
973 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000974 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000975
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000976 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000977 if (CI != Cost.end())
978 CI->second += RCCost;
979 else
980 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +0000981 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000982 // Is a virtual register use is a kill, hoisting it out of the loop
983 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +0000984 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000985 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
986 if (CI != Cost.end())
987 CI->second -= RCCost;
988 else
989 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000990 }
991 }
992
Evan Cheng134982d2010-10-20 22:03:58 +0000993 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000994 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +0000995 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000996 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000997 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000998 }
Evan Cheng0e673912010-10-14 01:16:09 +0000999
1000 // High register pressure situation, only hoist if the instruction is going to
1001 // be remat'ed.
1002 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
Evan Cheng9fe20092011-01-20 08:34:58 +00001003 !MI.isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001004 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001005 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001006
Evan Chengd67705f2011-04-11 21:09:18 +00001007 // If result(s) of this instruction is used by PHIs outside of the loop, then
1008 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001009 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1010 const MachineOperand &MO = MI.getOperand(i);
1011 if (!MO.isReg() || !MO.isDef())
1012 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001013 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001014 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001015 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001016
1017 return true;
1018}
1019
Dan Gohman5c952302009-10-29 17:47:20 +00001020MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001021 // Don't unfold simple loads.
1022 if (MI->getDesc().canFoldAsLoad())
1023 return 0;
1024
Dan Gohman5c952302009-10-29 17:47:20 +00001025 // If not, we may be able to unfold a load and hoist that.
1026 // First test whether the instruction is loading from an amenable
1027 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001028 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001029 return 0;
1030
Dan Gohman5c952302009-10-29 17:47:20 +00001031 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001032 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001033 unsigned NewOpc =
1034 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1035 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001036 /*UnfoldStore=*/false,
1037 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001038 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001039 const MCInstrDesc &MID = TII->get(NewOpc);
1040 if (MID.getNumDefs() != 1) return 0;
1041 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001042 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001043 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001044
1045 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001046 SmallVector<MachineInstr *, 2> NewMIs;
1047 bool Success =
1048 TII->unfoldMemoryOperand(MF, MI, Reg,
1049 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1050 NewMIs);
1051 (void)Success;
1052 assert(Success &&
1053 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1054 "succeeded!");
1055 assert(NewMIs.size() == 2 &&
1056 "Unfolded a load into multiple instructions!");
1057 MachineBasicBlock *MBB = MI->getParent();
1058 MBB->insert(MI, NewMIs[0]);
1059 MBB->insert(MI, NewMIs[1]);
1060 // If unfolding produced a load that wasn't loop-invariant or profitable to
1061 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001062 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001063 NewMIs[0]->eraseFromParent();
1064 NewMIs[1]->eraseFromParent();
1065 return 0;
1066 }
Evan Cheng134982d2010-10-20 22:03:58 +00001067
1068 // Update register pressure for the unfolded instruction.
1069 UpdateRegPressure(NewMIs[1]);
1070
Dan Gohman5c952302009-10-29 17:47:20 +00001071 // Otherwise we successfully unfolded a load that we can hoist.
1072 MI->eraseFromParent();
1073 return NewMIs[0];
1074}
1075
Evan Cheng777c6b72009-11-03 21:40:02 +00001076void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1077 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1078 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001079 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));
Evan Cheng777c6b72009-11-03 21:40:02 +00001088 }
1089 }
1090}
1091
Evan Cheng78e5c112009-11-07 03:52:02 +00001092const MachineInstr*
1093MachineLICM::LookForDuplicate(const MachineInstr *MI,
1094 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001095 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1096 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001097 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001098 return PrevMI;
1099 }
1100 return 0;
1101}
1102
1103bool MachineLICM::EliminateCSE(MachineInstr *MI,
1104 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001105 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1106 // the undef property onto uses.
1107 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001108 return false;
1109
1110 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001111 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001112
1113 // Replace virtual registers defined by MI by their counterparts defined
1114 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001115 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1116 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001117
1118 // Physical registers may not differ here.
1119 assert((!MO.isReg() || MO.getReg() == 0 ||
1120 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1121 MO.getReg() == Dup->getOperand(i).getReg()) &&
1122 "Instructions with different phys regs are not identical!");
1123
1124 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001125 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001126 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1127 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001128 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001129 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001130 MI->eraseFromParent();
1131 ++NumCSEed;
1132 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001133 }
1134 return false;
1135}
1136
Devang Patel9ac743a2011-10-10 19:09:20 +00001137/// IsGuaranteedToExecute - check to make sure that the instruction dominates
1138/// all of the exit blocks. If it doesn't, then there is a path out of the loop
1139/// which does not execute this instruction, so we can't hoist it.
1140bool MachineLICM::IsGuaranteedToExecute(MachineInstr *MI) {
1141 // If the instruction is in the header block for the loop (which is very
1142 // common), it is always guaranteed to dominate the exit blocks. Since this
1143 // is a common case, and can save some work, check it now.
1144 if (MI->getParent() == CurLoop->getHeader())
1145 return true;
1146
1147 // Get the exit blocks for the current loop.
Devang Patel6b50bc92011-10-10 20:32:03 +00001148 SmallVector<MachineBasicBlock*, 8> ExitingBlocks;
1149 CurLoop->getExitingBlocks(ExitingBlocks);
Devang Patel9ac743a2011-10-10 19:09:20 +00001150
1151 // Verify that the block dominates each of the exit blocks of the loop.
Devang Patel6b50bc92011-10-10 20:32:03 +00001152 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i)
1153 if (!DT->dominates(MI->getParent(), ExitingBlocks[i]))
Devang Patel9ac743a2011-10-10 19:09:20 +00001154 return false;
1155
1156 return true;
1157}
1158
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001159/// Hoist - When an instruction is found to use only loop invariant operands
1160/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001161///
Evan Cheng134982d2010-10-20 22:03:58 +00001162bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001163 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001164 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001165 // If not, try unfolding a hoistable load.
1166 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001167 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001168 }
Devang Patel9ac743a2011-10-10 19:09:20 +00001169 if (!IsGuaranteedToExecute(MI))
1170 return false;
Bill Wendling0f940c92007-12-07 21:42:31 +00001171
Dan Gohmanc475c362009-01-15 22:01:38 +00001172 // Now move the instructions to the predecessor, inserting it before any
1173 // terminator instructions.
1174 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001175 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001176 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001177 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001178 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001179 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001180 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001181 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001182 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001183 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001184
Evan Cheng777c6b72009-11-03 21:40:02 +00001185 // If this is the first instruction being hoisted to the preheader,
1186 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001187 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001188 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001189 FirstInLoop = false;
1190 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001191
Evan Chengaf6949d2009-02-05 08:45:46 +00001192 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001193 unsigned Opcode = MI->getOpcode();
1194 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1195 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001196 if (!EliminateCSE(MI, CI)) {
1197 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001198 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001199
Evan Cheng134982d2010-10-20 22:03:58 +00001200 // Update register pressure for BBs from header to this block.
1201 UpdateBackTraceRegPressure(MI);
1202
Dan Gohmane6cd7572010-05-13 20:34:42 +00001203 // Clear the kill flags of any register this instruction defines,
1204 // since they may need to be live throughout the entire loop
1205 // rather than just live for part of it.
1206 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1207 MachineOperand &MO = MI->getOperand(i);
1208 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001209 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001210 }
1211
Evan Chengaf6949d2009-02-05 08:45:46 +00001212 // Add to the CSE map.
1213 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001214 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001215 else {
1216 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001217 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001218 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001219 }
1220 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001221
Dan Gohmanc475c362009-01-15 22:01:38 +00001222 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001223 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001224
1225 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001226}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001227
1228MachineBasicBlock *MachineLICM::getCurPreheader() {
1229 // Determine the block to which to hoist instructions. If we can't find a
1230 // suitable loop predecessor, we can't do any hoisting.
1231
1232 // If we've tried to get a preheader and failed, don't try again.
1233 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1234 return 0;
1235
1236 if (!CurPreheader) {
1237 CurPreheader = CurLoop->getLoopPreheader();
1238 if (!CurPreheader) {
1239 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1240 if (!Pred) {
1241 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1242 return 0;
1243 }
1244
1245 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1246 if (!CurPreheader) {
1247 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1248 return 0;
1249 }
1250 }
1251 }
1252 return CurPreheader;
1253}