1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 // 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.
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.
21 //===----------------------------------------------------------------------===//
23 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
42 STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
45 class MachineLICM : public MachineFunctionPass {
46 const TargetMachine *TM;
47 const TargetInstrInfo *TII;
48 const TargetRegisterInfo *TRI;
49 BitVector AllocatableSet;
51 // Various analyses that we use...
52 AliasAnalysis *AA; // Alias analysis info.
53 MachineLoopInfo *LI; // Current MachineLoopInfo
54 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
55 MachineRegisterInfo *RegInfo; // Machine register information
57 // State that is updated as we process loops
58 bool Changed; // True if a loop is changed.
59 bool FirstInLoop; // True if it's the first LICM in the loop.
60 MachineLoop *CurLoop; // The current loop we are working on.
61 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
63 // For each opcode, keep a list of potentail CSE instructions.
64 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
66 static char ID; // Pass identification, replacement for typeid
67 MachineLICM() : MachineFunctionPass(&ID) {}
69 virtual bool runOnMachineFunction(MachineFunction &MF);
71 const char *getPassName() const { return "Machine Instruction LICM"; }
73 // FIXME: Loop preheaders?
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<MachineLoopInfo>();
77 AU.addRequired<MachineDominatorTree>();
78 AU.addRequired<AliasAnalysis>();
79 AU.addPreserved<MachineLoopInfo>();
80 AU.addPreserved<MachineDominatorTree>();
81 MachineFunctionPass::getAnalysisUsage(AU);
84 virtual void releaseMemory() {
89 /// IsLoopInvariantInst - Returns true if the instruction is loop
90 /// invariant. I.e., all virtual register operands are defined outside of
91 /// the loop, physical registers aren't accessed (explicitly or implicitly),
92 /// and the instruction is hoistable.
94 bool IsLoopInvariantInst(MachineInstr &I);
96 /// IsProfitableToHoist - Return true if it is potentially profitable to
97 /// hoist the given loop invariant.
98 bool IsProfitableToHoist(MachineInstr &MI);
100 /// HoistRegion - Walk the specified region of the CFG (defined by all
101 /// blocks dominated by the specified block, and that are in the current
102 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
103 /// visit definitions before uses, allowing us to hoist a loop body in one
104 /// pass without iteration.
106 void HoistRegion(MachineDomTreeNode *N);
108 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
109 /// the load itself could be hoisted. Return the unfolded and hoistable
110 /// load, or null if the load couldn't be unfolded or if it wouldn't
112 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
114 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
115 /// the preheader that compute the same value. If it's found, do a RAU on
116 /// with the definition of the existing instruction rather than hoisting
117 /// the instruction to the preheader.
118 bool EliminateCSE(MachineInstr *MI,
119 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
121 /// Hoist - When an instruction is found to only use loop invariant operands
122 /// that is safe to hoist, this instruction is called to do the dirty work.
124 void Hoist(MachineInstr *MI);
126 /// InitCSEMap - Initialize the CSE map with instructions that are in the
127 /// current loop preheader that may become duplicates of instructions that
128 /// are hoisted out of the loop.
129 void InitCSEMap(MachineBasicBlock *BB);
131 } // end anonymous namespace
133 char MachineLICM::ID = 0;
134 static RegisterPass<MachineLICM>
135 X("machinelicm", "Machine Loop Invariant Code Motion");
137 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
139 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
140 /// loop that has a preheader.
141 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
142 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
143 if (L->getLoopPreheader())
148 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
149 /// is not preserved so it is not a good idea to run LICM multiple times on one
152 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
153 DEBUG(errs() << "******** Machine LICM ********\n");
155 Changed = FirstInLoop = false;
156 TM = &MF.getTarget();
157 TII = TM->getInstrInfo();
158 TRI = TM->getRegisterInfo();
159 RegInfo = &MF.getRegInfo();
160 AllocatableSet = TRI->getAllocatableSet(MF);
162 // Get our Loop information...
163 LI = &getAnalysis<MachineLoopInfo>();
164 DT = &getAnalysis<MachineDominatorTree>();
165 AA = &getAnalysis<AliasAnalysis>();
167 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
170 // Only visit outer-most preheader-sporting loops.
171 if (!LoopIsOuterMostWithPreheader(CurLoop))
174 // Determine the block to which to hoist instructions. If we can't find a
175 // suitable loop preheader, we can't do any hoisting.
177 // FIXME: We are only hoisting if the basic block coming into this loop
178 // has only one successor. This isn't the case in general because we haven't
179 // broken critical edges or added preheaders.
180 CurPreheader = CurLoop->getLoopPreheader();
184 // CSEMap is initialized for loop header when the first instruction is
187 HoistRegion(DT->getNode(CurLoop->getHeader()));
194 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
195 /// dominated by the specified block, and that are in the current loop) in depth
196 /// first order w.r.t the DominatorTree. This allows us to visit definitions
197 /// before uses, allowing us to hoist a loop body in one pass without iteration.
199 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
200 assert(N != 0 && "Null dominator tree node?");
201 MachineBasicBlock *BB = N->getBlock();
203 // If this subregion is not in the top level loop at all, exit.
204 if (!CurLoop->contains(BB)) return;
206 for (MachineBasicBlock::iterator
207 MII = BB->begin(), E = BB->end(); MII != E; ) {
208 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
213 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
215 for (unsigned I = 0, E = Children.size(); I != E; ++I)
216 HoistRegion(Children[I]);
219 /// IsLoopInvariantInst - Returns true if the instruction is loop
220 /// invariant. I.e., all virtual register operands are defined outside of the
221 /// loop, physical registers aren't accessed explicitly, and there are no side
222 /// effects that aren't captured by the operands or other flags.
224 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
225 const TargetInstrDesc &TID = I.getDesc();
227 // Ignore stuff that we obviously can't hoist.
228 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
229 TID.hasUnmodeledSideEffects())
233 // Okay, this instruction does a load. As a refinement, we allow the target
234 // to decide whether the loaded value is actually a constant. If so, we can
235 // actually use it as a load.
236 if (!I.isInvariantLoad(AA))
237 // FIXME: we should be able to sink loads with no other side effects if
238 // there is nothing that can change memory from here until the end of
239 // block. This is a trivial form of alias analysis.
244 errs() << "--- Checking if we can hoist " << I;
245 if (I.getDesc().getImplicitUses()) {
246 errs() << " * Instruction has implicit uses:\n";
248 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
249 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
251 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
254 if (I.getDesc().getImplicitDefs()) {
255 errs() << " * Instruction has implicit defines:\n";
257 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
258 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
260 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
264 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
265 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
269 // The instruction is loop invariant if all of its operands are.
270 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
271 const MachineOperand &MO = I.getOperand(i);
276 unsigned Reg = MO.getReg();
277 if (Reg == 0) continue;
279 // Don't hoist an instruction that uses or defines a physical register.
280 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
282 // If the physreg has no defs anywhere, it's just an ambient register
283 // and we can freely move its uses. Alternatively, if it's allocatable,
284 // it could get allocated to something with a def during allocation.
285 if (!RegInfo->def_empty(Reg))
287 if (AllocatableSet.test(Reg))
289 // Check for a def among the register's aliases too.
290 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
291 unsigned AliasReg = *Alias;
292 if (!RegInfo->def_empty(AliasReg))
294 if (AllocatableSet.test(AliasReg))
297 // Otherwise it's safe to move.
299 } else if (!MO.isDead()) {
300 // A def that isn't dead. We can't move it.
308 assert(RegInfo->getVRegDef(Reg) &&
309 "Machine instr not mapped for this vreg?!");
311 // If the loop contains the definition of an operand, then the instruction
312 // isn't loop invariant.
313 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
317 // If we got this far, the instruction is loop invariant!
322 /// HasPHIUses - Return true if the specified register has any PHI use.
323 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
324 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
325 UE = RegInfo->use_end(); UI != UE; ++UI) {
326 MachineInstr *UseMI = &*UI;
327 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
333 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
334 /// the given loop invariant.
335 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
336 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
339 // FIXME: For now, only hoist re-materilizable instructions. LICM will
340 // increase register pressure. We want to make sure it doesn't increase
342 if (!TII->isTriviallyReMaterializable(&MI, AA))
345 // If result(s) of this instruction is used by PHIs, then don't hoist it.
346 // The presence of joins makes it difficult for current register allocator
347 // implementation to perform remat.
348 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
349 const MachineOperand &MO = MI.getOperand(i);
350 if (!MO.isReg() || !MO.isDef())
352 if (HasPHIUses(MO.getReg(), RegInfo))
359 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
360 // If not, we may be able to unfold a load and hoist that.
361 // First test whether the instruction is loading from an amenable
363 if (!MI->getDesc().mayLoad()) return 0;
364 if (!MI->hasOneMemOperand()) return 0;
365 MachineMemOperand *MMO = *MI->memoperands_begin();
366 if (MMO->isVolatile()) return 0;
367 MachineFunction &MF = *MI->getParent()->getParent();
368 if (!MMO->getValue()) return 0;
369 if (const PseudoSourceValue *PSV =
370 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
371 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
373 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
375 // Next determine the register class for a temporary register.
376 unsigned LoadRegIndex;
378 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
380 /*UnfoldStore=*/false,
382 if (NewOpc == 0) return 0;
383 const TargetInstrDesc &TID = TII->get(NewOpc);
384 if (TID.getNumDefs() != 1) return 0;
385 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
386 // Ok, we're unfolding. Create a temporary register and do the unfold.
387 unsigned Reg = RegInfo->createVirtualRegister(RC);
388 SmallVector<MachineInstr *, 2> NewMIs;
390 TII->unfoldMemoryOperand(MF, MI, Reg,
391 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
395 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
397 assert(NewMIs.size() == 2 &&
398 "Unfolded a load into multiple instructions!");
399 MachineBasicBlock *MBB = MI->getParent();
400 MBB->insert(MI, NewMIs[0]);
401 MBB->insert(MI, NewMIs[1]);
402 // If unfolding produced a load that wasn't loop-invariant or profitable to
403 // hoist, discard the new instructions and bail.
404 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
405 NewMIs[0]->eraseFromParent();
406 NewMIs[1]->eraseFromParent();
409 // Otherwise we successfully unfolded a load that we can hoist.
410 MI->eraseFromParent();
414 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
415 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
416 const MachineInstr *MI = &*I;
417 // FIXME: For now, only hoist re-materilizable instructions. LICM will
418 // increase register pressure. We want to make sure it doesn't increase
420 if (TII->isTriviallyReMaterializable(MI, AA)) {
421 unsigned Opcode = MI->getOpcode();
422 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
423 CI = CSEMap.find(Opcode);
424 if (CI != CSEMap.end())
425 CI->second.push_back(MI);
427 std::vector<const MachineInstr*> CSEMIs;
428 CSEMIs.push_back(MI);
429 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
435 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
436 std::vector<const MachineInstr*> &PrevMIs,
437 MachineRegisterInfo *RegInfo) {
438 unsigned NumOps = MI->getNumOperands();
439 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
440 const MachineInstr *PrevMI = PrevMIs[i];
441 unsigned NumOps2 = PrevMI->getNumOperands();
442 if (NumOps != NumOps2)
445 for (unsigned j = 0; j != NumOps; ++j) {
446 const MachineOperand &MO = MI->getOperand(j);
447 if (MO.isReg() && MO.isDef()) {
448 if (RegInfo->getRegClass(MO.getReg()) !=
449 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
455 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
466 bool MachineLICM::EliminateCSE(MachineInstr *MI,
467 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
468 if (CI != CSEMap.end()) {
469 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo)) {
470 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
471 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
472 const MachineOperand &MO = MI->getOperand(i);
473 if (MO.isReg() && MO.isDef())
474 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
476 MI->eraseFromParent();
484 /// Hoist - When an instruction is found to use only loop invariant operands
485 /// that are safe to hoist, this instruction is called to do the dirty work.
487 void MachineLICM::Hoist(MachineInstr *MI) {
488 // First check whether we should hoist this instruction.
489 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
490 // If not, try unfolding a hoistable load.
491 MI = ExtractHoistableLoad(MI);
495 // Now move the instructions to the predecessor, inserting it before any
496 // terminator instructions.
498 errs() << "Hoisting " << *MI;
499 if (CurPreheader->getBasicBlock())
500 errs() << " to MachineBasicBlock "
501 << CurPreheader->getBasicBlock()->getName();
502 if (MI->getParent()->getBasicBlock())
503 errs() << " from MachineBasicBlock "
504 << MI->getParent()->getBasicBlock()->getName();
508 // If this is the first instruction being hoisted to the preheader,
509 // initialize the CSE map with potential common expressions.
510 InitCSEMap(CurPreheader);
512 // Look for opportunity to CSE the hoisted instruction.
513 unsigned Opcode = MI->getOpcode();
514 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
515 CI = CSEMap.find(Opcode);
516 if (!EliminateCSE(MI, CI)) {
517 // Otherwise, splice the instruction to the preheader.
518 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
520 // Add to the CSE map.
521 if (CI != CSEMap.end())
522 CI->second.push_back(MI);
524 std::vector<const MachineInstr*> CSEMIs;
525 CSEMIs.push_back(MI);
526 CSEMap.insert(std::make_pair(Opcode, CSEMIs));