blob: 63c73d2e4ec379b27f4734419609cd5a3d7dd4af [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
Evan Chengfad62872011-10-11 23:48:44 +000094 enum {
95 SpeculateFalse = 0,
96 SpeculateTrue = 1,
97 SpeculateUnknown = 2
98 };
99
Devang Patel2e350472011-10-11 18:09:58 +0000100 // If a MBB does not dominate loop exiting blocks then it may not safe
101 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000102 // Tri-state: 0 - false, 1 - true, 2 - unknown
103 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000104
Bill Wendling0f940c92007-12-07 21:42:31 +0000105 public:
106 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000107 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000108 MachineFunctionPass(ID), PreRegAlloc(true) {
109 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
110 }
Evan Chengd94671a2010-04-07 00:41:17 +0000111
112 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000113 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
114 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
115 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000116
117 virtual bool runOnMachineFunction(MachineFunction &MF);
118
Dan Gohman72241702008-12-18 01:37:56 +0000119 const char *getPassName() const { return "Machine Instruction LICM"; }
120
Bill Wendling0f940c92007-12-07 21:42:31 +0000121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000122 AU.addRequired<MachineLoopInfo>();
123 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000124 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000125 AU.addPreserved<MachineLoopInfo>();
126 AU.addPreserved<MachineDominatorTree>();
127 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000128 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000129
130 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000131 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000132 RegPressure.clear();
133 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000134 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000135 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
136 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
137 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000138 CSEMap.clear();
139 }
140
Bill Wendling0f940c92007-12-07 21:42:31 +0000141 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000142 /// CandidateInfo - Keep track of information about hoisting candidates.
143 struct CandidateInfo {
144 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000145 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000146 int FI;
147 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
148 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000149 };
150
151 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
152 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000153 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000154
155 /// HoistPostRA - When an instruction is found to only use loop invariant
156 /// operands that is safe to hoist, this instruction is called to do the
157 /// dirty work.
158 void HoistPostRA(MachineInstr *MI, unsigned Def);
159
160 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
161 /// gather register def and frame object update information.
162 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
163 SmallSet<int, 32> &StoredFIs,
164 SmallVector<CandidateInfo, 32> &Candidates);
165
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000166 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
167 /// current loop.
168 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000169
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000170 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000171 /// candidate for LICM. e.g. If the instruction is a call, then it's
172 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000173 bool IsLICMCandidate(MachineInstr &I);
174
Bill Wendling041b3f82007-12-08 23:58:46 +0000175 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000176 /// invariant. I.e., all virtual register operands are defined outside of
177 /// the loop, physical registers aren't accessed (explicitly or implicitly),
178 /// and the instruction is hoistable.
179 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000180 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000181
Evan Chengd67705f2011-04-11 21:09:18 +0000182 /// HasAnyPHIUse - Return true if the specified register is used by any
183 /// phi node.
184 bool HasAnyPHIUse(unsigned Reg) const;
185
Evan Cheng23128422010-10-19 18:58:51 +0000186 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
187 /// and an use in the current loop, return true if the target considered
188 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000189 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
190 unsigned Reg) const;
191
192 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000193
Evan Cheng134982d2010-10-20 22:03:58 +0000194 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
195 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000196 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000197 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
198
199 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
200 /// the current block and update their register pressures to reflect the
201 /// effect of hoisting MI from the current block to the preheader.
202 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000203
Evan Cheng45e94d62009-02-04 09:19:56 +0000204 /// IsProfitableToHoist - Return true if it is potentially profitable to
205 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000206 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000207
Devang Patel2e350472011-10-11 18:09:58 +0000208 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
209 /// If not then a load from this mbb may not be safe to hoist.
210 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
211
Bill Wendling0f940c92007-12-07 21:42:31 +0000212 /// HoistRegion - Walk the specified region of the CFG (defined by all
213 /// blocks dominated by the specified block, and that are in the current
214 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
215 /// visit definitions before uses, allowing us to hoist a loop body in one
216 /// pass without iteration.
217 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000218 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000219
Evan Cheng61560e22011-09-01 01:45:00 +0000220 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
221 /// index, return the ID and cost of its representative register class by
222 /// reference.
223 void getRegisterClassIDAndCost(const MachineInstr *MI,
224 unsigned Reg, unsigned OpIdx,
225 unsigned &RCId, unsigned &RCCost) const;
226
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000227 /// InitRegPressure - Find all virtual register references that are liveout
228 /// of the preheader to initialize the starting "register pressure". Note
229 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000230 void InitRegPressure(MachineBasicBlock *BB);
231
Evan Cheng134982d2010-10-20 22:03:58 +0000232 /// UpdateRegPressure - Update estimate of register pressure after the
233 /// specified instruction.
234 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000235
Dan Gohman5c952302009-10-29 17:47:20 +0000236 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
237 /// the load itself could be hoisted. Return the unfolded and hoistable
238 /// load, or null if the load couldn't be unfolded or if it wouldn't
239 /// be hoistable.
240 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
241
Evan Cheng78e5c112009-11-07 03:52:02 +0000242 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
243 /// duplicate of MI. Return this instruction if it's found.
244 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
245 std::vector<const MachineInstr*> &PrevMIs);
246
Evan Cheng9fb744e2009-11-05 00:51:13 +0000247 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
248 /// the preheader that compute the same value. If it's found, do a RAU on
249 /// with the definition of the existing instruction rather than hoisting
250 /// the instruction to the preheader.
251 bool EliminateCSE(MachineInstr *MI,
252 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
253
Bill Wendling0f940c92007-12-07 21:42:31 +0000254 /// Hoist - When an instruction is found to only use loop invariant operands
255 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000256 /// It returns true if the instruction is hoisted.
257 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000258
259 /// InitCSEMap - Initialize the CSE map with instructions that are in the
260 /// current loop preheader that may become duplicates of instructions that
261 /// are hoisted out of the loop.
262 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000263
264 /// getCurPreheader - Get the preheader for the current loop, splitting
265 /// a critical edge if needed.
266 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000267 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000268} // end anonymous namespace
269
Dan Gohman844731a2008-05-13 00:00:25 +0000270char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000271INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
272 "Machine Loop Invariant Code Motion", false, false)
273INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
274INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
275INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
276INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000277 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000278
Evan Chengd94671a2010-04-07 00:41:17 +0000279FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
280 return new MachineLICM(PreRegAlloc);
281}
Bill Wendling0f940c92007-12-07 21:42:31 +0000282
Dan Gohman853d3fb2010-06-22 17:25:57 +0000283/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
284/// loop that has a unique predecessor.
285static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000286 // Check whether this loop even has a unique predecessor.
287 if (!CurLoop->getLoopPredecessor())
288 return false;
289 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000290 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000291 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000292 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000293 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000294 return true;
295}
296
Bill Wendling0f940c92007-12-07 21:42:31 +0000297bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000298 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000299 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000300 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000301 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
302 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000303
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000304 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000305 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000306 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000307 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000308 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000309 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000310 MRI = &MF.getRegInfo();
311 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000312 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000313
Evan Cheng0e673912010-10-14 01:16:09 +0000314 if (PreRegAlloc) {
315 // Estimate register pressure during pre-regalloc pass.
316 unsigned NumRC = TRI->getNumRegClasses();
317 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000318 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000319 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000320 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
321 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000322 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000323 }
324
Bill Wendling0f940c92007-12-07 21:42:31 +0000325 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000326 MLI = &getAnalysis<MachineLoopInfo>();
327 DT = &getAnalysis<MachineDominatorTree>();
328 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000329
Dan Gohmanaa742602010-07-09 18:49:45 +0000330 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
331 while (!Worklist.empty()) {
332 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000333 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000334
Evan Cheng4038f9c2010-04-08 01:03:47 +0000335 // If this is done before regalloc, only visit outer-most preheader-sporting
336 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000337 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
338 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000339 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000340 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000341
Bill Wendlingc83693f2011-10-11 22:42:31 +0000342 // If the header is a landing pad, then we don't want to hoist instructions
343 // out of it. This can happen with SjLj exception handling which has a
344 // dispatch table as the landing pad.
345 if (CurLoop->getHeader()->isLandingPad()) continue;
346
Evan Chengd94671a2010-04-07 00:41:17 +0000347 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000348 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000349 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000350 // CSEMap is initialized for loop header when the first instruction is
351 // being hoisted.
352 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000353 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000354 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000355 CSEMap.clear();
356 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000357 }
358
359 return Changed;
360}
361
Evan Cheng4038f9c2010-04-08 01:03:47 +0000362/// InstructionStoresToFI - Return true if instruction stores to the
363/// specified frame.
364static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
365 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
366 oe = MI->memoperands_end(); o != oe; ++o) {
367 if (!(*o)->isStore() || !(*o)->getValue())
368 continue;
369 if (const FixedStackPseudoSourceValue *Value =
370 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
371 if (Value->getFrameIndex() == FI)
372 return true;
373 }
374 }
375 return false;
376}
377
378/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
379/// gather register def and frame object update information.
380void MachineLICM::ProcessMI(MachineInstr *MI,
381 unsigned *PhysRegDefs,
382 SmallSet<int, 32> &StoredFIs,
383 SmallVector<CandidateInfo, 32> &Candidates) {
384 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000385 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000386 unsigned Def = 0;
387 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
388 const MachineOperand &MO = MI->getOperand(i);
389 if (MO.isFI()) {
390 // Remember if the instruction stores to the frame index.
391 int FI = MO.getIndex();
392 if (!StoredFIs.count(FI) &&
393 MFI->isSpillSlotObjectIndex(FI) &&
394 InstructionStoresToFI(MI, FI))
395 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000396 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000397 continue;
398 }
399
400 if (!MO.isReg())
401 continue;
402 unsigned Reg = MO.getReg();
403 if (!Reg)
404 continue;
405 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
406 "Not expecting virtual register!");
407
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000408 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000409 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000410 // If it's using a non-loop-invariant register, then it's obviously not
411 // safe to hoist.
412 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000413 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000414 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000415
416 if (MO.isImplicit()) {
417 ++PhysRegDefs[Reg];
418 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
419 ++PhysRegDefs[*AS];
420 if (!MO.isDead())
421 // Non-dead implicit def? This cannot be hoisted.
422 RuledOut = true;
423 // No need to check if a dead implicit def is also defined by
424 // another instruction.
425 continue;
426 }
427
428 // FIXME: For now, avoid instructions with multiple defs, unless
429 // it's a dead implicit def.
430 if (Def)
431 RuledOut = true;
432 else
433 Def = Reg;
434
435 // If we have already seen another instruction that defines the same
436 // register, then this is not safe.
437 if (++PhysRegDefs[Reg] > 1)
438 // MI defined register is seen defined by another instruction in
439 // the loop, it cannot be a LICM candidate.
440 RuledOut = true;
441 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
442 if (++PhysRegDefs[*AS] > 1)
443 RuledOut = true;
444 }
445
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000446 // Only consider reloads for now and remats which do not have register
447 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000448 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000449 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000450 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000451 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
452 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000453 }
454}
455
456/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
457/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000458void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000459 unsigned NumRegs = TRI->getNumRegs();
460 unsigned *PhysRegDefs = new unsigned[NumRegs];
461 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
462
Evan Cheng4038f9c2010-04-08 01:03:47 +0000463 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000464 SmallSet<int, 32> StoredFIs;
465
466 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000467 // collect potential LICM candidates.
468 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
469 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
470 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000471 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000472 // FIXME: That means a reload that're reused in successor block(s) will not
473 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000474 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000475 E = BB->livein_end(); I != E; ++I) {
476 unsigned Reg = *I;
477 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000478 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
479 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000480 }
481
Evan Chengfad62872011-10-11 23:48:44 +0000482 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000483 for (MachineBasicBlock::iterator
484 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000485 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000486 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000487 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000488 }
Evan Chengd94671a2010-04-07 00:41:17 +0000489
490 // Now evaluate whether the potential candidates qualify.
491 // 1. Check if the candidate defined register is defined by another
492 // instruction in the loop.
493 // 2. If the candidate is a load from stack slot (always true for now),
494 // check if the slot is stored anywhere in the loop.
495 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000496 if (Candidates[i].FI != INT_MIN &&
497 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000498 continue;
499
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000500 if (PhysRegDefs[Candidates[i].Def] == 1) {
501 bool Safe = true;
502 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000503 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
504 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000505 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000506 continue;
507 if (PhysRegDefs[MO.getReg()]) {
508 // If it's using a non-loop-invariant register, then it's obviously
509 // not safe to hoist.
510 Safe = false;
511 break;
512 }
513 }
514 if (Safe)
515 HoistPostRA(MI, Candidates[i].Def);
516 }
Evan Chengd94671a2010-04-07 00:41:17 +0000517 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000518
519 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000520}
521
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000522/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
523/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000524void MachineLICM::AddToLiveIns(unsigned Reg) {
525 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000526 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
527 MachineBasicBlock *BB = Blocks[i];
528 if (!BB->isLiveIn(Reg))
529 BB->addLiveIn(Reg);
530 for (MachineBasicBlock::iterator
531 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
532 MachineInstr *MI = &*MII;
533 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
534 MachineOperand &MO = MI->getOperand(i);
535 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
536 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
537 MO.setIsKill(false);
538 }
539 }
540 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000541}
542
543/// HoistPostRA - When an instruction is found to only use loop invariant
544/// operands that is safe to hoist, this instruction is called to do the
545/// dirty work.
546void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000547 MachineBasicBlock *Preheader = getCurPreheader();
548 if (!Preheader) return;
549
Evan Chengd94671a2010-04-07 00:41:17 +0000550 // Now move the instructions to the predecessor, inserting it before any
551 // terminator instructions.
552 DEBUG({
553 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000554 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000555 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000556 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000557 if (MI->getParent()->getBasicBlock())
558 dbgs() << " from MachineBasicBlock "
559 << MI->getParent()->getName();
560 dbgs() << "\n";
561 });
562
563 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000564 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000565 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000566
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000567 // Add register to livein list to all the BBs in the current loop since a
568 // loop invariant must be kept live throughout the whole loop. This is
569 // important to ensure later passes do not scavenge the def register.
570 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000571
572 ++NumPostRAHoisted;
573 Changed = true;
574}
575
Devang Patel2e350472011-10-11 18:09:58 +0000576// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
577// If not then a load from this mbb may not be safe to hoist.
578bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000579 if (SpeculationState != SpeculateUnknown)
580 return SpeculationState == SpeculateFalse;
581
Devang Patel2e350472011-10-11 18:09:58 +0000582 if (BB != CurLoop->getHeader()) {
583 // Check loop exiting blocks.
584 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
585 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
586 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
587 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Evan Chengfad62872011-10-11 23:48:44 +0000588 SpeculationState = SpeculateTrue;
589 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000590 }
591 }
592
Evan Chengfad62872011-10-11 23:48:44 +0000593 SpeculationState = SpeculateFalse;
594 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000595}
596
Bill Wendling0f940c92007-12-07 21:42:31 +0000597/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
598/// dominated by the specified block, and that are in the current loop) in depth
599/// first order w.r.t the DominatorTree. This allows us to visit definitions
600/// before uses, allowing us to hoist a loop body in one pass without iteration.
601///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000602void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000603 assert(N != 0 && "Null dominator tree node?");
604 MachineBasicBlock *BB = N->getBlock();
605
606 // If this subregion is not in the top level loop at all, exit.
607 if (!CurLoop->contains(BB)) return;
608
Evan Cheng0e673912010-10-14 01:16:09 +0000609 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000610 if (!Preheader)
611 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000612
Evan Cheng23128422010-10-19 18:58:51 +0000613 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000614 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000615 RegSeen.clear();
616 BackTrace.clear();
617 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000618 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000619
Evan Cheng23128422010-10-19 18:58:51 +0000620 // Remember livein register pressure.
621 BackTrace.push_back(RegPressure);
622
Evan Chengfad62872011-10-11 23:48:44 +0000623 SpeculationState = SpeculateUnknown;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000624 for (MachineBasicBlock::iterator
625 MII = BB->begin(), E = BB->end(); MII != E; ) {
626 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
627 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000628 if (!Hoist(MI, Preheader))
629 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000630 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000631 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000632
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000633 // Don't hoist things out of a large switch statement. This often causes
634 // code to be hoisted that wasn't going to be executed, and increases
635 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000636 if (BB->succ_size() < 25) {
637 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000638 for (unsigned I = 0, E = Children.size(); I != E; ++I)
639 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000640 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000641
Evan Cheng23128422010-10-19 18:58:51 +0000642 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000643}
644
Evan Cheng134982d2010-10-20 22:03:58 +0000645static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
646 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
647}
648
Evan Cheng61560e22011-09-01 01:45:00 +0000649/// getRegisterClassIDAndCost - For a given MI, register, and the operand
650/// index, return the ID and cost of its representative register class.
651void
652MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
653 unsigned Reg, unsigned OpIdx,
654 unsigned &RCId, unsigned &RCCost) const {
655 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
656 EVT VT = *RC->vt_begin();
657 if (VT == MVT::untyped) {
658 RCId = RC->getID();
659 RCCost = 1;
660 } else {
661 RCId = TLI->getRepRegClassFor(VT)->getID();
662 RCCost = TLI->getRepRegClassCostFor(VT);
663 }
664}
665
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000666/// InitRegPressure - Find all virtual register references that are liveout of
667/// the preheader to initialize the starting "register pressure". Note this
668/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000669void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000670 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000671
Evan Cheng134982d2010-10-20 22:03:58 +0000672 // If the preheader has only a single predecessor and it ends with a
673 // fallthrough or an unconditional branch, then scan its predecessor for live
674 // defs as well. This happens whenever the preheader is created by splitting
675 // the critical edge from the loop predecessor to the loop header.
676 if (BB->pred_size() == 1) {
677 MachineBasicBlock *TBB = 0, *FBB = 0;
678 SmallVector<MachineOperand, 4> Cond;
679 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
680 InitRegPressure(*BB->pred_begin());
681 }
682
Evan Cheng0e673912010-10-14 01:16:09 +0000683 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
684 MII != E; ++MII) {
685 MachineInstr *MI = &*MII;
686 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
687 const MachineOperand &MO = MI->getOperand(i);
688 if (!MO.isReg() || MO.isImplicit())
689 continue;
690 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000691 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000692 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000693
Andrew Trickdc986d22010-10-19 02:50:50 +0000694 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000695 unsigned RCId, RCCost;
696 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000697 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000698 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000699 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000700 bool isKill = isOperandKill(MO, MRI);
701 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000702 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000703 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000704 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000705 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000706 }
Evan Cheng0e673912010-10-14 01:16:09 +0000707 }
708 }
709}
710
Evan Cheng134982d2010-10-20 22:03:58 +0000711/// UpdateRegPressure - Update estimate of register pressure after the
712/// specified instruction.
713void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
714 if (MI->isImplicitDef())
715 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000716
Evan Cheng134982d2010-10-20 22:03:58 +0000717 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000718 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
719 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000720 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000721 continue;
722 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000723 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000724 continue;
725
Andrew Trickdc986d22010-10-19 02:50:50 +0000726 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000727 if (MO.isDef())
728 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000729 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000730 unsigned RCId, RCCost;
731 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000732 if (RCCost > RegPressure[RCId])
733 RegPressure[RCId] = 0;
734 else
Evan Cheng23128422010-10-19 18:58:51 +0000735 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000736 }
Evan Cheng0e673912010-10-14 01:16:09 +0000737 }
Evan Cheng0e673912010-10-14 01:16:09 +0000738
Evan Cheng61560e22011-09-01 01:45:00 +0000739 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000740 while (!Defs.empty()) {
741 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000742 unsigned RCId, RCCost;
743 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000744 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000745 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000746 }
747}
748
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000749/// IsLICMCandidate - Returns true if the instruction may be a suitable
750/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
751/// not safe to hoist it.
752bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000753 // Check if it's safe to move the instruction.
754 bool DontMoveAcrossStore = true;
755 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000756 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000757
758 // If it is load then check if it is guaranteed to execute by making sure that
759 // it dominates all exiting blocks. If it doesn't, then there is a path out of
760 // the loop which does not execute this load, so we can't hoist it.
761 // Stores and side effects are already checked by isSafeToMove.
762 if (I.getDesc().mayLoad() && !IsGuaranteedToExecute(I.getParent()))
763 return false;
764
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000765 return true;
766}
767
768/// IsLoopInvariantInst - Returns true if the instruction is loop
769/// invariant. I.e., all virtual register operands are defined outside of the
770/// loop, physical registers aren't accessed explicitly, and there are no side
771/// effects that aren't captured by the operands or other flags.
772///
773bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
774 if (!IsLICMCandidate(I))
775 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000776
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000777 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000778 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
779 const MachineOperand &MO = I.getOperand(i);
780
Dan Gohmand735b802008-10-03 15:45:36 +0000781 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000782 continue;
783
Dan Gohmanc475c362009-01-15 22:01:38 +0000784 unsigned Reg = MO.getReg();
785 if (Reg == 0) continue;
786
787 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000788 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000789 if (MO.isUse()) {
790 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000791 // and we can freely move its uses. Alternatively, if it's allocatable,
792 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000793 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000794 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000795 if (AllocatableSet.test(Reg))
796 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000797 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000798 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
799 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000800 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000801 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000802 if (AllocatableSet.test(AliasReg))
803 return false;
804 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000805 // Otherwise it's safe to move.
806 continue;
807 } else if (!MO.isDead()) {
808 // A def that isn't dead. We can't move it.
809 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000810 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
811 // If the reg is live into the loop, we can't hoist an instruction
812 // which would clobber it.
813 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000814 }
815 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000816
817 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000818 continue;
819
Evan Cheng0e673912010-10-14 01:16:09 +0000820 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000821 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000822
823 // If the loop contains the definition of an operand, then the instruction
824 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000825 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000826 return false;
827 }
828
829 // If we got this far, the instruction is loop invariant!
830 return true;
831}
832
Evan Chengaf6949d2009-02-05 08:45:46 +0000833
Evan Chengd67705f2011-04-11 21:09:18 +0000834/// HasAnyPHIUse - Return true if the specified register is used by any
835/// phi node.
836bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000837 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
838 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000839 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000840 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000841 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000842 // Look pass copies as well.
843 if (UseMI->isCopy()) {
844 unsigned Def = UseMI->getOperand(0).getReg();
845 if (TargetRegisterInfo::isVirtualRegister(Def) &&
846 HasAnyPHIUse(Def))
847 return true;
848 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000849 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000850 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000851}
852
Evan Cheng23128422010-10-19 18:58:51 +0000853/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
854/// and an use in the current loop, return true if the target considered
855/// it 'high'.
856bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000857 unsigned DefIdx, unsigned Reg) const {
858 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000859 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000860
Evan Cheng0e673912010-10-14 01:16:09 +0000861 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
862 E = MRI->use_nodbg_end(); I != E; ++I) {
863 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000864 if (UseMI->isCopyLike())
865 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000866 if (!CurLoop->contains(UseMI->getParent()))
867 continue;
868 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
869 const MachineOperand &MO = UseMI->getOperand(i);
870 if (!MO.isReg() || !MO.isUse())
871 continue;
872 unsigned MOReg = MO.getReg();
873 if (MOReg != Reg)
874 continue;
875
Evan Cheng23128422010-10-19 18:58:51 +0000876 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
877 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000878 }
879
Evan Cheng23128422010-10-19 18:58:51 +0000880 // Only look at the first in loop use.
881 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000882 }
883
Evan Cheng23128422010-10-19 18:58:51 +0000884 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000885}
886
Evan Chengc8141df2010-10-26 02:08:50 +0000887/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
888/// the operand latency between its def and a use is one or less.
889bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
890 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
891 return true;
892 if (!InstrItins || InstrItins->isEmpty())
893 return false;
894
895 bool isCheap = false;
896 unsigned NumDefs = MI.getDesc().getNumDefs();
897 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
898 MachineOperand &DefMO = MI.getOperand(i);
899 if (!DefMO.isReg() || !DefMO.isDef())
900 continue;
901 --NumDefs;
902 unsigned Reg = DefMO.getReg();
903 if (TargetRegisterInfo::isPhysicalRegister(Reg))
904 continue;
905
906 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
907 return false;
908 isCheap = true;
909 }
910
911 return isCheap;
912}
913
Evan Cheng134982d2010-10-20 22:03:58 +0000914/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000915/// if hoisting an instruction of the given cost matrix can cause high
916/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000917bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
918 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
919 CI != CE; ++CI) {
920 if (CI->second <= 0)
921 continue;
922
923 unsigned RCId = CI->first;
924 for (unsigned i = BackTrace.size(); i != 0; --i) {
925 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000926 if (RP[RCId] + CI->second >= RegLimit[RCId])
927 return true;
928 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000929 }
930
931 return false;
932}
933
Evan Cheng134982d2010-10-20 22:03:58 +0000934/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
935/// current block and update their register pressures to reflect the effect
936/// of hoisting MI from the current block to the preheader.
937void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
938 if (MI->isImplicitDef())
939 return;
940
941 // First compute the 'cost' of the instruction, i.e. its contribution
942 // to register pressure.
943 DenseMap<unsigned, int> Cost;
944 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
945 const MachineOperand &MO = MI->getOperand(i);
946 if (!MO.isReg() || MO.isImplicit())
947 continue;
948 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000949 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000950 continue;
951
Evan Cheng61560e22011-09-01 01:45:00 +0000952 unsigned RCId, RCCost;
953 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000954 if (MO.isDef()) {
955 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
956 if (CI != Cost.end())
957 CI->second += RCCost;
958 else
959 Cost.insert(std::make_pair(RCId, RCCost));
960 } else if (isOperandKill(MO, MRI)) {
961 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
962 if (CI != Cost.end())
963 CI->second -= RCCost;
964 else
965 Cost.insert(std::make_pair(RCId, -RCCost));
966 }
967 }
968
969 // Update register pressure of blocks from loop header to current block.
970 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
971 SmallVector<unsigned, 8> &RP = BackTrace[i];
972 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
973 CI != CE; ++CI) {
974 unsigned RCId = CI->first;
975 RP[RCId] += CI->second;
976 }
977 }
978}
979
Evan Cheng45e94d62009-02-04 09:19:56 +0000980/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
981/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000982bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000983 if (MI.isImplicitDef())
984 return true;
985
Evan Cheng23128422010-10-19 18:58:51 +0000986 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
987 // will increase register pressure. It's probably not worth it if the
988 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000989 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
990 // these tend to help performance in low register pressure situation. The
991 // trade off is it may cause spill in high pressure situation. It will end up
992 // adding a store in the loop preheader. But the reload is no more expensive.
993 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000994 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000995 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000996 return false;
997 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000998 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000999 // In low register pressure situation, we can be more aggressive about
1000 // hoisting. Also, favors hoisting long latency instructions even in
1001 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +00001002 // FIXME: If there are long latency loop-invariant instructions inside the
1003 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001004 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +00001005 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1006 const MachineOperand &MO = MI.getOperand(i);
1007 if (!MO.isReg() || MO.isImplicit())
1008 continue;
1009 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001010 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +00001011 continue;
Evan Cheng61560e22011-09-01 01:45:00 +00001012
1013 unsigned RCId, RCCost;
1014 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001015 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +00001016 if (HasHighOperandLatency(MI, i, Reg)) {
1017 ++NumHighLatency;
1018 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001019 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001020
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001021 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001022 if (CI != Cost.end())
1023 CI->second += RCCost;
1024 else
1025 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +00001026 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001027 // Is a virtual register use is a kill, hoisting it out of the loop
1028 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +00001029 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001030 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1031 if (CI != Cost.end())
1032 CI->second -= RCCost;
1033 else
1034 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +00001035 }
1036 }
1037
Evan Cheng134982d2010-10-20 22:03:58 +00001038 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001039 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +00001040 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001041 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +00001042 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001043 }
Evan Cheng0e673912010-10-14 01:16:09 +00001044
1045 // High register pressure situation, only hoist if the instruction is going to
1046 // be remat'ed.
Evan Chengfad62872011-10-11 23:48:44 +00001047 // Also, do not "speculate" in high register pressure situation. If an
1048 // instruction is not guaranteed to be executed in the loop, it's best to be
1049 // conservative.
1050 if (SpeculationState == SpeculateTrue ||
1051 (!TII->isTriviallyReMaterializable(&MI, AA) &&
1052 !MI.isInvariantLoad(AA)))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001053 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001054 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001055
Evan Chengd67705f2011-04-11 21:09:18 +00001056 // If result(s) of this instruction is used by PHIs outside of the loop, then
1057 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001058 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1059 const MachineOperand &MO = MI.getOperand(i);
1060 if (!MO.isReg() || !MO.isDef())
1061 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001062 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001063 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001064 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001065
1066 return true;
1067}
1068
Dan Gohman5c952302009-10-29 17:47:20 +00001069MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001070 // Don't unfold simple loads.
1071 if (MI->getDesc().canFoldAsLoad())
1072 return 0;
1073
Dan Gohman5c952302009-10-29 17:47:20 +00001074 // If not, we may be able to unfold a load and hoist that.
1075 // First test whether the instruction is loading from an amenable
1076 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001077 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001078 return 0;
1079
Dan Gohman5c952302009-10-29 17:47:20 +00001080 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001081 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001082 unsigned NewOpc =
1083 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1084 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001085 /*UnfoldStore=*/false,
1086 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001087 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001088 const MCInstrDesc &MID = TII->get(NewOpc);
1089 if (MID.getNumDefs() != 1) return 0;
1090 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001091 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001092 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001093
1094 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001095 SmallVector<MachineInstr *, 2> NewMIs;
1096 bool Success =
1097 TII->unfoldMemoryOperand(MF, MI, Reg,
1098 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1099 NewMIs);
1100 (void)Success;
1101 assert(Success &&
1102 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1103 "succeeded!");
1104 assert(NewMIs.size() == 2 &&
1105 "Unfolded a load into multiple instructions!");
1106 MachineBasicBlock *MBB = MI->getParent();
1107 MBB->insert(MI, NewMIs[0]);
1108 MBB->insert(MI, NewMIs[1]);
1109 // If unfolding produced a load that wasn't loop-invariant or profitable to
1110 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001111 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001112 NewMIs[0]->eraseFromParent();
1113 NewMIs[1]->eraseFromParent();
1114 return 0;
1115 }
Evan Cheng134982d2010-10-20 22:03:58 +00001116
1117 // Update register pressure for the unfolded instruction.
1118 UpdateRegPressure(NewMIs[1]);
1119
Dan Gohman5c952302009-10-29 17:47:20 +00001120 // Otherwise we successfully unfolded a load that we can hoist.
1121 MI->eraseFromParent();
1122 return NewMIs[0];
1123}
1124
Evan Cheng777c6b72009-11-03 21:40:02 +00001125void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1126 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1127 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001128 unsigned Opcode = MI->getOpcode();
1129 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1130 CI = CSEMap.find(Opcode);
1131 if (CI != CSEMap.end())
1132 CI->second.push_back(MI);
1133 else {
1134 std::vector<const MachineInstr*> CSEMIs;
1135 CSEMIs.push_back(MI);
1136 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001137 }
1138 }
1139}
1140
Evan Cheng78e5c112009-11-07 03:52:02 +00001141const MachineInstr*
1142MachineLICM::LookForDuplicate(const MachineInstr *MI,
1143 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001144 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1145 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001146 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001147 return PrevMI;
1148 }
1149 return 0;
1150}
1151
1152bool MachineLICM::EliminateCSE(MachineInstr *MI,
1153 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001154 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1155 // the undef property onto uses.
1156 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001157 return false;
1158
1159 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001160 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001161
1162 // Replace virtual registers defined by MI by their counterparts defined
1163 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001164 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1165 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001166
1167 // Physical registers may not differ here.
1168 assert((!MO.isReg() || MO.getReg() == 0 ||
1169 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1170 MO.getReg() == Dup->getOperand(i).getReg()) &&
1171 "Instructions with different phys regs are not identical!");
1172
1173 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001174 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001175 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1176 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001177 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001178 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001179 MI->eraseFromParent();
1180 ++NumCSEed;
1181 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001182 }
1183 return false;
1184}
1185
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001186/// Hoist - When an instruction is found to use only loop invariant operands
1187/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001188///
Evan Cheng134982d2010-10-20 22:03:58 +00001189bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001190 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001191 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001192 // If not, try unfolding a hoistable load.
1193 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001194 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001195 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001196
Dan Gohmanc475c362009-01-15 22:01:38 +00001197 // Now move the instructions to the predecessor, inserting it before any
1198 // terminator instructions.
1199 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001200 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001201 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001202 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001203 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001204 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001205 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001206 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001207 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001208 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001209
Evan Cheng777c6b72009-11-03 21:40:02 +00001210 // If this is the first instruction being hoisted to the preheader,
1211 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001212 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001213 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001214 FirstInLoop = false;
1215 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001216
Evan Chengaf6949d2009-02-05 08:45:46 +00001217 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001218 unsigned Opcode = MI->getOpcode();
1219 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1220 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001221 if (!EliminateCSE(MI, CI)) {
1222 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001223 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001224
Evan Cheng134982d2010-10-20 22:03:58 +00001225 // Update register pressure for BBs from header to this block.
1226 UpdateBackTraceRegPressure(MI);
1227
Dan Gohmane6cd7572010-05-13 20:34:42 +00001228 // Clear the kill flags of any register this instruction defines,
1229 // since they may need to be live throughout the entire loop
1230 // rather than just live for part of it.
1231 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1232 MachineOperand &MO = MI->getOperand(i);
1233 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001234 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001235 }
1236
Evan Chengaf6949d2009-02-05 08:45:46 +00001237 // Add to the CSE map.
1238 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001239 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001240 else {
1241 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001242 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001243 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001244 }
1245 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001246
Dan Gohmanc475c362009-01-15 22:01:38 +00001247 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001248 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001249
1250 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001251}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001252
1253MachineBasicBlock *MachineLICM::getCurPreheader() {
1254 // Determine the block to which to hoist instructions. If we can't find a
1255 // suitable loop predecessor, we can't do any hoisting.
1256
1257 // If we've tried to get a preheader and failed, don't try again.
1258 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1259 return 0;
1260
1261 if (!CurPreheader) {
1262 CurPreheader = CurLoop->getLoopPreheader();
1263 if (!CurPreheader) {
1264 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1265 if (!Pred) {
1266 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1267 return 0;
1268 }
1269
1270 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1271 if (!CurPreheader) {
1272 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1273 return 0;
1274 }
1275 }
1276 }
1277 return CurPreheader;
1278}