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/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/MC/MCInstrItineraries.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
45 "Number of machine instructions hoisted out of loops");
47 "Number of instructions hoisted in low reg pressure situation");
48 STATISTIC(NumHighLatency,
49 "Number of high latency instructions hoisted");
51 "Number of hoisted machine instructions CSEed");
52 STATISTIC(NumPostRAHoisted,
53 "Number of machine instructions hoisted out of loops post regalloc");
56 class MachineLICM : public MachineFunctionPass {
59 const TargetMachine *TM;
60 const TargetInstrInfo *TII;
61 const TargetLowering *TLI;
62 const TargetRegisterInfo *TRI;
63 const MachineFrameInfo *MFI;
64 MachineRegisterInfo *MRI;
65 const InstrItineraryData *InstrItins;
67 // Various analyses that we use...
68 AliasAnalysis *AA; // Alias analysis info.
69 MachineLoopInfo *MLI; // Current MachineLoopInfo
70 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
72 // State that is updated as we process loops
73 bool Changed; // True if a loop is changed.
74 bool FirstInLoop; // True if it's the first LICM in the loop.
75 MachineLoop *CurLoop; // The current loop we are working on.
76 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
78 BitVector AllocatableSet;
80 // Track 'estimated' register pressure.
81 SmallSet<unsigned, 32> RegSeen;
82 SmallVector<unsigned, 8> RegPressure;
84 // Register pressure "limit" per register class. If the pressure
85 // is higher than the limit, then it's considered high.
86 SmallVector<unsigned, 8> RegLimit;
88 // Register pressure on path leading from loop preheader to current BB.
89 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
91 // For each opcode, keep a list of potential CSE instructions.
92 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
100 // If a MBB does not dominate loop exiting blocks then it may not safe
101 // to hoist loads from this block.
102 // Tri-state: 0 - false, 1 - true, 2 - unknown
103 unsigned SpeculationState;
106 static char ID; // Pass identification, replacement for typeid
108 MachineFunctionPass(ID), PreRegAlloc(true) {
109 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
112 explicit MachineLICM(bool PreRA) :
113 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
114 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
117 virtual bool runOnMachineFunction(MachineFunction &MF);
119 const char *getPassName() const { return "Machine Instruction LICM"; }
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.addRequired<MachineLoopInfo>();
123 AU.addRequired<MachineDominatorTree>();
124 AU.addRequired<AliasAnalysis>();
125 AU.addPreserved<MachineLoopInfo>();
126 AU.addPreserved<MachineDominatorTree>();
127 MachineFunctionPass::getAnalysisUsage(AU);
130 virtual void releaseMemory() {
135 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
136 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
142 /// CandidateInfo - Keep track of information about hoisting candidates.
143 struct CandidateInfo {
147 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
148 : MI(mi), Def(def), FI(fi) {}
151 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
152 /// invariants out to the preheader.
153 void HoistRegionPostRA();
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
158 void HoistPostRA(MachineInstr *MI, unsigned Def);
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);
166 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
168 void AddToLiveIns(unsigned Reg);
170 /// IsLICMCandidate - Returns true if the instruction may be a suitable
171 /// candidate for LICM. e.g. If the instruction is a call, then it's
172 /// obviously not safe to hoist it.
173 bool IsLICMCandidate(MachineInstr &I);
175 /// IsLoopInvariantInst - Returns true if the instruction is loop
176 /// 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.
180 bool IsLoopInvariantInst(MachineInstr &I);
182 /// HasAnyPHIUse - Return true if the specified register is used by any
184 bool HasAnyPHIUse(unsigned Reg) const;
186 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
187 /// and an use in the current loop, return true if the target considered
189 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
192 bool IsCheapInstruction(MachineInstr &MI) const;
194 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
195 /// check if hoisting an instruction of the given cost matrix can cause high
196 /// register pressure.
197 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
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);
204 /// IsProfitableToHoist - Return true if it is potentially profitable to
205 /// hoist the given loop invariant.
206 bool IsProfitableToHoist(MachineInstr &MI);
208 /// 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);
212 /// 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.
218 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
220 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
221 /// index, return the ID and cost of its representative register class by
223 void getRegisterClassIDAndCost(const MachineInstr *MI,
224 unsigned Reg, unsigned OpIdx,
225 unsigned &RCId, unsigned &RCCost) const;
227 /// 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.
230 void InitRegPressure(MachineBasicBlock *BB);
232 /// UpdateRegPressure - Update estimate of register pressure after the
233 /// specified instruction.
234 void UpdateRegPressure(const MachineInstr *MI);
236 /// 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
240 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
242 /// 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);
247 /// 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);
254 /// MayCSE - Return true if the given instruction will be CSE'd if it's
255 /// hoisted out of the loop.
256 bool MayCSE(MachineInstr *MI);
258 /// Hoist - When an instruction is found to only use loop invariant operands
259 /// that is safe to hoist, this instruction is called to do the dirty work.
260 /// It returns true if the instruction is hoisted.
261 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
263 /// InitCSEMap - Initialize the CSE map with instructions that are in the
264 /// current loop preheader that may become duplicates of instructions that
265 /// are hoisted out of the loop.
266 void InitCSEMap(MachineBasicBlock *BB);
268 /// getCurPreheader - Get the preheader for the current loop, splitting
269 /// a critical edge if needed.
270 MachineBasicBlock *getCurPreheader();
272 } // end anonymous namespace
274 char MachineLICM::ID = 0;
275 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
276 "Machine Loop Invariant Code Motion", false, false)
277 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
278 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
279 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
280 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
281 "Machine Loop Invariant Code Motion", false, false)
283 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
284 return new MachineLICM(PreRegAlloc);
287 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
288 /// loop that has a unique predecessor.
289 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
290 // Check whether this loop even has a unique predecessor.
291 if (!CurLoop->getLoopPredecessor())
293 // Ok, now check to see if any of its outer loops do.
294 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
295 if (L->getLoopPredecessor())
297 // None of them did, so this is the outermost with a unique predecessor.
301 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
303 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
305 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
306 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
308 Changed = FirstInLoop = false;
309 TM = &MF.getTarget();
310 TII = TM->getInstrInfo();
311 TLI = TM->getTargetLowering();
312 TRI = TM->getRegisterInfo();
313 MFI = MF.getFrameInfo();
314 MRI = &MF.getRegInfo();
315 InstrItins = TM->getInstrItineraryData();
316 AllocatableSet = TRI->getAllocatableSet(MF);
319 // Estimate register pressure during pre-regalloc pass.
320 unsigned NumRC = TRI->getNumRegClasses();
321 RegPressure.resize(NumRC);
322 std::fill(RegPressure.begin(), RegPressure.end(), 0);
323 RegLimit.resize(NumRC);
324 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
325 E = TRI->regclass_end(); I != E; ++I)
326 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
329 // Get our Loop information...
330 MLI = &getAnalysis<MachineLoopInfo>();
331 DT = &getAnalysis<MachineDominatorTree>();
332 AA = &getAnalysis<AliasAnalysis>();
334 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
335 while (!Worklist.empty()) {
336 CurLoop = Worklist.pop_back_val();
339 // If this is done before regalloc, only visit outer-most preheader-sporting
341 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
342 Worklist.append(CurLoop->begin(), CurLoop->end());
346 // If the header is a landing pad, then we don't want to hoist instructions
347 // out of it. This can happen with SjLj exception handling which has a
348 // dispatch table as the landing pad.
349 if (CurLoop->getHeader()->isLandingPad()) continue;
354 // CSEMap is initialized for loop header when the first instruction is
356 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
358 HoistRegion(N, true);
366 /// InstructionStoresToFI - Return true if instruction stores to the
368 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
369 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
370 oe = MI->memoperands_end(); o != oe; ++o) {
371 if (!(*o)->isStore() || !(*o)->getValue())
373 if (const FixedStackPseudoSourceValue *Value =
374 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
375 if (Value->getFrameIndex() == FI)
382 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
383 /// gather register def and frame object update information.
384 void MachineLICM::ProcessMI(MachineInstr *MI,
385 unsigned *PhysRegDefs,
386 SmallSet<int, 32> &StoredFIs,
387 SmallVector<CandidateInfo, 32> &Candidates) {
388 bool RuledOut = false;
389 bool HasNonInvariantUse = false;
391 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
392 const MachineOperand &MO = MI->getOperand(i);
394 // Remember if the instruction stores to the frame index.
395 int FI = MO.getIndex();
396 if (!StoredFIs.count(FI) &&
397 MFI->isSpillSlotObjectIndex(FI) &&
398 InstructionStoresToFI(MI, FI))
399 StoredFIs.insert(FI);
400 HasNonInvariantUse = true;
406 unsigned Reg = MO.getReg();
409 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
410 "Not expecting virtual register!");
413 if (Reg && PhysRegDefs[Reg])
414 // If it's using a non-loop-invariant register, then it's obviously not
416 HasNonInvariantUse = true;
420 if (MO.isImplicit()) {
422 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
425 // Non-dead implicit def? This cannot be hoisted.
427 // No need to check if a dead implicit def is also defined by
428 // another instruction.
432 // FIXME: For now, avoid instructions with multiple defs, unless
433 // it's a dead implicit def.
439 // If we have already seen another instruction that defines the same
440 // register, then this is not safe.
441 if (++PhysRegDefs[Reg] > 1)
442 // MI defined register is seen defined by another instruction in
443 // the loop, it cannot be a LICM candidate.
445 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
446 if (++PhysRegDefs[*AS] > 1)
450 // Only consider reloads for now and remats which do not have register
451 // operands. FIXME: Consider unfold load folding instructions.
452 if (Def && !RuledOut) {
454 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
455 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
456 Candidates.push_back(CandidateInfo(MI, Def, FI));
460 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
461 /// invariants out to the preheader.
462 void MachineLICM::HoistRegionPostRA() {
463 unsigned NumRegs = TRI->getNumRegs();
464 unsigned *PhysRegDefs = new unsigned[NumRegs];
465 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
467 SmallVector<CandidateInfo, 32> Candidates;
468 SmallSet<int, 32> StoredFIs;
470 // Walk the entire region, count number of defs for each register, and
471 // collect potential LICM candidates.
472 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
473 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
474 MachineBasicBlock *BB = Blocks[i];
475 // Conservatively treat live-in's as an external def.
476 // FIXME: That means a reload that're reused in successor block(s) will not
478 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
479 E = BB->livein_end(); I != E; ++I) {
482 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
486 SpeculationState = SpeculateUnknown;
487 for (MachineBasicBlock::iterator
488 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
489 MachineInstr *MI = &*MII;
490 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
494 // Now evaluate whether the potential candidates qualify.
495 // 1. Check if the candidate defined register is defined by another
496 // instruction in the loop.
497 // 2. If the candidate is a load from stack slot (always true for now),
498 // check if the slot is stored anywhere in the loop.
499 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
500 if (Candidates[i].FI != INT_MIN &&
501 StoredFIs.count(Candidates[i].FI))
504 if (PhysRegDefs[Candidates[i].Def] == 1) {
506 MachineInstr *MI = Candidates[i].MI;
507 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
508 const MachineOperand &MO = MI->getOperand(j);
509 if (!MO.isReg() || MO.isDef() || !MO.getReg())
511 if (PhysRegDefs[MO.getReg()]) {
512 // If it's using a non-loop-invariant register, then it's obviously
513 // not safe to hoist.
519 HoistPostRA(MI, Candidates[i].Def);
523 delete[] PhysRegDefs;
526 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
527 /// loop, and make sure it is not killed by any instructions in the loop.
528 void MachineLICM::AddToLiveIns(unsigned Reg) {
529 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
530 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
531 MachineBasicBlock *BB = Blocks[i];
532 if (!BB->isLiveIn(Reg))
534 for (MachineBasicBlock::iterator
535 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
536 MachineInstr *MI = &*MII;
537 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
538 MachineOperand &MO = MI->getOperand(i);
539 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
540 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
547 /// HoistPostRA - When an instruction is found to only use loop invariant
548 /// operands that is safe to hoist, this instruction is called to do the
550 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
551 MachineBasicBlock *Preheader = getCurPreheader();
552 if (!Preheader) return;
554 // Now move the instructions to the predecessor, inserting it before any
555 // terminator instructions.
557 dbgs() << "Hoisting " << *MI;
558 if (Preheader->getBasicBlock())
559 dbgs() << " to MachineBasicBlock "
560 << Preheader->getName();
561 if (MI->getParent()->getBasicBlock())
562 dbgs() << " from MachineBasicBlock "
563 << MI->getParent()->getName();
567 // Splice the instruction to the preheader.
568 MachineBasicBlock *MBB = MI->getParent();
569 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
571 // Add register to livein list to all the BBs in the current loop since a
572 // loop invariant must be kept live throughout the whole loop. This is
573 // important to ensure later passes do not scavenge the def register.
580 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
581 // If not then a load from this mbb may not be safe to hoist.
582 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
583 if (SpeculationState != SpeculateUnknown)
584 return SpeculationState == SpeculateFalse;
586 if (BB != CurLoop->getHeader()) {
587 // Check loop exiting blocks.
588 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
589 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
590 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
591 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
592 SpeculationState = SpeculateTrue;
597 SpeculationState = SpeculateFalse;
601 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
602 /// dominated by the specified block, and that are in the current loop) in depth
603 /// first order w.r.t the DominatorTree. This allows us to visit definitions
604 /// before uses, allowing us to hoist a loop body in one pass without iteration.
606 void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
607 assert(N != 0 && "Null dominator tree node?");
608 MachineBasicBlock *BB = N->getBlock();
610 // If this subregion is not in the top level loop at all, exit.
611 if (!CurLoop->contains(BB)) return;
613 MachineBasicBlock *Preheader = getCurPreheader();
618 // Compute registers which are livein into the loop headers.
621 InitRegPressure(Preheader);
624 // Remember livein register pressure.
625 BackTrace.push_back(RegPressure);
627 SpeculationState = SpeculateUnknown;
628 for (MachineBasicBlock::iterator
629 MII = BB->begin(), E = BB->end(); MII != E; ) {
630 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
631 MachineInstr *MI = &*MII;
632 if (!Hoist(MI, Preheader))
633 UpdateRegPressure(MI);
637 // Don't hoist things out of a large switch statement. This often causes
638 // code to be hoisted that wasn't going to be executed, and increases
639 // register pressure in a situation where it's likely to matter.
640 if (BB->succ_size() < 25) {
641 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
642 for (unsigned I = 0, E = Children.size(); I != E; ++I)
643 HoistRegion(Children[I]);
646 BackTrace.pop_back();
649 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
650 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
653 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
654 /// index, return the ID and cost of its representative register class.
656 MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
657 unsigned Reg, unsigned OpIdx,
658 unsigned &RCId, unsigned &RCCost) const {
659 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
660 EVT VT = *RC->vt_begin();
661 if (VT == MVT::untyped) {
665 RCId = TLI->getRepRegClassFor(VT)->getID();
666 RCCost = TLI->getRepRegClassCostFor(VT);
670 /// InitRegPressure - Find all virtual register references that are liveout of
671 /// the preheader to initialize the starting "register pressure". Note this
672 /// does not count live through (livein but not used) registers.
673 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
674 std::fill(RegPressure.begin(), RegPressure.end(), 0);
676 // If the preheader has only a single predecessor and it ends with a
677 // fallthrough or an unconditional branch, then scan its predecessor for live
678 // defs as well. This happens whenever the preheader is created by splitting
679 // the critical edge from the loop predecessor to the loop header.
680 if (BB->pred_size() == 1) {
681 MachineBasicBlock *TBB = 0, *FBB = 0;
682 SmallVector<MachineOperand, 4> Cond;
683 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
684 InitRegPressure(*BB->pred_begin());
687 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
689 MachineInstr *MI = &*MII;
690 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
691 const MachineOperand &MO = MI->getOperand(i);
692 if (!MO.isReg() || MO.isImplicit())
694 unsigned Reg = MO.getReg();
695 if (!TargetRegisterInfo::isVirtualRegister(Reg))
698 bool isNew = RegSeen.insert(Reg);
699 unsigned RCId, RCCost;
700 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
702 RegPressure[RCId] += RCCost;
704 bool isKill = isOperandKill(MO, MRI);
705 if (isNew && !isKill)
706 // Haven't seen this, it must be a livein.
707 RegPressure[RCId] += RCCost;
708 else if (!isNew && isKill)
709 RegPressure[RCId] -= RCCost;
715 /// UpdateRegPressure - Update estimate of register pressure after the
716 /// specified instruction.
717 void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
718 if (MI->isImplicitDef())
721 SmallVector<unsigned, 4> Defs;
722 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
723 const MachineOperand &MO = MI->getOperand(i);
724 if (!MO.isReg() || MO.isImplicit())
726 unsigned Reg = MO.getReg();
727 if (!TargetRegisterInfo::isVirtualRegister(Reg))
730 bool isNew = RegSeen.insert(Reg);
733 else if (!isNew && isOperandKill(MO, MRI)) {
734 unsigned RCId, RCCost;
735 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
736 if (RCCost > RegPressure[RCId])
737 RegPressure[RCId] = 0;
739 RegPressure[RCId] -= RCCost;
744 while (!Defs.empty()) {
745 unsigned Reg = Defs.pop_back_val();
746 unsigned RCId, RCCost;
747 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
748 RegPressure[RCId] += RCCost;
753 /// IsLICMCandidate - Returns true if the instruction may be a suitable
754 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
755 /// not safe to hoist it.
756 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
757 // Check if it's safe to move the instruction.
758 bool DontMoveAcrossStore = true;
759 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
762 // If it is load then check if it is guaranteed to execute by making sure that
763 // it dominates all exiting blocks. If it doesn't, then there is a path out of
764 // the loop which does not execute this load, so we can't hoist it.
765 // Stores and side effects are already checked by isSafeToMove.
766 if (I.getDesc().mayLoad() && !IsGuaranteedToExecute(I.getParent()))
772 /// IsLoopInvariantInst - Returns true if the instruction is loop
773 /// invariant. I.e., all virtual register operands are defined outside of the
774 /// loop, physical registers aren't accessed explicitly, and there are no side
775 /// effects that aren't captured by the operands or other flags.
777 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
778 if (!IsLICMCandidate(I))
781 // The instruction is loop invariant if all of its operands are.
782 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
783 const MachineOperand &MO = I.getOperand(i);
788 unsigned Reg = MO.getReg();
789 if (Reg == 0) continue;
791 // Don't hoist an instruction that uses or defines a physical register.
792 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
794 // If the physreg has no defs anywhere, it's just an ambient register
795 // and we can freely move its uses. Alternatively, if it's allocatable,
796 // it could get allocated to something with a def during allocation.
797 if (!MRI->def_empty(Reg))
799 if (AllocatableSet.test(Reg))
801 // Check for a def among the register's aliases too.
802 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
803 unsigned AliasReg = *Alias;
804 if (!MRI->def_empty(AliasReg))
806 if (AllocatableSet.test(AliasReg))
809 // Otherwise it's safe to move.
811 } else if (!MO.isDead()) {
812 // A def that isn't dead. We can't move it.
814 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
815 // If the reg is live into the loop, we can't hoist an instruction
816 // which would clobber it.
824 assert(MRI->getVRegDef(Reg) &&
825 "Machine instr not mapped for this vreg?!");
827 // If the loop contains the definition of an operand, then the instruction
828 // isn't loop invariant.
829 if (CurLoop->contains(MRI->getVRegDef(Reg)))
833 // If we got this far, the instruction is loop invariant!
838 /// HasAnyPHIUse - Return true if the specified register is used by any
840 bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
841 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
842 UE = MRI->use_end(); UI != UE; ++UI) {
843 MachineInstr *UseMI = &*UI;
846 // Look pass copies as well.
847 if (UseMI->isCopy()) {
848 unsigned Def = UseMI->getOperand(0).getReg();
849 if (TargetRegisterInfo::isVirtualRegister(Def) &&
857 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
858 /// and an use in the current loop, return true if the target considered
860 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
861 unsigned DefIdx, unsigned Reg) const {
862 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
865 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
866 E = MRI->use_nodbg_end(); I != E; ++I) {
867 MachineInstr *UseMI = &*I;
868 if (UseMI->isCopyLike())
870 if (!CurLoop->contains(UseMI->getParent()))
872 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
873 const MachineOperand &MO = UseMI->getOperand(i);
874 if (!MO.isReg() || !MO.isUse())
876 unsigned MOReg = MO.getReg();
880 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
884 // Only look at the first in loop use.
891 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
892 /// the operand latency between its def and a use is one or less.
893 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
894 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
896 if (!InstrItins || InstrItins->isEmpty())
899 bool isCheap = false;
900 unsigned NumDefs = MI.getDesc().getNumDefs();
901 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
902 MachineOperand &DefMO = MI.getOperand(i);
903 if (!DefMO.isReg() || !DefMO.isDef())
906 unsigned Reg = DefMO.getReg();
907 if (TargetRegisterInfo::isPhysicalRegister(Reg))
910 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
918 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
919 /// if hoisting an instruction of the given cost matrix can cause high
920 /// register pressure.
921 bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
922 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
927 unsigned RCId = CI->first;
928 for (unsigned i = BackTrace.size(); i != 0; --i) {
929 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
930 if (RP[RCId] + CI->second >= RegLimit[RCId])
938 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
939 /// current block and update their register pressures to reflect the effect
940 /// of hoisting MI from the current block to the preheader.
941 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
942 if (MI->isImplicitDef())
945 // First compute the 'cost' of the instruction, i.e. its contribution
946 // to register pressure.
947 DenseMap<unsigned, int> Cost;
948 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
949 const MachineOperand &MO = MI->getOperand(i);
950 if (!MO.isReg() || MO.isImplicit())
952 unsigned Reg = MO.getReg();
953 if (!TargetRegisterInfo::isVirtualRegister(Reg))
956 unsigned RCId, RCCost;
957 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
959 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
960 if (CI != Cost.end())
961 CI->second += RCCost;
963 Cost.insert(std::make_pair(RCId, RCCost));
964 } else if (isOperandKill(MO, MRI)) {
965 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
966 if (CI != Cost.end())
967 CI->second -= RCCost;
969 Cost.insert(std::make_pair(RCId, -RCCost));
973 // Update register pressure of blocks from loop header to current block.
974 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
975 SmallVector<unsigned, 8> &RP = BackTrace[i];
976 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
978 unsigned RCId = CI->first;
979 RP[RCId] += CI->second;
984 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
985 /// the given loop invariant.
986 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
987 if (MI.isImplicitDef())
990 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
991 // will increase register pressure. It's probably not worth it if the
992 // instruction is cheap.
993 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
994 // these tend to help performance in low register pressure situation. The
995 // trade off is it may cause spill in high pressure situation. It will end up
996 // adding a store in the loop preheader. But the reload is no more expensive.
997 // The side benefit is these loads are frequently CSE'ed.
998 if (IsCheapInstruction(MI)) {
999 if (!TII->isTriviallyReMaterializable(&MI, AA))
1002 // Estimate register pressure to determine whether to LICM the instruction.
1003 // In low register pressure situation, we can be more aggressive about
1004 // hoisting. Also, favors hoisting long latency instructions even in
1005 // moderately high pressure situation.
1006 // FIXME: If there are long latency loop-invariant instructions inside the
1007 // loop at this point, why didn't the optimizer's LICM hoist them?
1008 DenseMap<unsigned, int> Cost;
1009 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1010 const MachineOperand &MO = MI.getOperand(i);
1011 if (!MO.isReg() || MO.isImplicit())
1013 unsigned Reg = MO.getReg();
1014 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1017 unsigned RCId, RCCost;
1018 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1020 if (HasHighOperandLatency(MI, i, Reg)) {
1025 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1026 if (CI != Cost.end())
1027 CI->second += RCCost;
1029 Cost.insert(std::make_pair(RCId, RCCost));
1030 } else if (isOperandKill(MO, MRI)) {
1031 // Is a virtual register use is a kill, hoisting it out of the loop
1032 // may actually reduce register pressure or be register pressure
1034 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1035 if (CI != Cost.end())
1036 CI->second -= RCCost;
1038 Cost.insert(std::make_pair(RCId, -RCCost));
1042 // Visit BBs from header to current BB, if hoisting this doesn't cause
1043 // high register pressure, then it's safe to proceed.
1044 if (!CanCauseHighRegPressure(Cost)) {
1049 // High register pressure situation, only hoist if the instruction is going to
1051 // Also, do not "speculate" in high register pressure situation. If an
1052 // instruction is not guaranteed to be executed in the loop, it's best to be
1054 if ((!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)) ||
1055 (!TII->isTriviallyReMaterializable(&MI, AA) &&
1056 !MI.isInvariantLoad(AA)))
1060 // If result(s) of this instruction is used by PHIs outside of the loop, then
1061 // don't hoist it if the instruction because it will introduce an extra copy.
1062 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1063 const MachineOperand &MO = MI.getOperand(i);
1064 if (!MO.isReg() || !MO.isDef())
1066 if (HasAnyPHIUse(MO.getReg()))
1073 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1074 // Don't unfold simple loads.
1075 if (MI->getDesc().canFoldAsLoad())
1078 // If not, we may be able to unfold a load and hoist that.
1079 // First test whether the instruction is loading from an amenable
1081 if (!MI->isInvariantLoad(AA))
1084 // Next determine the register class for a temporary register.
1085 unsigned LoadRegIndex;
1087 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1088 /*UnfoldLoad=*/true,
1089 /*UnfoldStore=*/false,
1091 if (NewOpc == 0) return 0;
1092 const MCInstrDesc &MID = TII->get(NewOpc);
1093 if (MID.getNumDefs() != 1) return 0;
1094 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
1095 // Ok, we're unfolding. Create a temporary register and do the unfold.
1096 unsigned Reg = MRI->createVirtualRegister(RC);
1098 MachineFunction &MF = *MI->getParent()->getParent();
1099 SmallVector<MachineInstr *, 2> NewMIs;
1101 TII->unfoldMemoryOperand(MF, MI, Reg,
1102 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1106 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1108 assert(NewMIs.size() == 2 &&
1109 "Unfolded a load into multiple instructions!");
1110 MachineBasicBlock *MBB = MI->getParent();
1111 MBB->insert(MI, NewMIs[0]);
1112 MBB->insert(MI, NewMIs[1]);
1113 // If unfolding produced a load that wasn't loop-invariant or profitable to
1114 // hoist, discard the new instructions and bail.
1115 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1116 NewMIs[0]->eraseFromParent();
1117 NewMIs[1]->eraseFromParent();
1121 // Update register pressure for the unfolded instruction.
1122 UpdateRegPressure(NewMIs[1]);
1124 // Otherwise we successfully unfolded a load that we can hoist.
1125 MI->eraseFromParent();
1129 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1130 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1131 const MachineInstr *MI = &*I;
1132 unsigned Opcode = MI->getOpcode();
1133 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1134 CI = CSEMap.find(Opcode);
1135 if (CI != CSEMap.end())
1136 CI->second.push_back(MI);
1138 std::vector<const MachineInstr*> CSEMIs;
1139 CSEMIs.push_back(MI);
1140 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1146 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1147 std::vector<const MachineInstr*> &PrevMIs) {
1148 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1149 const MachineInstr *PrevMI = PrevMIs[i];
1150 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
1156 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1157 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1158 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1159 // the undef property onto uses.
1160 if (CI == CSEMap.end() || MI->isImplicitDef())
1163 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1164 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1166 // Replace virtual registers defined by MI by their counterparts defined
1168 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1169 const MachineOperand &MO = MI->getOperand(i);
1171 // Physical registers may not differ here.
1172 assert((!MO.isReg() || MO.getReg() == 0 ||
1173 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1174 MO.getReg() == Dup->getOperand(i).getReg()) &&
1175 "Instructions with different phys regs are not identical!");
1177 if (MO.isReg() && MO.isDef() &&
1178 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
1179 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1180 MRI->clearKillFlags(Dup->getOperand(i).getReg());
1183 MI->eraseFromParent();
1190 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1191 /// hoisted out of the loop.
1192 bool MachineLICM::MayCSE(MachineInstr *MI) {
1193 unsigned Opcode = MI->getOpcode();
1194 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1195 CI = CSEMap.find(Opcode);
1196 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1197 // the undef property onto uses.
1198 if (CI == CSEMap.end() || MI->isImplicitDef())
1201 return LookForDuplicate(MI, CI->second) != 0;
1204 /// Hoist - When an instruction is found to use only loop invariant operands
1205 /// that are safe to hoist, this instruction is called to do the dirty work.
1207 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1208 // First check whether we should hoist this instruction.
1209 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1210 // If not, try unfolding a hoistable load.
1211 MI = ExtractHoistableLoad(MI);
1212 if (!MI) return false;
1215 // Now move the instructions to the predecessor, inserting it before any
1216 // terminator instructions.
1218 dbgs() << "Hoisting " << *MI;
1219 if (Preheader->getBasicBlock())
1220 dbgs() << " to MachineBasicBlock "
1221 << Preheader->getName();
1222 if (MI->getParent()->getBasicBlock())
1223 dbgs() << " from MachineBasicBlock "
1224 << MI->getParent()->getName();
1228 // If this is the first instruction being hoisted to the preheader,
1229 // initialize the CSE map with potential common expressions.
1231 InitCSEMap(Preheader);
1232 FirstInLoop = false;
1235 // Look for opportunity to CSE the hoisted instruction.
1236 unsigned Opcode = MI->getOpcode();
1237 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1238 CI = CSEMap.find(Opcode);
1239 if (!EliminateCSE(MI, CI)) {
1240 // Otherwise, splice the instruction to the preheader.
1241 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1243 // Update register pressure for BBs from header to this block.
1244 UpdateBackTraceRegPressure(MI);
1246 // Clear the kill flags of any register this instruction defines,
1247 // since they may need to be live throughout the entire loop
1248 // rather than just live for part of it.
1249 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1250 MachineOperand &MO = MI->getOperand(i);
1251 if (MO.isReg() && MO.isDef() && !MO.isDead())
1252 MRI->clearKillFlags(MO.getReg());
1255 // Add to the CSE map.
1256 if (CI != CSEMap.end())
1257 CI->second.push_back(MI);
1259 std::vector<const MachineInstr*> CSEMIs;
1260 CSEMIs.push_back(MI);
1261 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1271 MachineBasicBlock *MachineLICM::getCurPreheader() {
1272 // Determine the block to which to hoist instructions. If we can't find a
1273 // suitable loop predecessor, we can't do any hoisting.
1275 // If we've tried to get a preheader and failed, don't try again.
1276 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1279 if (!CurPreheader) {
1280 CurPreheader = CurLoop->getLoopPreheader();
1281 if (!CurPreheader) {
1282 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1284 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1288 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1289 if (!CurPreheader) {
1290 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1295 return CurPreheader;