blob: 0edd44ba2e555cb8c68808af18f70339bc337784 [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"
Dan Gohman6f0d0242008-02-10 18:45:23 +000031#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000032#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000033#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000034#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000035#include "llvm/ADT/DenseMap.h"
Evan Chengd94671a2010-04-07 00:41:17 +000036#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000038#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000040
41using namespace llvm;
42
Bill Wendling041b3f82007-12-08 23:58:46 +000043STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000044STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000045STATISTIC(NumPostRAHoisted,
46 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000047
Bill Wendling0f940c92007-12-07 21:42:31 +000048namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000049 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000050 bool PreRegAlloc;
51
Bill Wendling9258cd32008-01-02 19:32:43 +000052 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000053 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000054 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000055 const MachineFrameInfo *MFI;
56 MachineRegisterInfo *RegInfo;
Bill Wendling12ebf142007-12-11 19:40:06 +000057
Bill Wendling0f940c92007-12-07 21:42:31 +000058 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000059 AliasAnalysis *AA; // Alias analysis info.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000060 MachineLoopInfo *LI; // Current MachineLoopInfo
61 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000062
Bill Wendling0f940c92007-12-07 21:42:31 +000063 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000064 bool Changed; // True if a loop is changed.
Evan Cheng777c6b72009-11-03 21:40:02 +000065 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000066 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000067 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000068
Evan Chengd94671a2010-04-07 00:41:17 +000069 BitVector AllocatableSet;
70
Evan Cheng777c6b72009-11-03 21:40:02 +000071 // For each opcode, keep a list of potentail CSE instructions.
72 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000073
Bill Wendling0f940c92007-12-07 21:42:31 +000074 public:
75 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000076 MachineLICM() :
77 MachineFunctionPass(&ID), PreRegAlloc(true) {}
78
79 explicit MachineLICM(bool PreRA) :
80 MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000081
82 virtual bool runOnMachineFunction(MachineFunction &MF);
83
Dan Gohman72241702008-12-18 01:37:56 +000084 const char *getPassName() const { return "Machine Instruction LICM"; }
85
Bill Wendling074223a2008-03-10 08:13:01 +000086 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000087 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.setPreservesCFG();
89 AU.addRequired<MachineLoopInfo>();
90 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000091 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000092 AU.addPreserved<MachineLoopInfo>();
93 AU.addPreserved<MachineDominatorTree>();
94 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000095 }
Evan Chengaf6949d2009-02-05 08:45:46 +000096
97 virtual void releaseMemory() {
98 CSEMap.clear();
99 }
100
Bill Wendling0f940c92007-12-07 21:42:31 +0000101 private:
Bill Wendling041b3f82007-12-08 23:58:46 +0000102 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000103 /// invariant. I.e., all virtual register operands are defined outside of
104 /// the loop, physical registers aren't accessed (explicitly or implicitly),
105 /// and the instruction is hoistable.
106 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000107 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000108
Evan Cheng45e94d62009-02-04 09:19:56 +0000109 /// IsProfitableToHoist - Return true if it is potentially profitable to
110 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000111 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000112
Bill Wendling0f940c92007-12-07 21:42:31 +0000113 /// HoistRegion - Walk the specified region of the CFG (defined by all
114 /// blocks dominated by the specified block, and that are in the current
115 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
116 /// visit definitions before uses, allowing us to hoist a loop body in one
117 /// pass without iteration.
118 ///
119 void HoistRegion(MachineDomTreeNode *N);
Evan Chengd94671a2010-04-07 00:41:17 +0000120 void HoistRegionPostRA(MachineDomTreeNode *N);
Bill Wendling0f940c92007-12-07 21:42:31 +0000121
Evan Cheng87b75ba2009-11-20 19:55:37 +0000122 /// isLoadFromConstantMemory - Return true if the given instruction is a
123 /// load from constant memory.
124 bool isLoadFromConstantMemory(MachineInstr *MI);
125
Dan Gohman5c952302009-10-29 17:47:20 +0000126 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
127 /// the load itself could be hoisted. Return the unfolded and hoistable
128 /// load, or null if the load couldn't be unfolded or if it wouldn't
129 /// be hoistable.
130 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
131
Evan Cheng78e5c112009-11-07 03:52:02 +0000132 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
133 /// duplicate of MI. Return this instruction if it's found.
134 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
135 std::vector<const MachineInstr*> &PrevMIs);
136
Evan Cheng9fb744e2009-11-05 00:51:13 +0000137 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
138 /// the preheader that compute the same value. If it's found, do a RAU on
139 /// with the definition of the existing instruction rather than hoisting
140 /// the instruction to the preheader.
141 bool EliminateCSE(MachineInstr *MI,
142 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
143
Bill Wendling0f940c92007-12-07 21:42:31 +0000144 /// Hoist - When an instruction is found to only use loop invariant operands
145 /// that is safe to hoist, this instruction is called to do the dirty work.
146 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000147 void Hoist(MachineInstr *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000148 void HoistPostRA(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000149
150 /// InitCSEMap - Initialize the CSE map with instructions that are in the
151 /// current loop preheader that may become duplicates of instructions that
152 /// are hoisted out of the loop.
153 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000154 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000155} // end anonymous namespace
156
Dan Gohman844731a2008-05-13 00:00:25 +0000157char MachineLICM::ID = 0;
158static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000159X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000160
Evan Chengd94671a2010-04-07 00:41:17 +0000161FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
162 return new MachineLICM(PreRegAlloc);
163}
Bill Wendling0f940c92007-12-07 21:42:31 +0000164
Dan Gohmanc475c362009-01-15 22:01:38 +0000165/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
166/// loop that has a preheader.
167static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
168 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
169 if (L->getLoopPreheader())
170 return false;
171 return true;
172}
173
Bill Wendling0f940c92007-12-07 21:42:31 +0000174/// Hoist expressions out of the specified loop. Note, alias info for inner loop
175/// is not preserved so it is not a good idea to run LICM multiple times on one
176/// loop.
177///
178bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000179 if (PreRegAlloc)
180 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
181 else
182 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000183
Evan Cheng777c6b72009-11-03 21:40:02 +0000184 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000185 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000186 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000187 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000188 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000189 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000190 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000191
192 // Get our Loop information...
193 LI = &getAnalysis<MachineLoopInfo>();
194 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000195 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000196
Evan Cheng777c6b72009-11-03 21:40:02 +0000197 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000198 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000199
Dan Gohmanc475c362009-01-15 22:01:38 +0000200 // Only visit outer-most preheader-sporting loops.
201 if (!LoopIsOuterMostWithPreheader(CurLoop))
202 continue;
203
204 // Determine the block to which to hoist instructions. If we can't find a
205 // suitable loop preheader, we can't do any hoisting.
206 //
207 // FIXME: We are only hoisting if the basic block coming into this loop
208 // has only one successor. This isn't the case in general because we haven't
209 // broken critical edges or added preheaders.
210 CurPreheader = CurLoop->getLoopPreheader();
211 if (!CurPreheader)
212 continue;
213
Evan Cheng777c6b72009-11-03 21:40:02 +0000214 // CSEMap is initialized for loop header when the first instruction is
215 // being hoisted.
216 FirstInLoop = true;
Evan Chengd94671a2010-04-07 00:41:17 +0000217 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
218 if (!PreRegAlloc)
219 HoistRegionPostRA(N);
220 else {
221 HoistRegion(N);
222 CSEMap.clear();
223 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000224 }
225
226 return Changed;
227}
228
Evan Chengd94671a2010-04-07 00:41:17 +0000229void MachineLICM::HoistRegionPostRA(MachineDomTreeNode *N) {
230 assert(N != 0 && "Null dominator tree node?");
231
232 unsigned NumRegs = TRI->getNumRegs();
233 unsigned *PhysRegDefs = new unsigned[NumRegs];
234 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
235
236 SmallVector<std::pair<MachineInstr*, int>, 32> Candidates;
237 SmallSet<int, 32> StoredFIs;
238
239 // Walk the entire region, count number of defs for each register, and
240 // return potential LICM candidates.
241 SmallVector<MachineDomTreeNode*, 8> WorkList;
242 WorkList.push_back(N);
243 do {
244 N = WorkList.pop_back_val();
245 MachineBasicBlock *BB = N->getBlock();
246
247 if (!CurLoop->contains(BB))
248 continue;
249 // Conservatively treat live-in's as an external def.
Evan Cheng5b463902010-04-07 06:00:33 +0000250 // FIXME: That means a reload that's reused into a fallthrough block
251 // will not be LICM'ed.
Evan Chengd94671a2010-04-07 00:41:17 +0000252 for (MachineBasicBlock::const_livein_iterator I = BB->livein_begin(),
253 E = BB->livein_end(); I != E; ++I) {
254 unsigned Reg = *I;
255 ++PhysRegDefs[Reg];
256 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
257 ++PhysRegDefs[*SR];
258 }
259
260 for (MachineBasicBlock::iterator
261 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
262 bool RuledOut = false;
263 bool SeenDef = false;
264 MachineInstr *MI = &*MII;
265 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
266 const MachineOperand &MO = MI->getOperand(i);
267 if (!MO.isReg())
268 continue;
269 unsigned Reg = MO.getReg();
270 if (!Reg)
271 continue;
272 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
273 "Not expecting virtual register!");
274
275 if (MO.isDef()) {
276 SeenDef = true;
277 if (++PhysRegDefs[Reg] > 1)
278 // MI defined register is seen defined by another instruction in
279 // the loop, it cannot be a LICM candidate.
280 RuledOut = true;
281 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
282 if (++PhysRegDefs[*SR] > 1)
283 RuledOut = true;
284 }
285 }
286
Evan Cheng5b463902010-04-07 06:00:33 +0000287 // FIXME: Only consider reloads for now. We should be able to handle
288 // remat which does not have register operands.
Evan Chengd94671a2010-04-07 00:41:17 +0000289 bool SkipCheck = false;
290 int FI;
291 if (SeenDef && !RuledOut) {
292 if (TII->isLoadFromStackSlot(MI, FI) &&
293 MFI->isSpillSlotObjectIndex(FI)) {
294 Candidates.push_back(std::make_pair(MI, FI));
295 SkipCheck = true;
296 }
297 }
298
299 // If MI is a store to a stack slot, remember the slot. An instruction
300 // loads from this slot cannot be a LICM candidate.
Evan Cheng348856e2010-04-07 05:59:12 +0000301 if (!SkipCheck && TII->isStoreToStackSlot(MI, FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000302 StoredFIs.insert(FI);
303 }
304
305 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
306 for (unsigned I = 0, E = Children.size(); I != E; ++I)
307 WorkList.push_back(Children[I]);
308 } while (!WorkList.empty());
309
310 // Now evaluate whether the potential candidates qualify.
311 // 1. Check if the candidate defined register is defined by another
312 // instruction in the loop.
313 // 2. If the candidate is a load from stack slot (always true for now),
314 // check if the slot is stored anywhere in the loop.
315 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
316 bool Safe = true;
317 int FI = Candidates[i].second;
318 if (StoredFIs.count(FI))
319 continue;
320
321 MachineInstr *MI = Candidates[i].first;
322 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
323 const MachineOperand &MO = MI->getOperand(j);
324 if (!MO.isReg())
325 continue;
326 unsigned Reg = MO.getReg();
327 if (!Reg)
328 continue;
329 if (MO.isDef() && PhysRegDefs[Reg] > 1) {
330 Safe = false;
331 break;
332 }
333 }
334
335 if (Safe)
336 HoistPostRA(MI);
337 }
338}
339
340void MachineLICM::HoistPostRA(MachineInstr *MI) {
341 // Now move the instructions to the predecessor, inserting it before any
342 // terminator instructions.
343 DEBUG({
344 dbgs() << "Hoisting " << *MI;
345 if (CurPreheader->getBasicBlock())
346 dbgs() << " to MachineBasicBlock "
347 << CurPreheader->getName();
348 if (MI->getParent()->getBasicBlock())
349 dbgs() << " from MachineBasicBlock "
350 << MI->getParent()->getName();
351 dbgs() << "\n";
352 });
353
354 // Splice the instruction to the preheader.
355 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
356
357 ++NumPostRAHoisted;
358 Changed = true;
359}
360
Bill Wendling0f940c92007-12-07 21:42:31 +0000361/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
362/// dominated by the specified block, and that are in the current loop) in depth
363/// first order w.r.t the DominatorTree. This allows us to visit definitions
364/// before uses, allowing us to hoist a loop body in one pass without iteration.
365///
366void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
367 assert(N != 0 && "Null dominator tree node?");
368 MachineBasicBlock *BB = N->getBlock();
369
370 // If this subregion is not in the top level loop at all, exit.
371 if (!CurLoop->contains(BB)) return;
372
Dan Gohmanc475c362009-01-15 22:01:38 +0000373 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000374 MII = BB->begin(), E = BB->end(); MII != E; ) {
375 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000376 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000377 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000378 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000379
380 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000381 for (unsigned I = 0, E = Children.size(); I != E; ++I)
382 HoistRegion(Children[I]);
383}
384
Bill Wendling041b3f82007-12-08 23:58:46 +0000385/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000386/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000387/// loop, physical registers aren't accessed explicitly, and there are no side
388/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000389///
Bill Wendling041b3f82007-12-08 23:58:46 +0000390bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000391 const TargetInstrDesc &TID = I.getDesc();
392
393 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000394 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000395 TID.hasUnmodeledSideEffects())
396 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000397
Chris Lattnera22edc82008-01-10 23:08:24 +0000398 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000399 // Okay, this instruction does a load. As a refinement, we allow the target
400 // to decide whether the loaded value is actually a constant. If so, we can
401 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000402 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000403 // FIXME: we should be able to hoist loads with no other side effects if
404 // there are no other instructions which can change memory in this loop.
405 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000406 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000407 }
Bill Wendling074223a2008-03-10 08:13:01 +0000408
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000409 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000410 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
411 const MachineOperand &MO = I.getOperand(i);
412
Dan Gohmand735b802008-10-03 15:45:36 +0000413 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000414 continue;
415
Dan Gohmanc475c362009-01-15 22:01:38 +0000416 unsigned Reg = MO.getReg();
417 if (Reg == 0) continue;
418
419 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000420 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000421 if (MO.isUse()) {
422 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000423 // and we can freely move its uses. Alternatively, if it's allocatable,
424 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000425 if (!RegInfo->def_empty(Reg))
426 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000427 if (AllocatableSet.test(Reg))
428 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000429 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000430 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
431 unsigned AliasReg = *Alias;
432 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000433 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000434 if (AllocatableSet.test(AliasReg))
435 return false;
436 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000437 // Otherwise it's safe to move.
438 continue;
439 } else if (!MO.isDead()) {
440 // A def that isn't dead. We can't move it.
441 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000442 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
443 // If the reg is live into the loop, we can't hoist an instruction
444 // which would clobber it.
445 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000446 }
447 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000448
449 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000450 continue;
451
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000452 assert(RegInfo->getVRegDef(Reg) &&
453 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000454
455 // If the loop contains the definition of an operand, then the instruction
456 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000457 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000458 return false;
459 }
460
461 // If we got this far, the instruction is loop invariant!
462 return true;
463}
464
Evan Chengaf6949d2009-02-05 08:45:46 +0000465
466/// HasPHIUses - Return true if the specified register has any PHI use.
467static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000468 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
469 UE = RegInfo->use_end(); UI != UE; ++UI) {
470 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000471 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000472 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000473 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000474 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000475}
476
Evan Cheng87b75ba2009-11-20 19:55:37 +0000477/// isLoadFromConstantMemory - Return true if the given instruction is a
478/// load from constant memory. Machine LICM will hoist these even if they are
479/// not re-materializable.
480bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
481 if (!MI->getDesc().mayLoad()) return false;
482 if (!MI->hasOneMemOperand()) return false;
483 MachineMemOperand *MMO = *MI->memoperands_begin();
484 if (MMO->isVolatile()) return false;
485 if (!MMO->getValue()) return false;
486 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
487 if (PSV) {
488 MachineFunction &MF = *MI->getParent()->getParent();
489 return PSV->isConstant(MF.getFrameInfo());
490 } else {
491 return AA->pointsToConstantMemory(MMO->getValue());
492 }
493}
494
Evan Cheng45e94d62009-02-04 09:19:56 +0000495/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
496/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000497bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Chris Lattner518bb532010-02-09 19:54:29 +0000498 if (MI.isImplicitDef())
Evan Chengefc78392009-02-27 00:02:22 +0000499 return false;
500
Evan Cheng45e94d62009-02-04 09:19:56 +0000501 // FIXME: For now, only hoist re-materilizable instructions. LICM will
502 // increase register pressure. We want to make sure it doesn't increase
503 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000504 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
505 // these tend to help performance in low register pressure situation. The
506 // trade off is it may cause spill in high pressure situation. It will end up
507 // adding a store in the loop preheader. But the reload is no more expensive.
508 // The side benefit is these loads are frequently CSE'ed.
509 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000510 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000511 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000512 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000513
Evan Chengaf6949d2009-02-05 08:45:46 +0000514 // If result(s) of this instruction is used by PHIs, then don't hoist it.
515 // The presence of joins makes it difficult for current register allocator
516 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000517 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
518 const MachineOperand &MO = MI.getOperand(i);
519 if (!MO.isReg() || !MO.isDef())
520 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000521 if (HasPHIUses(MO.getReg(), RegInfo))
522 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000523 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000524
525 return true;
526}
527
Dan Gohman5c952302009-10-29 17:47:20 +0000528MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
529 // If not, we may be able to unfold a load and hoist that.
530 // First test whether the instruction is loading from an amenable
531 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000532 if (!isLoadFromConstantMemory(MI))
533 return 0;
534
Dan Gohman5c952302009-10-29 17:47:20 +0000535 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000536 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000537 unsigned NewOpc =
538 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
539 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000540 /*UnfoldStore=*/false,
541 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000542 if (NewOpc == 0) return 0;
543 const TargetInstrDesc &TID = TII->get(NewOpc);
544 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000545 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000546 // Ok, we're unfolding. Create a temporary register and do the unfold.
547 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000548
549 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000550 SmallVector<MachineInstr *, 2> NewMIs;
551 bool Success =
552 TII->unfoldMemoryOperand(MF, MI, Reg,
553 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
554 NewMIs);
555 (void)Success;
556 assert(Success &&
557 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
558 "succeeded!");
559 assert(NewMIs.size() == 2 &&
560 "Unfolded a load into multiple instructions!");
561 MachineBasicBlock *MBB = MI->getParent();
562 MBB->insert(MI, NewMIs[0]);
563 MBB->insert(MI, NewMIs[1]);
564 // If unfolding produced a load that wasn't loop-invariant or profitable to
565 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000566 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000567 NewMIs[0]->eraseFromParent();
568 NewMIs[1]->eraseFromParent();
569 return 0;
570 }
571 // Otherwise we successfully unfolded a load that we can hoist.
572 MI->eraseFromParent();
573 return NewMIs[0];
574}
575
Evan Cheng777c6b72009-11-03 21:40:02 +0000576void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
577 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
578 const MachineInstr *MI = &*I;
579 // FIXME: For now, only hoist re-materilizable instructions. LICM will
580 // increase register pressure. We want to make sure it doesn't increase
581 // spilling.
582 if (TII->isTriviallyReMaterializable(MI, AA)) {
583 unsigned Opcode = MI->getOpcode();
584 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
585 CI = CSEMap.find(Opcode);
586 if (CI != CSEMap.end())
587 CI->second.push_back(MI);
588 else {
589 std::vector<const MachineInstr*> CSEMIs;
590 CSEMIs.push_back(MI);
591 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
592 }
593 }
594 }
595}
596
Evan Cheng78e5c112009-11-07 03:52:02 +0000597const MachineInstr*
598MachineLICM::LookForDuplicate(const MachineInstr *MI,
599 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000600 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
601 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000602 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000603 return PrevMI;
604 }
605 return 0;
606}
607
608bool MachineLICM::EliminateCSE(MachineInstr *MI,
609 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000610 if (CI == CSEMap.end())
611 return false;
612
613 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000614 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000615
616 // Replace virtual registers defined by MI by their counterparts defined
617 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000618 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
619 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000620
621 // Physical registers may not differ here.
622 assert((!MO.isReg() || MO.getReg() == 0 ||
623 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
624 MO.getReg() == Dup->getOperand(i).getReg()) &&
625 "Instructions with different phys regs are not identical!");
626
627 if (MO.isReg() && MO.isDef() &&
628 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
Evan Cheng78e5c112009-11-07 03:52:02 +0000629 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000630 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000631 MI->eraseFromParent();
632 ++NumCSEed;
633 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000634 }
635 return false;
636}
637
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000638/// Hoist - When an instruction is found to use only loop invariant operands
639/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000640///
Dan Gohman589f1f52009-10-28 03:21:57 +0000641void MachineLICM::Hoist(MachineInstr *MI) {
642 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000643 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000644 // If not, try unfolding a hoistable load.
645 MI = ExtractHoistableLoad(MI);
646 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000647 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000648
Dan Gohmanc475c362009-01-15 22:01:38 +0000649 // Now move the instructions to the predecessor, inserting it before any
650 // terminator instructions.
651 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000652 dbgs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000653 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000654 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000655 << CurPreheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000656 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000657 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000658 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000659 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000660 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000661
Evan Cheng777c6b72009-11-03 21:40:02 +0000662 // If this is the first instruction being hoisted to the preheader,
663 // initialize the CSE map with potential common expressions.
664 InitCSEMap(CurPreheader);
665
Evan Chengaf6949d2009-02-05 08:45:46 +0000666 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000667 unsigned Opcode = MI->getOpcode();
668 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
669 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000670 if (!EliminateCSE(MI, CI)) {
671 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000672 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
673
Evan Chengaf6949d2009-02-05 08:45:46 +0000674 // Add to the CSE map.
675 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000676 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000677 else {
678 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000679 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000680 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000681 }
682 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000683
Dan Gohmanc475c362009-01-15 22:01:38 +0000684 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000685 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000686}