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 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/PseudoSourceValue.h"
34 #include "llvm/MC/MCInstrItineraries.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "machine-licm"
48 AvoidSpeculation("avoid-speculation",
49 cl::desc("MachineLICM should avoid speculation"),
50 cl::init(true), cl::Hidden);
53 HoistCheapInsts("hoist-cheap-insts",
54 cl::desc("MachineLICM should hoist even cheap instructions"),
55 cl::init(false), cl::Hidden);
58 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
59 cl::desc("MachineLICM should sink instructions into "
60 "loops to avoid register spills"),
61 cl::init(false), cl::Hidden);
64 "Number of machine instructions hoisted out of loops");
66 "Number of instructions hoisted in low reg pressure situation");
67 STATISTIC(NumHighLatency,
68 "Number of high latency instructions hoisted");
70 "Number of hoisted machine instructions CSEed");
71 STATISTIC(NumPostRAHoisted,
72 "Number of machine instructions hoisted out of loops post regalloc");
75 class MachineLICM : public MachineFunctionPass {
76 const TargetInstrInfo *TII;
77 const TargetLoweringBase *TLI;
78 const TargetRegisterInfo *TRI;
79 const MachineFrameInfo *MFI;
80 MachineRegisterInfo *MRI;
81 const InstrItineraryData *InstrItins;
84 // Various analyses that we use...
85 AliasAnalysis *AA; // Alias analysis info.
86 MachineLoopInfo *MLI; // Current MachineLoopInfo
87 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
89 // State that is updated as we process loops
90 bool Changed; // True if a loop is changed.
91 bool FirstInLoop; // True if it's the first LICM in the loop.
92 MachineLoop *CurLoop; // The current loop we are working on.
93 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
95 // Exit blocks for CurLoop.
96 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
98 bool isExitBlock(const MachineBasicBlock *MBB) const {
99 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
103 // Track 'estimated' register pressure.
104 SmallSet<unsigned, 32> RegSeen;
105 SmallVector<unsigned, 8> RegPressure;
107 // Register pressure "limit" per register class. If the pressure
108 // is higher than the limit, then it's considered high.
109 SmallVector<unsigned, 8> RegLimit;
111 // Register pressure on path leading from loop preheader to current BB.
112 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
114 // For each opcode, keep a list of potential CSE instructions.
115 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
123 // If a MBB does not dominate loop exiting blocks then it may not safe
124 // to hoist loads from this block.
125 // Tri-state: 0 - false, 1 - true, 2 - unknown
126 unsigned SpeculationState;
129 static char ID; // Pass identification, replacement for typeid
131 MachineFunctionPass(ID), PreRegAlloc(true) {
132 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
135 explicit MachineLICM(bool PreRA) :
136 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
137 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
140 bool runOnMachineFunction(MachineFunction &MF) override;
142 void getAnalysisUsage(AnalysisUsage &AU) const override {
143 AU.addRequired<MachineLoopInfo>();
144 AU.addRequired<MachineDominatorTree>();
145 AU.addRequired<AliasAnalysis>();
146 AU.addPreserved<MachineLoopInfo>();
147 AU.addPreserved<MachineDominatorTree>();
148 MachineFunctionPass::getAnalysisUsage(AU);
151 void releaseMemory() override {
160 /// CandidateInfo - Keep track of information about hoisting candidates.
161 struct CandidateInfo {
165 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
166 : MI(mi), Def(def), FI(fi) {}
169 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
170 /// invariants out to the preheader.
171 void HoistRegionPostRA();
173 /// HoistPostRA - When an instruction is found to only use loop invariant
174 /// operands that is safe to hoist, this instruction is called to do the
176 void HoistPostRA(MachineInstr *MI, unsigned Def);
178 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
179 /// gather register def and frame object update information.
180 void ProcessMI(MachineInstr *MI,
181 BitVector &PhysRegDefs,
182 BitVector &PhysRegClobbers,
183 SmallSet<int, 32> &StoredFIs,
184 SmallVectorImpl<CandidateInfo> &Candidates);
186 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
188 void AddToLiveIns(unsigned Reg);
190 /// IsLICMCandidate - Returns true if the instruction may be a suitable
191 /// candidate for LICM. e.g. If the instruction is a call, then it's
192 /// obviously not safe to hoist it.
193 bool IsLICMCandidate(MachineInstr &I);
195 /// IsLoopInvariantInst - Returns true if the instruction is loop
196 /// invariant. I.e., all virtual register operands are defined outside of
197 /// the loop, physical registers aren't accessed (explicitly or implicitly),
198 /// and the instruction is hoistable.
200 bool IsLoopInvariantInst(MachineInstr &I);
202 /// HasLoopPHIUse - Return true if the specified instruction is used by any
203 /// phi node in the current loop.
204 bool HasLoopPHIUse(const MachineInstr *MI) const;
206 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
207 /// and an use in the current loop, return true if the target considered
209 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
212 bool IsCheapInstruction(MachineInstr &MI) const;
214 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
215 /// check if hoisting an instruction of the given cost matrix can cause high
216 /// register pressure.
217 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
219 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
220 /// the current block and update their register pressures to reflect the
221 /// effect of hoisting MI from the current block to the preheader.
222 void UpdateBackTraceRegPressure(const MachineInstr *MI);
224 /// IsProfitableToHoist - Return true if it is potentially profitable to
225 /// hoist the given loop invariant.
226 bool IsProfitableToHoist(MachineInstr &MI);
228 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
229 /// If not then a load from this mbb may not be safe to hoist.
230 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
232 void EnterScope(MachineBasicBlock *MBB);
234 void ExitScope(MachineBasicBlock *MBB);
236 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
237 /// dominator tree node if its a leaf or all of its children are done. Walk
238 /// up the dominator tree to destroy ancestors which are now done.
239 void ExitScopeIfDone(MachineDomTreeNode *Node,
240 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
241 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
243 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
244 /// blocks dominated by the specified header block, and that are in the
245 /// current loop) in depth first order w.r.t the DominatorTree. This allows
246 /// us to visit definitions before uses, allowing us to hoist a loop body in
247 /// one pass without iteration.
249 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
250 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
252 /// SinkIntoLoop - Sink instructions into loops if profitable. This
253 /// especially tries to prevent register spills caused by register pressure
254 /// if there is little to no overhead moving instructions into loops.
257 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
258 /// index, return the ID and cost of its representative register class by
260 void getRegisterClassIDAndCost(const MachineInstr *MI,
261 unsigned Reg, unsigned OpIdx,
262 unsigned &RCId, unsigned &RCCost) const;
264 /// InitRegPressure - Find all virtual register references that are liveout
265 /// of the preheader to initialize the starting "register pressure". Note
266 /// this does not count live through (livein but not used) registers.
267 void InitRegPressure(MachineBasicBlock *BB);
269 /// UpdateRegPressure - Update estimate of register pressure after the
270 /// specified instruction.
271 void UpdateRegPressure(const MachineInstr *MI);
273 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
274 /// the load itself could be hoisted. Return the unfolded and hoistable
275 /// load, or null if the load couldn't be unfolded or if it wouldn't
277 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
279 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
280 /// duplicate of MI. Return this instruction if it's found.
281 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
282 std::vector<const MachineInstr*> &PrevMIs);
284 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
285 /// the preheader that compute the same value. If it's found, do a RAU on
286 /// with the definition of the existing instruction rather than hoisting
287 /// the instruction to the preheader.
288 bool EliminateCSE(MachineInstr *MI,
289 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
291 /// MayCSE - Return true if the given instruction will be CSE'd if it's
292 /// hoisted out of the loop.
293 bool MayCSE(MachineInstr *MI);
295 /// Hoist - When an instruction is found to only use loop invariant operands
296 /// that is safe to hoist, this instruction is called to do the dirty work.
297 /// It returns true if the instruction is hoisted.
298 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
300 /// InitCSEMap - Initialize the CSE map with instructions that are in the
301 /// current loop preheader that may become duplicates of instructions that
302 /// are hoisted out of the loop.
303 void InitCSEMap(MachineBasicBlock *BB);
305 /// getCurPreheader - Get the preheader for the current loop, splitting
306 /// a critical edge if needed.
307 MachineBasicBlock *getCurPreheader();
309 } // end anonymous namespace
311 char MachineLICM::ID = 0;
312 char &llvm::MachineLICMID = MachineLICM::ID;
313 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
314 "Machine Loop Invariant Code Motion", false, false)
315 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
316 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
317 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
318 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
319 "Machine Loop Invariant Code Motion", false, false)
321 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
322 /// loop that has a unique predecessor.
323 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
324 // Check whether this loop even has a unique predecessor.
325 if (!CurLoop->getLoopPredecessor())
327 // Ok, now check to see if any of its outer loops do.
328 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
329 if (L->getLoopPredecessor())
331 // None of them did, so this is the outermost with a unique predecessor.
335 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
336 if (skipOptnoneFunction(*MF.getFunction()))
339 Changed = FirstInLoop = false;
340 TII = MF.getSubtarget().getInstrInfo();
341 TLI = MF.getSubtarget().getTargetLowering();
342 TRI = MF.getSubtarget().getRegisterInfo();
343 MFI = MF.getFrameInfo();
344 MRI = &MF.getRegInfo();
345 InstrItins = MF.getSubtarget().getInstrItineraryData();
347 PreRegAlloc = MRI->isSSA();
350 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
352 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
353 DEBUG(dbgs() << MF.getName() << " ********\n");
356 // Estimate register pressure during pre-regalloc pass.
357 unsigned NumRC = TRI->getNumRegClasses();
358 RegPressure.resize(NumRC);
359 std::fill(RegPressure.begin(), RegPressure.end(), 0);
360 RegLimit.resize(NumRC);
361 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
362 E = TRI->regclass_end(); I != E; ++I)
363 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
366 // Get our Loop information...
367 MLI = &getAnalysis<MachineLoopInfo>();
368 DT = &getAnalysis<MachineDominatorTree>();
369 AA = &getAnalysis<AliasAnalysis>();
371 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
372 while (!Worklist.empty()) {
373 CurLoop = Worklist.pop_back_val();
374 CurPreheader = nullptr;
377 // If this is done before regalloc, only visit outer-most preheader-sporting
379 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
380 Worklist.append(CurLoop->begin(), CurLoop->end());
384 CurLoop->getExitBlocks(ExitBlocks);
389 // CSEMap is initialized for loop header when the first instruction is
391 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
396 if (SinkInstsToAvoidSpills)
404 /// InstructionStoresToFI - Return true if instruction stores to the
406 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
407 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
408 oe = MI->memoperands_end(); o != oe; ++o) {
409 if (!(*o)->isStore() || !(*o)->getPseudoValue())
411 if (const FixedStackPseudoSourceValue *Value =
412 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
413 if (Value->getFrameIndex() == FI)
420 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
421 /// gather register def and frame object update information.
422 void MachineLICM::ProcessMI(MachineInstr *MI,
423 BitVector &PhysRegDefs,
424 BitVector &PhysRegClobbers,
425 SmallSet<int, 32> &StoredFIs,
426 SmallVectorImpl<CandidateInfo> &Candidates) {
427 bool RuledOut = false;
428 bool HasNonInvariantUse = false;
430 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
431 const MachineOperand &MO = MI->getOperand(i);
433 // Remember if the instruction stores to the frame index.
434 int FI = MO.getIndex();
435 if (!StoredFIs.count(FI) &&
436 MFI->isSpillSlotObjectIndex(FI) &&
437 InstructionStoresToFI(MI, FI))
438 StoredFIs.insert(FI);
439 HasNonInvariantUse = true;
443 // We can't hoist an instruction defining a physreg that is clobbered in
445 if (MO.isRegMask()) {
446 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
452 unsigned Reg = MO.getReg();
455 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
456 "Not expecting virtual register!");
459 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
460 // If it's using a non-loop-invariant register, then it's obviously not
462 HasNonInvariantUse = true;
466 if (MO.isImplicit()) {
467 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
468 PhysRegClobbers.set(*AI);
470 // Non-dead implicit def? This cannot be hoisted.
472 // No need to check if a dead implicit def is also defined by
473 // another instruction.
477 // FIXME: For now, avoid instructions with multiple defs, unless
478 // it's a dead implicit def.
484 // If we have already seen another instruction that defines the same
485 // register, then this is not safe. Two defs is indicated by setting a
486 // PhysRegClobbers bit.
487 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
488 if (PhysRegDefs.test(*AS))
489 PhysRegClobbers.set(*AS);
490 PhysRegDefs.set(*AS);
492 if (PhysRegClobbers.test(Reg))
493 // MI defined register is seen defined by another instruction in
494 // the loop, it cannot be a LICM candidate.
498 // Only consider reloads for now and remats which do not have register
499 // operands. FIXME: Consider unfold load folding instructions.
500 if (Def && !RuledOut) {
502 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
503 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
504 Candidates.push_back(CandidateInfo(MI, Def, FI));
508 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
509 /// invariants out to the preheader.
510 void MachineLICM::HoistRegionPostRA() {
511 MachineBasicBlock *Preheader = getCurPreheader();
515 unsigned NumRegs = TRI->getNumRegs();
516 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
517 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
519 SmallVector<CandidateInfo, 32> Candidates;
520 SmallSet<int, 32> StoredFIs;
522 // Walk the entire region, count number of defs for each register, and
523 // collect potential LICM candidates.
524 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
525 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
526 MachineBasicBlock *BB = Blocks[i];
528 // If the header of the loop containing this basic block is a landing pad,
529 // then don't try to hoist instructions out of this loop.
530 const MachineLoop *ML = MLI->getLoopFor(BB);
531 if (ML && ML->getHeader()->isLandingPad()) continue;
533 // Conservatively treat live-in's as an external def.
534 // FIXME: That means a reload that're reused in successor block(s) will not
536 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
537 E = BB->livein_end(); I != E; ++I) {
539 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
540 PhysRegDefs.set(*AI);
543 SpeculationState = SpeculateUnknown;
544 for (MachineBasicBlock::iterator
545 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
546 MachineInstr *MI = &*MII;
547 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
551 // Gather the registers read / clobbered by the terminator.
552 BitVector TermRegs(NumRegs);
553 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
554 if (TI != Preheader->end()) {
555 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
556 const MachineOperand &MO = TI->getOperand(i);
559 unsigned Reg = MO.getReg();
562 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
567 // Now evaluate whether the potential candidates qualify.
568 // 1. Check if the candidate defined register is defined by another
569 // instruction in the loop.
570 // 2. If the candidate is a load from stack slot (always true for now),
571 // check if the slot is stored anywhere in the loop.
572 // 3. Make sure candidate def should not clobber
573 // registers read by the terminator. Similarly its def should not be
574 // clobbered by the terminator.
575 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
576 if (Candidates[i].FI != INT_MIN &&
577 StoredFIs.count(Candidates[i].FI))
580 unsigned Def = Candidates[i].Def;
581 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
583 MachineInstr *MI = Candidates[i].MI;
584 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
585 const MachineOperand &MO = MI->getOperand(j);
586 if (!MO.isReg() || MO.isDef() || !MO.getReg())
588 unsigned Reg = MO.getReg();
589 if (PhysRegDefs.test(Reg) ||
590 PhysRegClobbers.test(Reg)) {
591 // If it's using a non-loop-invariant register, then it's obviously
592 // not safe to hoist.
598 HoistPostRA(MI, Candidates[i].Def);
603 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
604 /// loop, and make sure it is not killed by any instructions in the loop.
605 void MachineLICM::AddToLiveIns(unsigned Reg) {
606 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
607 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
608 MachineBasicBlock *BB = Blocks[i];
609 if (!BB->isLiveIn(Reg))
611 for (MachineBasicBlock::iterator
612 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
613 MachineInstr *MI = &*MII;
614 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
615 MachineOperand &MO = MI->getOperand(i);
616 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
617 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
624 /// HoistPostRA - When an instruction is found to only use loop invariant
625 /// operands that is safe to hoist, this instruction is called to do the
627 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
628 MachineBasicBlock *Preheader = getCurPreheader();
630 // Now move the instructions to the predecessor, inserting it before any
631 // terminator instructions.
632 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
633 << MI->getParent()->getNumber() << ": " << *MI);
635 // Splice the instruction to the preheader.
636 MachineBasicBlock *MBB = MI->getParent();
637 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
639 // Add register to livein list to all the BBs in the current loop since a
640 // loop invariant must be kept live throughout the whole loop. This is
641 // important to ensure later passes do not scavenge the def register.
648 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
649 // If not then a load from this mbb may not be safe to hoist.
650 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
651 if (SpeculationState != SpeculateUnknown)
652 return SpeculationState == SpeculateFalse;
654 if (BB != CurLoop->getHeader()) {
655 // Check loop exiting blocks.
656 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
657 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
658 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
659 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
660 SpeculationState = SpeculateTrue;
665 SpeculationState = SpeculateFalse;
669 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
670 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
672 // Remember livein register pressure.
673 BackTrace.push_back(RegPressure);
676 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
677 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
678 BackTrace.pop_back();
681 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
682 /// dominator tree node if its a leaf or all of its children are done. Walk
683 /// up the dominator tree to destroy ancestors which are now done.
684 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
685 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
686 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
687 if (OpenChildren[Node])
691 ExitScope(Node->getBlock());
693 // Now traverse upwards to pop ancestors whose offsprings are all done.
694 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
695 unsigned Left = --OpenChildren[Parent];
698 ExitScope(Parent->getBlock());
703 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
704 /// blocks dominated by the specified header block, and that are in the
705 /// current loop) in depth first order w.r.t the DominatorTree. This allows
706 /// us to visit definitions before uses, allowing us to hoist a loop body in
707 /// one pass without iteration.
709 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
710 MachineBasicBlock *Preheader = getCurPreheader();
714 SmallVector<MachineDomTreeNode*, 32> Scopes;
715 SmallVector<MachineDomTreeNode*, 8> WorkList;
716 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
717 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
719 // Perform a DFS walk to determine the order of visit.
720 WorkList.push_back(HeaderN);
721 while (!WorkList.empty()) {
722 MachineDomTreeNode *Node = WorkList.pop_back_val();
723 assert(Node && "Null dominator tree node?");
724 MachineBasicBlock *BB = Node->getBlock();
726 // If the header of the loop containing this basic block is a landing pad,
727 // then don't try to hoist instructions out of this loop.
728 const MachineLoop *ML = MLI->getLoopFor(BB);
729 if (ML && ML->getHeader()->isLandingPad())
732 // If this subregion is not in the top level loop at all, exit.
733 if (!CurLoop->contains(BB))
736 Scopes.push_back(Node);
737 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
738 unsigned NumChildren = Children.size();
740 // Don't hoist things out of a large switch statement. This often causes
741 // code to be hoisted that wasn't going to be executed, and increases
742 // register pressure in a situation where it's likely to matter.
743 if (BB->succ_size() >= 25)
746 OpenChildren[Node] = NumChildren;
747 // Add children in reverse order as then the next popped worklist node is
748 // the first child of this node. This means we ultimately traverse the
749 // DOM tree in exactly the same order as if we'd recursed.
750 for (int i = (int)NumChildren-1; i >= 0; --i) {
751 MachineDomTreeNode *Child = Children[i];
752 ParentMap[Child] = Node;
753 WorkList.push_back(Child);
757 if (Scopes.size() == 0)
760 // Compute registers which are livein into the loop headers.
763 InitRegPressure(Preheader);
766 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
767 MachineDomTreeNode *Node = Scopes[i];
768 MachineBasicBlock *MBB = Node->getBlock();
773 SpeculationState = SpeculateUnknown;
774 for (MachineBasicBlock::iterator
775 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
776 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
777 MachineInstr *MI = &*MII;
778 if (!Hoist(MI, Preheader))
779 UpdateRegPressure(MI);
783 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
784 ExitScopeIfDone(Node, OpenChildren, ParentMap);
788 void MachineLICM::SinkIntoLoop() {
789 MachineBasicBlock *Preheader = getCurPreheader();
793 SmallVector<MachineInstr *, 8> Candidates;
794 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
795 I != Preheader->instr_end(); ++I) {
796 // We need to ensure that we can safely move this instruction into the loop.
797 // As such, it must not have side-effects, e.g. such as a call has.
798 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(I))
799 Candidates.push_back(I);
802 for (MachineInstr *I : Candidates) {
803 const MachineOperand &MO = I->getOperand(0);
804 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
806 if (!MRI->hasOneDef(MO.getReg()))
809 MachineBasicBlock *B = nullptr;
810 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
811 // FIXME: Come up with a proper cost model that estimates whether sinking
812 // the instruction (and thus possibly executing it on every loop
813 // iteration) is more expensive than a register.
814 // For now assumes that copies are cheap and thus almost always worth it.
823 B = DT->findNearestCommonDominator(B, MI.getParent());
829 if (!CanSink || !B || B == Preheader)
831 B->splice(B->getFirstNonPHI(), Preheader, I);
835 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
836 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
839 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
840 /// index, return the ID and cost of its representative register class.
842 MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
843 unsigned Reg, unsigned OpIdx,
844 unsigned &RCId, unsigned &RCCost) const {
845 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
846 MVT VT = *RC->vt_begin();
847 if (VT == MVT::Untyped) {
851 RCId = TLI->getRepRegClassFor(VT)->getID();
852 RCCost = TLI->getRepRegClassCostFor(VT);
856 /// InitRegPressure - Find all virtual register references that are liveout of
857 /// the preheader to initialize the starting "register pressure". Note this
858 /// does not count live through (livein but not used) registers.
859 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
860 std::fill(RegPressure.begin(), RegPressure.end(), 0);
862 // If the preheader has only a single predecessor and it ends with a
863 // fallthrough or an unconditional branch, then scan its predecessor for live
864 // defs as well. This happens whenever the preheader is created by splitting
865 // the critical edge from the loop predecessor to the loop header.
866 if (BB->pred_size() == 1) {
867 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
868 SmallVector<MachineOperand, 4> Cond;
869 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
870 InitRegPressure(*BB->pred_begin());
873 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
875 MachineInstr *MI = &*MII;
876 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
877 const MachineOperand &MO = MI->getOperand(i);
878 if (!MO.isReg() || MO.isImplicit())
880 unsigned Reg = MO.getReg();
881 if (!TargetRegisterInfo::isVirtualRegister(Reg))
884 bool isNew = RegSeen.insert(Reg).second;
885 unsigned RCId, RCCost;
886 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
888 RegPressure[RCId] += RCCost;
890 bool isKill = isOperandKill(MO, MRI);
891 if (isNew && !isKill)
892 // Haven't seen this, it must be a livein.
893 RegPressure[RCId] += RCCost;
894 else if (!isNew && isKill)
895 RegPressure[RCId] -= RCCost;
901 /// UpdateRegPressure - Update estimate of register pressure after the
902 /// specified instruction.
903 void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
904 if (MI->isImplicitDef())
907 SmallVector<unsigned, 4> Defs;
908 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
909 const MachineOperand &MO = MI->getOperand(i);
910 if (!MO.isReg() || MO.isImplicit())
912 unsigned Reg = MO.getReg();
913 if (!TargetRegisterInfo::isVirtualRegister(Reg))
916 bool isNew = RegSeen.insert(Reg).second;
919 else if (!isNew && isOperandKill(MO, MRI)) {
920 unsigned RCId, RCCost;
921 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
922 if (RCCost > RegPressure[RCId])
923 RegPressure[RCId] = 0;
925 RegPressure[RCId] -= RCCost;
930 while (!Defs.empty()) {
931 unsigned Reg = Defs.pop_back_val();
932 unsigned RCId, RCCost;
933 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
934 RegPressure[RCId] += RCCost;
939 /// isLoadFromGOTOrConstantPool - Return true if this machine instruction
940 /// loads from global offset table or constant pool.
941 static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
942 assert (MI.mayLoad() && "Expected MI that loads!");
943 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
944 E = MI.memoperands_end(); I != E; ++I) {
945 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
946 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
953 /// IsLICMCandidate - Returns true if the instruction may be a suitable
954 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
955 /// not safe to hoist it.
956 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
957 // Check if it's safe to move the instruction.
958 bool DontMoveAcrossStore = true;
959 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
962 // If it is load then check if it is guaranteed to execute by making sure that
963 // it dominates all exiting blocks. If it doesn't, then there is a path out of
964 // the loop which does not execute this load, so we can't hoist it. Loads
965 // from constant memory are not safe to speculate all the time, for example
966 // indexed load from a jump table.
967 // Stores and side effects are already checked by isSafeToMove.
968 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
969 !IsGuaranteedToExecute(I.getParent()))
975 /// IsLoopInvariantInst - Returns true if the instruction is loop
976 /// invariant. I.e., all virtual register operands are defined outside of the
977 /// loop, physical registers aren't accessed explicitly, and there are no side
978 /// effects that aren't captured by the operands or other flags.
980 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
981 if (!IsLICMCandidate(I))
984 // The instruction is loop invariant if all of its operands are.
985 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
986 const MachineOperand &MO = I.getOperand(i);
991 unsigned Reg = MO.getReg();
992 if (Reg == 0) continue;
994 // Don't hoist an instruction that uses or defines a physical register.
995 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
997 // If the physreg has no defs anywhere, it's just an ambient register
998 // and we can freely move its uses. Alternatively, if it's allocatable,
999 // it could get allocated to something with a def during allocation.
1000 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
1002 // Otherwise it's safe to move.
1004 } else if (!MO.isDead()) {
1005 // A def that isn't dead. We can't move it.
1007 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1008 // If the reg is live into the loop, we can't hoist an instruction
1009 // which would clobber it.
1017 assert(MRI->getVRegDef(Reg) &&
1018 "Machine instr not mapped for this vreg?!");
1020 // If the loop contains the definition of an operand, then the instruction
1021 // isn't loop invariant.
1022 if (CurLoop->contains(MRI->getVRegDef(Reg)))
1026 // If we got this far, the instruction is loop invariant!
1031 /// HasLoopPHIUse - Return true if the specified instruction is used by a
1032 /// phi node and hoisting it could cause a copy to be inserted.
1033 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1034 SmallVector<const MachineInstr*, 8> Work(1, MI);
1036 MI = Work.pop_back_val();
1037 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1038 if (!MO->isReg() || !MO->isDef())
1040 unsigned Reg = MO->getReg();
1041 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1043 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1044 // A PHI may cause a copy to be inserted.
1045 if (UseMI.isPHI()) {
1046 // A PHI inside the loop causes a copy because the live range of Reg is
1047 // extended across the PHI.
1048 if (CurLoop->contains(&UseMI))
1050 // A PHI in an exit block can cause a copy to be inserted if the PHI
1051 // has multiple predecessors in the loop with different values.
1052 // For now, approximate by rejecting all exit blocks.
1053 if (isExitBlock(UseMI.getParent()))
1057 // Look past copies as well.
1058 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1059 Work.push_back(&UseMI);
1062 } while (!Work.empty());
1066 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1067 /// and an use in the current loop, return true if the target considered
1069 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
1070 unsigned DefIdx, unsigned Reg) const {
1071 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
1074 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1075 if (UseMI.isCopyLike())
1077 if (!CurLoop->contains(UseMI.getParent()))
1079 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1080 const MachineOperand &MO = UseMI.getOperand(i);
1081 if (!MO.isReg() || !MO.isUse())
1083 unsigned MOReg = MO.getReg();
1087 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
1091 // Only look at the first in loop use.
1098 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1099 /// the operand latency between its def and a use is one or less.
1100 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1101 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
1103 if (!InstrItins || InstrItins->isEmpty())
1106 bool isCheap = false;
1107 unsigned NumDefs = MI.getDesc().getNumDefs();
1108 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1109 MachineOperand &DefMO = MI.getOperand(i);
1110 if (!DefMO.isReg() || !DefMO.isDef())
1113 unsigned Reg = DefMO.getReg();
1114 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1117 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1125 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
1126 /// if hoisting an instruction of the given cost matrix can cause high
1127 /// register pressure.
1128 bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1130 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1132 if (CI->second <= 0)
1135 unsigned RCId = CI->first;
1136 unsigned Limit = RegLimit[RCId];
1137 int Cost = CI->second;
1139 // Don't hoist cheap instructions if they would increase register pressure,
1140 // even if we're under the limit.
1141 if (CheapInstr && !HoistCheapInsts)
1144 for (unsigned i = BackTrace.size(); i != 0; --i) {
1145 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
1146 if (RP[RCId] + Cost >= Limit)
1154 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1155 /// current block and update their register pressures to reflect the effect
1156 /// of hoisting MI from the current block to the preheader.
1157 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1158 if (MI->isImplicitDef())
1161 // First compute the 'cost' of the instruction, i.e. its contribution
1162 // to register pressure.
1163 DenseMap<unsigned, int> Cost;
1164 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1165 const MachineOperand &MO = MI->getOperand(i);
1166 if (!MO.isReg() || MO.isImplicit())
1168 unsigned Reg = MO.getReg();
1169 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1172 unsigned RCId, RCCost;
1173 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
1175 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1176 if (CI != Cost.end())
1177 CI->second += RCCost;
1179 Cost.insert(std::make_pair(RCId, RCCost));
1180 } else if (isOperandKill(MO, MRI)) {
1181 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1182 if (CI != Cost.end())
1183 CI->second -= RCCost;
1185 Cost.insert(std::make_pair(RCId, -RCCost));
1189 // Update register pressure of blocks from loop header to current block.
1190 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1191 SmallVectorImpl<unsigned> &RP = BackTrace[i];
1192 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1194 unsigned RCId = CI->first;
1195 RP[RCId] += CI->second;
1200 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1201 /// the given loop invariant.
1202 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1203 if (MI.isImplicitDef())
1206 // Besides removing computation from the loop, hoisting an instruction has
1209 // - The value defined by the instruction becomes live across the entire
1210 // loop. This increases register pressure in the loop.
1212 // - If the value is used by a PHI in the loop, a copy will be required for
1213 // lowering the PHI after extending the live range.
1215 // - When hoisting the last use of a value in the loop, that value no longer
1216 // needs to be live in the loop. This lowers register pressure in the loop.
1218 bool CheapInstr = IsCheapInstruction(MI);
1219 bool CreatesCopy = HasLoopPHIUse(&MI);
1221 // Don't hoist a cheap instruction if it would create a copy in the loop.
1222 if (CheapInstr && CreatesCopy) {
1223 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1227 // Rematerializable instructions should always be hoisted since the register
1228 // allocator can just pull them down again when needed.
1229 if (TII->isTriviallyReMaterializable(&MI, AA))
1232 // Estimate register pressure to determine whether to LICM the instruction.
1233 // In low register pressure situation, we can be more aggressive about
1234 // hoisting. Also, favors hoisting long latency instructions even in
1235 // moderately high pressure situation.
1236 // Cheap instructions will only be hoisted if they don't increase register
1238 // FIXME: If there are long latency loop-invariant instructions inside the
1239 // loop at this point, why didn't the optimizer's LICM hoist them?
1240 DenseMap<unsigned, int> Cost;
1241 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1242 const MachineOperand &MO = MI.getOperand(i);
1243 if (!MO.isReg() || MO.isImplicit())
1245 unsigned Reg = MO.getReg();
1246 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1249 unsigned RCId, RCCost;
1250 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1252 if (HasHighOperandLatency(MI, i, Reg)) {
1253 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1257 Cost[RCId] += RCCost;
1258 } else if (isOperandKill(MO, MRI)) {
1259 // Is a virtual register use is a kill, hoisting it out of the loop
1260 // may actually reduce register pressure or be register pressure
1262 Cost[RCId] -= RCCost;
1266 // Visit BBs from header to current BB, if hoisting this doesn't cause
1267 // high register pressure, then it's safe to proceed.
1268 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1269 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1274 // Don't risk increasing register pressure if it would create copies.
1276 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1280 // Do not "speculate" in high register pressure situation. If an
1281 // instruction is not guaranteed to be executed in the loop, it's best to be
1283 if (AvoidSpeculation &&
1284 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1285 DEBUG(dbgs() << "Won't speculate: " << MI);
1289 // High register pressure situation, only hoist if the instruction is going
1291 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1292 !MI.isInvariantLoad(AA)) {
1293 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1300 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1301 // Don't unfold simple loads.
1302 if (MI->canFoldAsLoad())
1305 // If not, we may be able to unfold a load and hoist that.
1306 // First test whether the instruction is loading from an amenable
1308 if (!MI->isInvariantLoad(AA))
1311 // Next determine the register class for a temporary register.
1312 unsigned LoadRegIndex;
1314 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1315 /*UnfoldLoad=*/true,
1316 /*UnfoldStore=*/false,
1318 if (NewOpc == 0) return nullptr;
1319 const MCInstrDesc &MID = TII->get(NewOpc);
1320 if (MID.getNumDefs() != 1) return nullptr;
1321 MachineFunction &MF = *MI->getParent()->getParent();
1322 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1323 // Ok, we're unfolding. Create a temporary register and do the unfold.
1324 unsigned Reg = MRI->createVirtualRegister(RC);
1326 SmallVector<MachineInstr *, 2> NewMIs;
1328 TII->unfoldMemoryOperand(MF, MI, Reg,
1329 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1333 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1335 assert(NewMIs.size() == 2 &&
1336 "Unfolded a load into multiple instructions!");
1337 MachineBasicBlock *MBB = MI->getParent();
1338 MachineBasicBlock::iterator Pos = MI;
1339 MBB->insert(Pos, NewMIs[0]);
1340 MBB->insert(Pos, NewMIs[1]);
1341 // If unfolding produced a load that wasn't loop-invariant or profitable to
1342 // hoist, discard the new instructions and bail.
1343 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1344 NewMIs[0]->eraseFromParent();
1345 NewMIs[1]->eraseFromParent();
1349 // Update register pressure for the unfolded instruction.
1350 UpdateRegPressure(NewMIs[1]);
1352 // Otherwise we successfully unfolded a load that we can hoist.
1353 MI->eraseFromParent();
1357 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1358 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1359 const MachineInstr *MI = &*I;
1360 unsigned Opcode = MI->getOpcode();
1361 CSEMap[Opcode].push_back(MI);
1366 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1367 std::vector<const MachineInstr*> &PrevMIs) {
1368 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1369 const MachineInstr *PrevMI = PrevMIs[i];
1370 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
1376 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1377 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1378 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1379 // the undef property onto uses.
1380 if (CI == CSEMap.end() || MI->isImplicitDef())
1383 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1384 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1386 // Replace virtual registers defined by MI by their counterparts defined
1388 SmallVector<unsigned, 2> Defs;
1389 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1390 const MachineOperand &MO = MI->getOperand(i);
1392 // Physical registers may not differ here.
1393 assert((!MO.isReg() || MO.getReg() == 0 ||
1394 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1395 MO.getReg() == Dup->getOperand(i).getReg()) &&
1396 "Instructions with different phys regs are not identical!");
1398 if (MO.isReg() && MO.isDef() &&
1399 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1403 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1404 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1405 unsigned Idx = Defs[i];
1406 unsigned Reg = MI->getOperand(Idx).getReg();
1407 unsigned DupReg = Dup->getOperand(Idx).getReg();
1408 OrigRCs.push_back(MRI->getRegClass(DupReg));
1410 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1411 // Restore old RCs if more than one defs.
1412 for (unsigned j = 0; j != i; ++j)
1413 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1418 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1419 unsigned Idx = Defs[i];
1420 unsigned Reg = MI->getOperand(Idx).getReg();
1421 unsigned DupReg = Dup->getOperand(Idx).getReg();
1422 MRI->replaceRegWith(Reg, DupReg);
1423 MRI->clearKillFlags(DupReg);
1426 MI->eraseFromParent();
1433 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1434 /// hoisted out of the loop.
1435 bool MachineLICM::MayCSE(MachineInstr *MI) {
1436 unsigned Opcode = MI->getOpcode();
1437 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1438 CI = CSEMap.find(Opcode);
1439 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1440 // the undef property onto uses.
1441 if (CI == CSEMap.end() || MI->isImplicitDef())
1444 return LookForDuplicate(MI, CI->second) != nullptr;
1447 /// Hoist - When an instruction is found to use only loop invariant operands
1448 /// that are safe to hoist, this instruction is called to do the dirty work.
1450 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1451 // First check whether we should hoist this instruction.
1452 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1453 // If not, try unfolding a hoistable load.
1454 MI = ExtractHoistableLoad(MI);
1455 if (!MI) return false;
1458 // Now move the instructions to the predecessor, inserting it before any
1459 // terminator instructions.
1461 dbgs() << "Hoisting " << *MI;
1462 if (Preheader->getBasicBlock())
1463 dbgs() << " to MachineBasicBlock "
1464 << Preheader->getName();
1465 if (MI->getParent()->getBasicBlock())
1466 dbgs() << " from MachineBasicBlock "
1467 << MI->getParent()->getName();
1471 // If this is the first instruction being hoisted to the preheader,
1472 // initialize the CSE map with potential common expressions.
1474 InitCSEMap(Preheader);
1475 FirstInLoop = false;
1478 // Look for opportunity to CSE the hoisted instruction.
1479 unsigned Opcode = MI->getOpcode();
1480 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1481 CI = CSEMap.find(Opcode);
1482 if (!EliminateCSE(MI, CI)) {
1483 // Otherwise, splice the instruction to the preheader.
1484 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1486 // Update register pressure for BBs from header to this block.
1487 UpdateBackTraceRegPressure(MI);
1489 // Clear the kill flags of any register this instruction defines,
1490 // since they may need to be live throughout the entire loop
1491 // rather than just live for part of it.
1492 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1493 MachineOperand &MO = MI->getOperand(i);
1494 if (MO.isReg() && MO.isDef() && !MO.isDead())
1495 MRI->clearKillFlags(MO.getReg());
1498 // Add to the CSE map.
1499 if (CI != CSEMap.end())
1500 CI->second.push_back(MI);
1502 CSEMap[Opcode].push_back(MI);
1511 MachineBasicBlock *MachineLICM::getCurPreheader() {
1512 // Determine the block to which to hoist instructions. If we can't find a
1513 // suitable loop predecessor, we can't do any hoisting.
1515 // If we've tried to get a preheader and failed, don't try again.
1516 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1519 if (!CurPreheader) {
1520 CurPreheader = CurLoop->getLoopPreheader();
1521 if (!CurPreheader) {
1522 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1524 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1528 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1529 if (!CurPreheader) {
1530 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1535 return CurPreheader;