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 is not intended to be a replacement or a complete alternative
14 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15 // constructs that are not exposed before lowering and instruction selection.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/MC/MCInstrItineraries.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
41 #define DEBUG_TYPE "machine-licm"
44 AvoidSpeculation("avoid-speculation",
45 cl::desc("MachineLICM should avoid speculation"),
46 cl::init(true), cl::Hidden);
49 HoistCheapInsts("hoist-cheap-insts",
50 cl::desc("MachineLICM should hoist even cheap instructions"),
51 cl::init(false), cl::Hidden);
54 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55 cl::desc("MachineLICM should sink instructions into "
56 "loops to avoid register spills"),
57 cl::init(false), cl::Hidden);
60 "Number of machine instructions hoisted out of loops");
62 "Number of instructions hoisted in low reg pressure situation");
63 STATISTIC(NumHighLatency,
64 "Number of high latency instructions hoisted");
66 "Number of hoisted machine instructions CSEed");
67 STATISTIC(NumPostRAHoisted,
68 "Number of machine instructions hoisted out of loops post regalloc");
71 class MachineLICM : public MachineFunctionPass {
72 const TargetInstrInfo *TII;
73 const TargetLoweringBase *TLI;
74 const TargetRegisterInfo *TRI;
75 const MachineFrameInfo *MFI;
76 MachineRegisterInfo *MRI;
77 const InstrItineraryData *InstrItins;
80 // Various analyses that we use...
81 AliasAnalysis *AA; // Alias analysis info.
82 MachineLoopInfo *MLI; // Current MachineLoopInfo
83 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
85 // State that is updated as we process loops
86 bool Changed; // True if a loop is changed.
87 bool FirstInLoop; // True if it's the first LICM in the loop.
88 MachineLoop *CurLoop; // The current loop we are working on.
89 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
91 // Exit blocks for CurLoop.
92 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
94 bool isExitBlock(const MachineBasicBlock *MBB) const {
95 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
99 // Track 'estimated' register pressure.
100 SmallSet<unsigned, 32> RegSeen;
101 SmallVector<unsigned, 8> RegPressure;
103 // Register pressure "limit" per register class. If the pressure
104 // is higher than the limit, then it's considered high.
105 SmallVector<unsigned, 8> RegLimit;
107 // Register pressure on path leading from loop preheader to current BB.
108 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
110 // For each opcode, keep a list of potential CSE instructions.
111 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
119 // If a MBB does not dominate loop exiting blocks then it may not safe
120 // to hoist loads from this block.
121 // Tri-state: 0 - false, 1 - true, 2 - unknown
122 unsigned SpeculationState;
125 static char ID; // Pass identification, replacement for typeid
127 MachineFunctionPass(ID), PreRegAlloc(true) {
128 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
131 explicit MachineLICM(bool PreRA) :
132 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
133 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
136 bool runOnMachineFunction(MachineFunction &MF) override;
138 void getAnalysisUsage(AnalysisUsage &AU) const override {
139 AU.addRequired<MachineLoopInfo>();
140 AU.addRequired<MachineDominatorTree>();
141 AU.addRequired<AliasAnalysis>();
142 AU.addPreserved<MachineLoopInfo>();
143 AU.addPreserved<MachineDominatorTree>();
144 MachineFunctionPass::getAnalysisUsage(AU);
147 void releaseMemory() override {
156 /// CandidateInfo - Keep track of information about hoisting candidates.
157 struct CandidateInfo {
161 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
162 : MI(mi), Def(def), FI(fi) {}
165 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
166 /// invariants out to the preheader.
167 void HoistRegionPostRA();
169 /// HoistPostRA - When an instruction is found to only use loop invariant
170 /// operands that is safe to hoist, this instruction is called to do the
172 void HoistPostRA(MachineInstr *MI, unsigned Def);
174 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
175 /// gather register def and frame object update information.
176 void ProcessMI(MachineInstr *MI,
177 BitVector &PhysRegDefs,
178 BitVector &PhysRegClobbers,
179 SmallSet<int, 32> &StoredFIs,
180 SmallVectorImpl<CandidateInfo> &Candidates);
182 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
184 void AddToLiveIns(unsigned Reg);
186 /// IsLICMCandidate - Returns true if the instruction may be a suitable
187 /// candidate for LICM. e.g. If the instruction is a call, then it's
188 /// obviously not safe to hoist it.
189 bool IsLICMCandidate(MachineInstr &I);
191 /// IsLoopInvariantInst - Returns true if the instruction is loop
192 /// invariant. I.e., all virtual register operands are defined outside of
193 /// the loop, physical registers aren't accessed (explicitly or implicitly),
194 /// and the instruction is hoistable.
196 bool IsLoopInvariantInst(MachineInstr &I);
198 /// HasLoopPHIUse - Return true if the specified instruction is used by any
199 /// phi node in the current loop.
200 bool HasLoopPHIUse(const MachineInstr *MI) const;
202 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
203 /// and an use in the current loop, return true if the target considered
205 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
208 bool IsCheapInstruction(MachineInstr &MI) const;
210 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
211 /// check if hoisting an instruction of the given cost matrix can cause high
212 /// register pressure.
213 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
216 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
217 /// the current block and update their register pressures to reflect the
218 /// effect of hoisting MI from the current block to the preheader.
219 void UpdateBackTraceRegPressure(const MachineInstr *MI);
221 /// IsProfitableToHoist - Return true if it is potentially profitable to
222 /// hoist the given loop invariant.
223 bool IsProfitableToHoist(MachineInstr &MI);
225 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
226 /// If not then a load from this mbb may not be safe to hoist.
227 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
229 void EnterScope(MachineBasicBlock *MBB);
231 void ExitScope(MachineBasicBlock *MBB);
233 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
234 /// dominator tree node if its a leaf or all of its children are done. Walk
235 /// up the dominator tree to destroy ancestors which are now done.
236 void ExitScopeIfDone(MachineDomTreeNode *Node,
237 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
238 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
240 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
241 /// blocks dominated by the specified header block, and that are in the
242 /// current loop) in depth first order w.r.t the DominatorTree. This allows
243 /// us to visit definitions before uses, allowing us to hoist a loop body in
244 /// one pass without iteration.
246 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
247 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
249 /// SinkIntoLoop - Sink instructions into loops if profitable. This
250 /// especially tries to prevent register spills caused by register pressure
251 /// if there is little to no overhead moving instructions into loops.
254 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
255 /// index, return the ID and cost of its representative register class by
257 void getRegisterClassIDAndCost(const MachineInstr *MI,
258 unsigned Reg, unsigned OpIdx,
259 unsigned &RCId, unsigned &RCCost) const;
261 /// InitRegPressure - Find all virtual register references that are liveout
262 /// of the preheader to initialize the starting "register pressure". Note
263 /// this does not count live through (livein but not used) registers.
264 void InitRegPressure(MachineBasicBlock *BB);
266 /// UpdateRegPressure - Update estimate of register pressure after the
267 /// specified instruction.
268 void UpdateRegPressure(const MachineInstr *MI);
270 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
271 /// the load itself could be hoisted. Return the unfolded and hoistable
272 /// load, or null if the load couldn't be unfolded or if it wouldn't
274 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
276 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
277 /// duplicate of MI. Return this instruction if it's found.
278 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
279 std::vector<const MachineInstr*> &PrevMIs);
281 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
282 /// the preheader that compute the same value. If it's found, do a RAU on
283 /// with the definition of the existing instruction rather than hoisting
284 /// the instruction to the preheader.
285 bool EliminateCSE(MachineInstr *MI,
286 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
288 /// MayCSE - Return true if the given instruction will be CSE'd if it's
289 /// hoisted out of the loop.
290 bool MayCSE(MachineInstr *MI);
292 /// Hoist - When an instruction is found to only use loop invariant operands
293 /// that is safe to hoist, this instruction is called to do the dirty work.
294 /// It returns true if the instruction is hoisted.
295 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
297 /// InitCSEMap - Initialize the CSE map with instructions that are in the
298 /// current loop preheader that may become duplicates of instructions that
299 /// are hoisted out of the loop.
300 void InitCSEMap(MachineBasicBlock *BB);
302 /// getCurPreheader - Get the preheader for the current loop, splitting
303 /// a critical edge if needed.
304 MachineBasicBlock *getCurPreheader();
306 } // end anonymous namespace
308 char MachineLICM::ID = 0;
309 char &llvm::MachineLICMID = MachineLICM::ID;
310 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
311 "Machine Loop Invariant Code Motion", false, false)
312 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
313 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
314 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
315 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
316 "Machine Loop Invariant Code Motion", false, false)
318 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
319 /// loop that has a unique predecessor.
320 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
321 // Check whether this loop even has a unique predecessor.
322 if (!CurLoop->getLoopPredecessor())
324 // Ok, now check to see if any of its outer loops do.
325 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
326 if (L->getLoopPredecessor())
328 // None of them did, so this is the outermost with a unique predecessor.
332 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
333 if (skipOptnoneFunction(*MF.getFunction()))
336 Changed = FirstInLoop = false;
337 TII = MF.getSubtarget().getInstrInfo();
338 TLI = MF.getSubtarget().getTargetLowering();
339 TRI = MF.getSubtarget().getRegisterInfo();
340 MFI = MF.getFrameInfo();
341 MRI = &MF.getRegInfo();
342 InstrItins = MF.getSubtarget().getInstrItineraryData();
344 PreRegAlloc = MRI->isSSA();
347 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
349 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
350 DEBUG(dbgs() << MF.getName() << " ********\n");
353 // Estimate register pressure during pre-regalloc pass.
354 unsigned NumRC = TRI->getNumRegClasses();
355 RegPressure.resize(NumRC);
356 std::fill(RegPressure.begin(), RegPressure.end(), 0);
357 RegLimit.resize(NumRC);
358 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
359 E = TRI->regclass_end(); I != E; ++I)
360 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
363 // Get our Loop information...
364 MLI = &getAnalysis<MachineLoopInfo>();
365 DT = &getAnalysis<MachineDominatorTree>();
366 AA = &getAnalysis<AliasAnalysis>();
368 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
369 while (!Worklist.empty()) {
370 CurLoop = Worklist.pop_back_val();
371 CurPreheader = nullptr;
374 // If this is done before regalloc, only visit outer-most preheader-sporting
376 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
377 Worklist.append(CurLoop->begin(), CurLoop->end());
381 CurLoop->getExitBlocks(ExitBlocks);
386 // CSEMap is initialized for loop header when the first instruction is
388 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
393 if (SinkInstsToAvoidSpills)
401 /// InstructionStoresToFI - Return true if instruction stores to the
403 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
404 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
405 oe = MI->memoperands_end(); o != oe; ++o) {
406 if (!(*o)->isStore() || !(*o)->getPseudoValue())
408 if (const FixedStackPseudoSourceValue *Value =
409 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
410 if (Value->getFrameIndex() == FI)
417 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
418 /// gather register def and frame object update information.
419 void MachineLICM::ProcessMI(MachineInstr *MI,
420 BitVector &PhysRegDefs,
421 BitVector &PhysRegClobbers,
422 SmallSet<int, 32> &StoredFIs,
423 SmallVectorImpl<CandidateInfo> &Candidates) {
424 bool RuledOut = false;
425 bool HasNonInvariantUse = false;
427 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428 const MachineOperand &MO = MI->getOperand(i);
430 // Remember if the instruction stores to the frame index.
431 int FI = MO.getIndex();
432 if (!StoredFIs.count(FI) &&
433 MFI->isSpillSlotObjectIndex(FI) &&
434 InstructionStoresToFI(MI, FI))
435 StoredFIs.insert(FI);
436 HasNonInvariantUse = true;
440 // We can't hoist an instruction defining a physreg that is clobbered in
442 if (MO.isRegMask()) {
443 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
449 unsigned Reg = MO.getReg();
452 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
453 "Not expecting virtual register!");
456 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
457 // If it's using a non-loop-invariant register, then it's obviously not
459 HasNonInvariantUse = true;
463 if (MO.isImplicit()) {
464 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
465 PhysRegClobbers.set(*AI);
467 // Non-dead implicit def? This cannot be hoisted.
469 // No need to check if a dead implicit def is also defined by
470 // another instruction.
474 // FIXME: For now, avoid instructions with multiple defs, unless
475 // it's a dead implicit def.
481 // If we have already seen another instruction that defines the same
482 // register, then this is not safe. Two defs is indicated by setting a
483 // PhysRegClobbers bit.
484 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
485 if (PhysRegDefs.test(*AS))
486 PhysRegClobbers.set(*AS);
487 PhysRegDefs.set(*AS);
489 if (PhysRegClobbers.test(Reg))
490 // MI defined register is seen defined by another instruction in
491 // the loop, it cannot be a LICM candidate.
495 // Only consider reloads for now and remats which do not have register
496 // operands. FIXME: Consider unfold load folding instructions.
497 if (Def && !RuledOut) {
499 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
500 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
501 Candidates.push_back(CandidateInfo(MI, Def, FI));
505 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
506 /// invariants out to the preheader.
507 void MachineLICM::HoistRegionPostRA() {
508 MachineBasicBlock *Preheader = getCurPreheader();
512 unsigned NumRegs = TRI->getNumRegs();
513 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
514 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
516 SmallVector<CandidateInfo, 32> Candidates;
517 SmallSet<int, 32> StoredFIs;
519 // Walk the entire region, count number of defs for each register, and
520 // collect potential LICM candidates.
521 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
522 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
523 MachineBasicBlock *BB = Blocks[i];
525 // If the header of the loop containing this basic block is a landing pad,
526 // then don't try to hoist instructions out of this loop.
527 const MachineLoop *ML = MLI->getLoopFor(BB);
528 if (ML && ML->getHeader()->isLandingPad()) continue;
530 // Conservatively treat live-in's as an external def.
531 // FIXME: That means a reload that're reused in successor block(s) will not
533 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
534 E = BB->livein_end(); I != E; ++I) {
536 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
537 PhysRegDefs.set(*AI);
540 SpeculationState = SpeculateUnknown;
541 for (MachineBasicBlock::iterator
542 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
543 MachineInstr *MI = &*MII;
544 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
548 // Gather the registers read / clobbered by the terminator.
549 BitVector TermRegs(NumRegs);
550 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
551 if (TI != Preheader->end()) {
552 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
553 const MachineOperand &MO = TI->getOperand(i);
556 unsigned Reg = MO.getReg();
559 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
564 // Now evaluate whether the potential candidates qualify.
565 // 1. Check if the candidate defined register is defined by another
566 // instruction in the loop.
567 // 2. If the candidate is a load from stack slot (always true for now),
568 // check if the slot is stored anywhere in the loop.
569 // 3. Make sure candidate def should not clobber
570 // registers read by the terminator. Similarly its def should not be
571 // clobbered by the terminator.
572 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
573 if (Candidates[i].FI != INT_MIN &&
574 StoredFIs.count(Candidates[i].FI))
577 unsigned Def = Candidates[i].Def;
578 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
580 MachineInstr *MI = Candidates[i].MI;
581 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
582 const MachineOperand &MO = MI->getOperand(j);
583 if (!MO.isReg() || MO.isDef() || !MO.getReg())
585 unsigned Reg = MO.getReg();
586 if (PhysRegDefs.test(Reg) ||
587 PhysRegClobbers.test(Reg)) {
588 // If it's using a non-loop-invariant register, then it's obviously
589 // not safe to hoist.
595 HoistPostRA(MI, Candidates[i].Def);
600 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
601 /// loop, and make sure it is not killed by any instructions in the loop.
602 void MachineLICM::AddToLiveIns(unsigned Reg) {
603 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
604 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
605 MachineBasicBlock *BB = Blocks[i];
606 if (!BB->isLiveIn(Reg))
608 for (MachineBasicBlock::iterator
609 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
610 MachineInstr *MI = &*MII;
611 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
612 MachineOperand &MO = MI->getOperand(i);
613 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
614 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
621 /// HoistPostRA - When an instruction is found to only use loop invariant
622 /// operands that is safe to hoist, this instruction is called to do the
624 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
625 MachineBasicBlock *Preheader = getCurPreheader();
627 // Now move the instructions to the predecessor, inserting it before any
628 // terminator instructions.
629 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
630 << MI->getParent()->getNumber() << ": " << *MI);
632 // Splice the instruction to the preheader.
633 MachineBasicBlock *MBB = MI->getParent();
634 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
636 // Add register to livein list to all the BBs in the current loop since a
637 // loop invariant must be kept live throughout the whole loop. This is
638 // important to ensure later passes do not scavenge the def register.
645 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
646 // If not then a load from this mbb may not be safe to hoist.
647 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
648 if (SpeculationState != SpeculateUnknown)
649 return SpeculationState == SpeculateFalse;
651 if (BB != CurLoop->getHeader()) {
652 // Check loop exiting blocks.
653 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
654 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
655 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
656 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
657 SpeculationState = SpeculateTrue;
662 SpeculationState = SpeculateFalse;
666 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
667 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
669 // Remember livein register pressure.
670 BackTrace.push_back(RegPressure);
673 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
674 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
675 BackTrace.pop_back();
678 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
679 /// dominator tree node if its a leaf or all of its children are done. Walk
680 /// up the dominator tree to destroy ancestors which are now done.
681 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
682 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
683 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
684 if (OpenChildren[Node])
688 ExitScope(Node->getBlock());
690 // Now traverse upwards to pop ancestors whose offsprings are all done.
691 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
692 unsigned Left = --OpenChildren[Parent];
695 ExitScope(Parent->getBlock());
700 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
701 /// blocks dominated by the specified header block, and that are in the
702 /// current loop) in depth first order w.r.t the DominatorTree. This allows
703 /// us to visit definitions before uses, allowing us to hoist a loop body in
704 /// one pass without iteration.
706 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
707 MachineBasicBlock *Preheader = getCurPreheader();
711 SmallVector<MachineDomTreeNode*, 32> Scopes;
712 SmallVector<MachineDomTreeNode*, 8> WorkList;
713 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
714 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
716 // Perform a DFS walk to determine the order of visit.
717 WorkList.push_back(HeaderN);
718 while (!WorkList.empty()) {
719 MachineDomTreeNode *Node = WorkList.pop_back_val();
720 assert(Node && "Null dominator tree node?");
721 MachineBasicBlock *BB = Node->getBlock();
723 // If the header of the loop containing this basic block is a landing pad,
724 // then don't try to hoist instructions out of this loop.
725 const MachineLoop *ML = MLI->getLoopFor(BB);
726 if (ML && ML->getHeader()->isLandingPad())
729 // If this subregion is not in the top level loop at all, exit.
730 if (!CurLoop->contains(BB))
733 Scopes.push_back(Node);
734 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
735 unsigned NumChildren = Children.size();
737 // Don't hoist things out of a large switch statement. This often causes
738 // code to be hoisted that wasn't going to be executed, and increases
739 // register pressure in a situation where it's likely to matter.
740 if (BB->succ_size() >= 25)
743 OpenChildren[Node] = NumChildren;
744 // Add children in reverse order as then the next popped worklist node is
745 // the first child of this node. This means we ultimately traverse the
746 // DOM tree in exactly the same order as if we'd recursed.
747 for (int i = (int)NumChildren-1; i >= 0; --i) {
748 MachineDomTreeNode *Child = Children[i];
749 ParentMap[Child] = Node;
750 WorkList.push_back(Child);
754 if (Scopes.size() == 0)
757 // Compute registers which are livein into the loop headers.
760 InitRegPressure(Preheader);
763 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
764 MachineDomTreeNode *Node = Scopes[i];
765 MachineBasicBlock *MBB = Node->getBlock();
770 SpeculationState = SpeculateUnknown;
771 for (MachineBasicBlock::iterator
772 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
773 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
774 MachineInstr *MI = &*MII;
775 if (!Hoist(MI, Preheader))
776 UpdateRegPressure(MI);
780 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
781 ExitScopeIfDone(Node, OpenChildren, ParentMap);
785 void MachineLICM::SinkIntoLoop() {
786 MachineBasicBlock *Preheader = getCurPreheader();
790 SmallVector<MachineInstr *, 8> Candidates;
791 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
792 I != Preheader->instr_end(); ++I) {
793 // We need to ensure that we can safely move this instruction into the loop.
794 // As such, it must not have side-effects, e.g. such as a call has.
795 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(I))
796 Candidates.push_back(I);
799 for (MachineInstr *I : Candidates) {
800 const MachineOperand &MO = I->getOperand(0);
801 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
803 if (!MRI->hasOneDef(MO.getReg()))
806 MachineBasicBlock *B = nullptr;
807 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
808 // FIXME: Come up with a proper cost model that estimates whether sinking
809 // the instruction (and thus possibly executing it on every loop
810 // iteration) is more expensive than a register.
811 // For now assumes that copies are cheap and thus almost always worth it.
820 B = DT->findNearestCommonDominator(B, MI.getParent());
826 if (!CanSink || !B || B == Preheader)
828 B->splice(B->getFirstNonPHI(), Preheader, I);
832 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
833 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
836 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
837 /// index, return the ID and cost of its representative register class.
839 MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
840 unsigned Reg, unsigned OpIdx,
841 unsigned &RCId, unsigned &RCCost) const {
842 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
843 MVT VT = *RC->vt_begin();
844 if (VT == MVT::Untyped) {
848 RCId = TLI->getRepRegClassFor(VT)->getID();
849 RCCost = TLI->getRepRegClassCostFor(VT);
853 /// InitRegPressure - Find all virtual register references that are liveout of
854 /// the preheader to initialize the starting "register pressure". Note this
855 /// does not count live through (livein but not used) registers.
856 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
857 std::fill(RegPressure.begin(), RegPressure.end(), 0);
859 // If the preheader has only a single predecessor and it ends with a
860 // fallthrough or an unconditional branch, then scan its predecessor for live
861 // defs as well. This happens whenever the preheader is created by splitting
862 // the critical edge from the loop predecessor to the loop header.
863 if (BB->pred_size() == 1) {
864 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
865 SmallVector<MachineOperand, 4> Cond;
866 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
867 InitRegPressure(*BB->pred_begin());
870 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
872 MachineInstr *MI = &*MII;
873 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
874 const MachineOperand &MO = MI->getOperand(i);
875 if (!MO.isReg() || MO.isImplicit())
877 unsigned Reg = MO.getReg();
878 if (!TargetRegisterInfo::isVirtualRegister(Reg))
881 bool isNew = RegSeen.insert(Reg).second;
882 unsigned RCId, RCCost;
883 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
885 RegPressure[RCId] += RCCost;
887 bool isKill = isOperandKill(MO, MRI);
888 if (isNew && !isKill)
889 // Haven't seen this, it must be a livein.
890 RegPressure[RCId] += RCCost;
891 else if (!isNew && isKill)
892 RegPressure[RCId] -= RCCost;
898 /// UpdateRegPressure - Update estimate of register pressure after the
899 /// specified instruction.
900 void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
901 if (MI->isImplicitDef())
904 SmallVector<unsigned, 4> Defs;
905 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
906 const MachineOperand &MO = MI->getOperand(i);
907 if (!MO.isReg() || MO.isImplicit())
909 unsigned Reg = MO.getReg();
910 if (!TargetRegisterInfo::isVirtualRegister(Reg))
913 bool isNew = RegSeen.insert(Reg).second;
916 else if (!isNew && isOperandKill(MO, MRI)) {
917 unsigned RCId, RCCost;
918 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
919 if (RCCost > RegPressure[RCId])
920 RegPressure[RCId] = 0;
922 RegPressure[RCId] -= RCCost;
927 while (!Defs.empty()) {
928 unsigned Reg = Defs.pop_back_val();
929 unsigned RCId, RCCost;
930 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
931 RegPressure[RCId] += RCCost;
936 /// isLoadFromGOTOrConstantPool - Return true if this machine instruction
937 /// loads from global offset table or constant pool.
938 static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
939 assert (MI.mayLoad() && "Expected MI that loads!");
940 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
941 E = MI.memoperands_end(); I != E; ++I) {
942 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
943 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
950 /// IsLICMCandidate - Returns true if the instruction may be a suitable
951 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
952 /// not safe to hoist it.
953 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
954 // Check if it's safe to move the instruction.
955 bool DontMoveAcrossStore = true;
956 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
959 // If it is load then check if it is guaranteed to execute by making sure that
960 // it dominates all exiting blocks. If it doesn't, then there is a path out of
961 // the loop which does not execute this load, so we can't hoist it. Loads
962 // from constant memory are not safe to speculate all the time, for example
963 // indexed load from a jump table.
964 // Stores and side effects are already checked by isSafeToMove.
965 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
966 !IsGuaranteedToExecute(I.getParent()))
972 /// IsLoopInvariantInst - Returns true if the instruction is loop
973 /// invariant. I.e., all virtual register operands are defined outside of the
974 /// loop, physical registers aren't accessed explicitly, and there are no side
975 /// effects that aren't captured by the operands or other flags.
977 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
978 if (!IsLICMCandidate(I))
981 // The instruction is loop invariant if all of its operands are.
982 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
983 const MachineOperand &MO = I.getOperand(i);
988 unsigned Reg = MO.getReg();
989 if (Reg == 0) continue;
991 // Don't hoist an instruction that uses or defines a physical register.
992 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
994 // If the physreg has no defs anywhere, it's just an ambient register
995 // and we can freely move its uses. Alternatively, if it's allocatable,
996 // it could get allocated to something with a def during allocation.
997 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
999 // Otherwise it's safe to move.
1001 } else if (!MO.isDead()) {
1002 // A def that isn't dead. We can't move it.
1004 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1005 // If the reg is live into the loop, we can't hoist an instruction
1006 // which would clobber it.
1014 assert(MRI->getVRegDef(Reg) &&
1015 "Machine instr not mapped for this vreg?!");
1017 // If the loop contains the definition of an operand, then the instruction
1018 // isn't loop invariant.
1019 if (CurLoop->contains(MRI->getVRegDef(Reg)))
1023 // If we got this far, the instruction is loop invariant!
1028 /// HasLoopPHIUse - Return true if the specified instruction is used by a
1029 /// phi node and hoisting it could cause a copy to be inserted.
1030 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1031 SmallVector<const MachineInstr*, 8> Work(1, MI);
1033 MI = Work.pop_back_val();
1034 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1035 if (!MO->isReg() || !MO->isDef())
1037 unsigned Reg = MO->getReg();
1038 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1040 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1041 // A PHI may cause a copy to be inserted.
1042 if (UseMI.isPHI()) {
1043 // A PHI inside the loop causes a copy because the live range of Reg is
1044 // extended across the PHI.
1045 if (CurLoop->contains(&UseMI))
1047 // A PHI in an exit block can cause a copy to be inserted if the PHI
1048 // has multiple predecessors in the loop with different values.
1049 // For now, approximate by rejecting all exit blocks.
1050 if (isExitBlock(UseMI.getParent()))
1054 // Look past copies as well.
1055 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1056 Work.push_back(&UseMI);
1059 } while (!Work.empty());
1063 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1064 /// and an use in the current loop, return true if the target considered
1066 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
1067 unsigned DefIdx, unsigned Reg) const {
1068 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
1071 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1072 if (UseMI.isCopyLike())
1074 if (!CurLoop->contains(UseMI.getParent()))
1076 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1077 const MachineOperand &MO = UseMI.getOperand(i);
1078 if (!MO.isReg() || !MO.isUse())
1080 unsigned MOReg = MO.getReg();
1084 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
1088 // Only look at the first in loop use.
1095 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1096 /// the operand latency between its def and a use is one or less.
1097 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1098 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
1100 if (!InstrItins || InstrItins->isEmpty())
1103 bool isCheap = false;
1104 unsigned NumDefs = MI.getDesc().getNumDefs();
1105 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1106 MachineOperand &DefMO = MI.getOperand(i);
1107 if (!DefMO.isReg() || !DefMO.isDef())
1110 unsigned Reg = DefMO.getReg();
1111 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1114 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1122 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
1123 /// if hoisting an instruction of the given cost matrix can cause high
1124 /// register pressure.
1125 bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1127 for (const auto &ClassAndCost : Cost) {
1128 if (ClassAndCost.second <= 0)
1131 unsigned Class = ClassAndCost.first;
1132 int Limit = RegLimit[Class];
1134 // Don't hoist cheap instructions if they would increase register pressure,
1135 // even if we're under the limit.
1136 if (CheapInstr && !HoistCheapInsts)
1139 for (const auto &RP : BackTrace)
1140 if (static_cast<int>(RP[Class]) + ClassAndCost.second >= Limit)
1147 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1148 /// current block and update their register pressures to reflect the effect
1149 /// of hoisting MI from the current block to the preheader.
1150 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1151 if (MI->isImplicitDef())
1154 // First compute the 'cost' of the instruction, i.e. its contribution
1155 // to register pressure.
1156 DenseMap<unsigned, int> Cost;
1157 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1158 const MachineOperand &MO = MI->getOperand(i);
1159 if (!MO.isReg() || MO.isImplicit())
1161 unsigned Reg = MO.getReg();
1162 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1165 unsigned RCId, RCCost;
1166 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
1168 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1169 if (CI != Cost.end())
1170 CI->second += RCCost;
1172 Cost.insert(std::make_pair(RCId, RCCost));
1173 } else if (isOperandKill(MO, MRI)) {
1174 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1175 if (CI != Cost.end())
1176 CI->second -= RCCost;
1178 Cost.insert(std::make_pair(RCId, -RCCost));
1182 // Update register pressure of blocks from loop header to current block.
1183 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1184 SmallVectorImpl<unsigned> &RP = BackTrace[i];
1185 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1187 unsigned RCId = CI->first;
1188 RP[RCId] += CI->second;
1193 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1194 /// the given loop invariant.
1195 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1196 if (MI.isImplicitDef())
1199 // Besides removing computation from the loop, hoisting an instruction has
1202 // - The value defined by the instruction becomes live across the entire
1203 // loop. This increases register pressure in the loop.
1205 // - If the value is used by a PHI in the loop, a copy will be required for
1206 // lowering the PHI after extending the live range.
1208 // - When hoisting the last use of a value in the loop, that value no longer
1209 // needs to be live in the loop. This lowers register pressure in the loop.
1211 bool CheapInstr = IsCheapInstruction(MI);
1212 bool CreatesCopy = HasLoopPHIUse(&MI);
1214 // Don't hoist a cheap instruction if it would create a copy in the loop.
1215 if (CheapInstr && CreatesCopy) {
1216 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1220 // Rematerializable instructions should always be hoisted since the register
1221 // allocator can just pull them down again when needed.
1222 if (TII->isTriviallyReMaterializable(&MI, AA))
1225 // Estimate register pressure to determine whether to LICM the instruction.
1226 // In low register pressure situation, we can be more aggressive about
1227 // hoisting. Also, favors hoisting long latency instructions even in
1228 // moderately high pressure situation.
1229 // Cheap instructions will only be hoisted if they don't increase register
1231 // FIXME: If there are long latency loop-invariant instructions inside the
1232 // loop at this point, why didn't the optimizer's LICM hoist them?
1233 DenseMap<unsigned, int> Cost;
1234 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1235 const MachineOperand &MO = MI.getOperand(i);
1236 if (!MO.isReg() || MO.isImplicit())
1238 unsigned Reg = MO.getReg();
1239 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1242 unsigned RCId, RCCost;
1243 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1245 if (HasHighOperandLatency(MI, i, Reg)) {
1246 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1250 Cost[RCId] += RCCost;
1251 } else if (isOperandKill(MO, MRI)) {
1252 // Is a virtual register use is a kill, hoisting it out of the loop
1253 // may actually reduce register pressure or be register pressure
1255 Cost[RCId] -= RCCost;
1259 // Visit BBs from header to current BB, if hoisting this doesn't cause
1260 // high register pressure, then it's safe to proceed.
1261 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1262 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1267 // Don't risk increasing register pressure if it would create copies.
1269 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1273 // Do not "speculate" in high register pressure situation. If an
1274 // instruction is not guaranteed to be executed in the loop, it's best to be
1276 if (AvoidSpeculation &&
1277 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1278 DEBUG(dbgs() << "Won't speculate: " << MI);
1282 // High register pressure situation, only hoist if the instruction is going
1284 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1285 !MI.isInvariantLoad(AA)) {
1286 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1293 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1294 // Don't unfold simple loads.
1295 if (MI->canFoldAsLoad())
1298 // If not, we may be able to unfold a load and hoist that.
1299 // First test whether the instruction is loading from an amenable
1301 if (!MI->isInvariantLoad(AA))
1304 // Next determine the register class for a temporary register.
1305 unsigned LoadRegIndex;
1307 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1308 /*UnfoldLoad=*/true,
1309 /*UnfoldStore=*/false,
1311 if (NewOpc == 0) return nullptr;
1312 const MCInstrDesc &MID = TII->get(NewOpc);
1313 if (MID.getNumDefs() != 1) return nullptr;
1314 MachineFunction &MF = *MI->getParent()->getParent();
1315 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1316 // Ok, we're unfolding. Create a temporary register and do the unfold.
1317 unsigned Reg = MRI->createVirtualRegister(RC);
1319 SmallVector<MachineInstr *, 2> NewMIs;
1321 TII->unfoldMemoryOperand(MF, MI, Reg,
1322 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1326 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1328 assert(NewMIs.size() == 2 &&
1329 "Unfolded a load into multiple instructions!");
1330 MachineBasicBlock *MBB = MI->getParent();
1331 MachineBasicBlock::iterator Pos = MI;
1332 MBB->insert(Pos, NewMIs[0]);
1333 MBB->insert(Pos, NewMIs[1]);
1334 // If unfolding produced a load that wasn't loop-invariant or profitable to
1335 // hoist, discard the new instructions and bail.
1336 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1337 NewMIs[0]->eraseFromParent();
1338 NewMIs[1]->eraseFromParent();
1342 // Update register pressure for the unfolded instruction.
1343 UpdateRegPressure(NewMIs[1]);
1345 // Otherwise we successfully unfolded a load that we can hoist.
1346 MI->eraseFromParent();
1350 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1351 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1352 const MachineInstr *MI = &*I;
1353 unsigned Opcode = MI->getOpcode();
1354 CSEMap[Opcode].push_back(MI);
1359 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1360 std::vector<const MachineInstr*> &PrevMIs) {
1361 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1362 const MachineInstr *PrevMI = PrevMIs[i];
1363 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
1369 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1370 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1371 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1372 // the undef property onto uses.
1373 if (CI == CSEMap.end() || MI->isImplicitDef())
1376 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1377 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1379 // Replace virtual registers defined by MI by their counterparts defined
1381 SmallVector<unsigned, 2> Defs;
1382 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1383 const MachineOperand &MO = MI->getOperand(i);
1385 // Physical registers may not differ here.
1386 assert((!MO.isReg() || MO.getReg() == 0 ||
1387 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1388 MO.getReg() == Dup->getOperand(i).getReg()) &&
1389 "Instructions with different phys regs are not identical!");
1391 if (MO.isReg() && MO.isDef() &&
1392 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1396 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1397 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1398 unsigned Idx = Defs[i];
1399 unsigned Reg = MI->getOperand(Idx).getReg();
1400 unsigned DupReg = Dup->getOperand(Idx).getReg();
1401 OrigRCs.push_back(MRI->getRegClass(DupReg));
1403 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1404 // Restore old RCs if more than one defs.
1405 for (unsigned j = 0; j != i; ++j)
1406 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1411 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1412 unsigned Idx = Defs[i];
1413 unsigned Reg = MI->getOperand(Idx).getReg();
1414 unsigned DupReg = Dup->getOperand(Idx).getReg();
1415 MRI->replaceRegWith(Reg, DupReg);
1416 MRI->clearKillFlags(DupReg);
1419 MI->eraseFromParent();
1426 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1427 /// hoisted out of the loop.
1428 bool MachineLICM::MayCSE(MachineInstr *MI) {
1429 unsigned Opcode = MI->getOpcode();
1430 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1431 CI = CSEMap.find(Opcode);
1432 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1433 // the undef property onto uses.
1434 if (CI == CSEMap.end() || MI->isImplicitDef())
1437 return LookForDuplicate(MI, CI->second) != nullptr;
1440 /// Hoist - When an instruction is found to use only loop invariant operands
1441 /// that are safe to hoist, this instruction is called to do the dirty work.
1443 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1444 // First check whether we should hoist this instruction.
1445 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1446 // If not, try unfolding a hoistable load.
1447 MI = ExtractHoistableLoad(MI);
1448 if (!MI) return false;
1451 // Now move the instructions to the predecessor, inserting it before any
1452 // terminator instructions.
1454 dbgs() << "Hoisting " << *MI;
1455 if (Preheader->getBasicBlock())
1456 dbgs() << " to MachineBasicBlock "
1457 << Preheader->getName();
1458 if (MI->getParent()->getBasicBlock())
1459 dbgs() << " from MachineBasicBlock "
1460 << MI->getParent()->getName();
1464 // If this is the first instruction being hoisted to the preheader,
1465 // initialize the CSE map with potential common expressions.
1467 InitCSEMap(Preheader);
1468 FirstInLoop = false;
1471 // Look for opportunity to CSE the hoisted instruction.
1472 unsigned Opcode = MI->getOpcode();
1473 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1474 CI = CSEMap.find(Opcode);
1475 if (!EliminateCSE(MI, CI)) {
1476 // Otherwise, splice the instruction to the preheader.
1477 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1479 // Update register pressure for BBs from header to this block.
1480 UpdateBackTraceRegPressure(MI);
1482 // Clear the kill flags of any register this instruction defines,
1483 // since they may need to be live throughout the entire loop
1484 // rather than just live for part of it.
1485 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1486 MachineOperand &MO = MI->getOperand(i);
1487 if (MO.isReg() && MO.isDef() && !MO.isDead())
1488 MRI->clearKillFlags(MO.getReg());
1491 // Add to the CSE map.
1492 if (CI != CSEMap.end())
1493 CI->second.push_back(MI);
1495 CSEMap[Opcode].push_back(MI);
1504 MachineBasicBlock *MachineLICM::getCurPreheader() {
1505 // Determine the block to which to hoist instructions. If we can't find a
1506 // suitable loop predecessor, we can't do any hoisting.
1508 // If we've tried to get a preheader and failed, don't try again.
1509 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1512 if (!CurPreheader) {
1513 CurPreheader = CurLoop->getLoopPreheader();
1514 if (!CurPreheader) {
1515 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1517 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1521 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1522 if (!CurPreheader) {
1523 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1528 return CurPreheader;