1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs loop invariant code motion on machine instructions. We
11 // attempt to remove as much code from the body of a loop as possible.
13 // This pass does not attempt to throttle itself to limit register pressure.
14 // The register allocation phases are expected to perform rematerialization
15 // to recover when register pressure is high.
17 // This pass is not intended to be a replacement or a complete alternative
18 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19 // constructs that are not exposed before lowering and instruction selection.
21 //===----------------------------------------------------------------------===//
23 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetInstrItineraries.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
46 "Number of machine instructions hoisted out of loops");
48 "Number of instructions hoisted in low reg pressure situation");
49 STATISTIC(NumHighLatency
,
50 "Number of high latency instructions hoisted");
52 "Number of hoisted machine instructions CSEed");
53 STATISTIC(NumPostRAHoisted
,
54 "Number of machine instructions hoisted out of loops post regalloc");
57 class MachineLICM
: public MachineFunctionPass
{
60 const TargetMachine
*TM
;
61 const TargetInstrInfo
*TII
;
62 const TargetLowering
*TLI
;
63 const TargetRegisterInfo
*TRI
;
64 const MachineFrameInfo
*MFI
;
65 MachineRegisterInfo
*MRI
;
66 const InstrItineraryData
*InstrItins
;
68 // Various analyses that we use...
69 AliasAnalysis
*AA
; // Alias analysis info.
70 MachineLoopInfo
*MLI
; // Current MachineLoopInfo
71 MachineDominatorTree
*DT
; // Machine dominator tree for the cur loop
73 // State that is updated as we process loops
74 bool Changed
; // True if a loop is changed.
75 bool FirstInLoop
; // True if it's the first LICM in the loop.
76 MachineLoop
*CurLoop
; // The current loop we are working on.
77 MachineBasicBlock
*CurPreheader
; // The preheader for CurLoop.
79 BitVector AllocatableSet
;
81 // Track 'estimated' register pressure.
82 SmallSet
<unsigned, 32> RegSeen
;
83 SmallVector
<unsigned, 8> RegPressure
;
85 // Register pressure "limit" per register class. If the pressure
86 // is higher than the limit, then it's considered high.
87 SmallVector
<unsigned, 8> RegLimit
;
89 // Register pressure on path leading from loop preheader to current BB.
90 SmallVector
<SmallVector
<unsigned, 8>, 16> BackTrace
;
92 // For each opcode, keep a list of potential CSE instructions.
93 DenseMap
<unsigned, std::vector
<const MachineInstr
*> > CSEMap
;
96 static char ID
; // Pass identification, replacement for typeid
98 MachineFunctionPass(ID
), PreRegAlloc(true) {
99 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
102 explicit MachineLICM(bool PreRA
) :
103 MachineFunctionPass(ID
), PreRegAlloc(PreRA
) {
104 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
107 virtual bool runOnMachineFunction(MachineFunction
&MF
);
109 const char *getPassName() const { return "Machine Instruction LICM"; }
111 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
112 AU
.addRequired
<MachineLoopInfo
>();
113 AU
.addRequired
<MachineDominatorTree
>();
114 AU
.addRequired
<AliasAnalysis
>();
115 AU
.addPreserved
<MachineLoopInfo
>();
116 AU
.addPreserved
<MachineDominatorTree
>();
117 MachineFunctionPass::getAnalysisUsage(AU
);
120 virtual void releaseMemory() {
125 for (DenseMap
<unsigned,std::vector
<const MachineInstr
*> >::iterator
126 CI
= CSEMap
.begin(), CE
= CSEMap
.end(); CI
!= CE
; ++CI
)
132 /// CandidateInfo - Keep track of information about hoisting candidates.
133 struct CandidateInfo
{
137 CandidateInfo(MachineInstr
*mi
, unsigned def
, int fi
)
138 : MI(mi
), Def(def
), FI(fi
) {}
141 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
142 /// invariants out to the preheader.
143 void HoistRegionPostRA();
145 /// HoistPostRA - When an instruction is found to only use loop invariant
146 /// operands that is safe to hoist, this instruction is called to do the
148 void HoistPostRA(MachineInstr
*MI
, unsigned Def
);
150 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
151 /// gather register def and frame object update information.
152 void ProcessMI(MachineInstr
*MI
, unsigned *PhysRegDefs
,
153 SmallSet
<int, 32> &StoredFIs
,
154 SmallVector
<CandidateInfo
, 32> &Candidates
);
156 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
158 void AddToLiveIns(unsigned Reg
);
160 /// IsLICMCandidate - Returns true if the instruction may be a suitable
161 /// candidate for LICM. e.g. If the instruction is a call, then it's
162 /// obviously not safe to hoist it.
163 bool IsLICMCandidate(MachineInstr
&I
);
165 /// IsLoopInvariantInst - Returns true if the instruction is loop
166 /// invariant. I.e., all virtual register operands are defined outside of
167 /// the loop, physical registers aren't accessed (explicitly or implicitly),
168 /// and the instruction is hoistable.
170 bool IsLoopInvariantInst(MachineInstr
&I
);
172 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
173 /// and an use in the current loop, return true if the target considered
175 bool HasHighOperandLatency(MachineInstr
&MI
, unsigned DefIdx
,
178 bool IsCheapInstruction(MachineInstr
&MI
) const;
180 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
181 /// check if hoisting an instruction of the given cost matrix can cause high
182 /// register pressure.
183 bool CanCauseHighRegPressure(DenseMap
<unsigned, int> &Cost
);
185 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
186 /// the current block and update their register pressures to reflect the
187 /// effect of hoisting MI from the current block to the preheader.
188 void UpdateBackTraceRegPressure(const MachineInstr
*MI
);
190 /// IsProfitableToHoist - Return true if it is potentially profitable to
191 /// hoist the given loop invariant.
192 bool IsProfitableToHoist(MachineInstr
&MI
);
194 /// HoistRegion - Walk the specified region of the CFG (defined by all
195 /// blocks dominated by the specified block, and that are in the current
196 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
197 /// visit definitions before uses, allowing us to hoist a loop body in one
198 /// pass without iteration.
200 void HoistRegion(MachineDomTreeNode
*N
, bool IsHeader
= false);
202 /// InitRegPressure - Find all virtual register references that are liveout
203 /// of the preheader to initialize the starting "register pressure". Note
204 /// this does not count live through (livein but not used) registers.
205 void InitRegPressure(MachineBasicBlock
*BB
);
207 /// UpdateRegPressure - Update estimate of register pressure after the
208 /// specified instruction.
209 void UpdateRegPressure(const MachineInstr
*MI
);
211 /// isLoadFromConstantMemory - Return true if the given instruction is a
212 /// load from constant memory.
213 bool isLoadFromConstantMemory(MachineInstr
*MI
);
215 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
216 /// the load itself could be hoisted. Return the unfolded and hoistable
217 /// load, or null if the load couldn't be unfolded or if it wouldn't
219 MachineInstr
*ExtractHoistableLoad(MachineInstr
*MI
);
221 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
222 /// duplicate of MI. Return this instruction if it's found.
223 const MachineInstr
*LookForDuplicate(const MachineInstr
*MI
,
224 std::vector
<const MachineInstr
*> &PrevMIs
);
226 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
227 /// the preheader that compute the same value. If it's found, do a RAU on
228 /// with the definition of the existing instruction rather than hoisting
229 /// the instruction to the preheader.
230 bool EliminateCSE(MachineInstr
*MI
,
231 DenseMap
<unsigned, std::vector
<const MachineInstr
*> >::iterator
&CI
);
233 /// Hoist - When an instruction is found to only use loop invariant operands
234 /// that is safe to hoist, this instruction is called to do the dirty work.
235 /// It returns true if the instruction is hoisted.
236 bool Hoist(MachineInstr
*MI
, MachineBasicBlock
*Preheader
);
238 /// InitCSEMap - Initialize the CSE map with instructions that are in the
239 /// current loop preheader that may become duplicates of instructions that
240 /// are hoisted out of the loop.
241 void InitCSEMap(MachineBasicBlock
*BB
);
243 /// getCurPreheader - Get the preheader for the current loop, splitting
244 /// a critical edge if needed.
245 MachineBasicBlock
*getCurPreheader();
247 } // end anonymous namespace
249 char MachineLICM::ID
= 0;
250 INITIALIZE_PASS_BEGIN(MachineLICM
, "machinelicm",
251 "Machine Loop Invariant Code Motion", false, false)
252 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
253 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
254 INITIALIZE_AG_DEPENDENCY(AliasAnalysis
)
255 INITIALIZE_PASS_END(MachineLICM
, "machinelicm",
256 "Machine Loop Invariant Code Motion", false, false)
258 FunctionPass
*llvm::createMachineLICMPass(bool PreRegAlloc
) {
259 return new MachineLICM(PreRegAlloc
);
262 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
263 /// loop that has a unique predecessor.
264 static bool LoopIsOuterMostWithPredecessor(MachineLoop
*CurLoop
) {
265 // Check whether this loop even has a unique predecessor.
266 if (!CurLoop
->getLoopPredecessor())
268 // Ok, now check to see if any of its outer loops do.
269 for (MachineLoop
*L
= CurLoop
->getParentLoop(); L
; L
= L
->getParentLoop())
270 if (L
->getLoopPredecessor())
272 // None of them did, so this is the outermost with a unique predecessor.
276 bool MachineLICM::runOnMachineFunction(MachineFunction
&MF
) {
278 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
280 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
281 DEBUG(dbgs() << MF
.getFunction()->getName() << " ********\n");
283 Changed
= FirstInLoop
= false;
284 TM
= &MF
.getTarget();
285 TII
= TM
->getInstrInfo();
286 TLI
= TM
->getTargetLowering();
287 TRI
= TM
->getRegisterInfo();
288 MFI
= MF
.getFrameInfo();
289 MRI
= &MF
.getRegInfo();
290 InstrItins
= TM
->getInstrItineraryData();
291 AllocatableSet
= TRI
->getAllocatableSet(MF
);
294 // Estimate register pressure during pre-regalloc pass.
295 unsigned NumRC
= TRI
->getNumRegClasses();
296 RegPressure
.resize(NumRC
);
297 std::fill(RegPressure
.begin(), RegPressure
.end(), 0);
298 RegLimit
.resize(NumRC
);
299 for (TargetRegisterInfo::regclass_iterator I
= TRI
->regclass_begin(),
300 E
= TRI
->regclass_end(); I
!= E
; ++I
)
301 RegLimit
[(*I
)->getID()] = TLI
->getRegPressureLimit(*I
, MF
);
304 // Get our Loop information...
305 MLI
= &getAnalysis
<MachineLoopInfo
>();
306 DT
= &getAnalysis
<MachineDominatorTree
>();
307 AA
= &getAnalysis
<AliasAnalysis
>();
309 SmallVector
<MachineLoop
*, 8> Worklist(MLI
->begin(), MLI
->end());
310 while (!Worklist
.empty()) {
311 CurLoop
= Worklist
.pop_back_val();
314 // If this is done before regalloc, only visit outer-most preheader-sporting
316 if (PreRegAlloc
&& !LoopIsOuterMostWithPredecessor(CurLoop
)) {
317 Worklist
.append(CurLoop
->begin(), CurLoop
->end());
324 // CSEMap is initialized for loop header when the first instruction is
326 MachineDomTreeNode
*N
= DT
->getNode(CurLoop
->getHeader());
328 HoistRegion(N
, true);
336 /// InstructionStoresToFI - Return true if instruction stores to the
338 static bool InstructionStoresToFI(const MachineInstr
*MI
, int FI
) {
339 for (MachineInstr::mmo_iterator o
= MI
->memoperands_begin(),
340 oe
= MI
->memoperands_end(); o
!= oe
; ++o
) {
341 if (!(*o
)->isStore() || !(*o
)->getValue())
343 if (const FixedStackPseudoSourceValue
*Value
=
344 dyn_cast
<const FixedStackPseudoSourceValue
>((*o
)->getValue())) {
345 if (Value
->getFrameIndex() == FI
)
352 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
353 /// gather register def and frame object update information.
354 void MachineLICM::ProcessMI(MachineInstr
*MI
,
355 unsigned *PhysRegDefs
,
356 SmallSet
<int, 32> &StoredFIs
,
357 SmallVector
<CandidateInfo
, 32> &Candidates
) {
358 bool RuledOut
= false;
359 bool HasNonInvariantUse
= false;
361 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
362 const MachineOperand
&MO
= MI
->getOperand(i
);
364 // Remember if the instruction stores to the frame index.
365 int FI
= MO
.getIndex();
366 if (!StoredFIs
.count(FI
) &&
367 MFI
->isSpillSlotObjectIndex(FI
) &&
368 InstructionStoresToFI(MI
, FI
))
369 StoredFIs
.insert(FI
);
370 HasNonInvariantUse
= true;
376 unsigned Reg
= MO
.getReg();
379 assert(TargetRegisterInfo::isPhysicalRegister(Reg
) &&
380 "Not expecting virtual register!");
383 if (Reg
&& PhysRegDefs
[Reg
])
384 // If it's using a non-loop-invariant register, then it's obviously not
386 HasNonInvariantUse
= true;
390 if (MO
.isImplicit()) {
392 for (const unsigned *AS
= TRI
->getAliasSet(Reg
); *AS
; ++AS
)
395 // Non-dead implicit def? This cannot be hoisted.
397 // No need to check if a dead implicit def is also defined by
398 // another instruction.
402 // FIXME: For now, avoid instructions with multiple defs, unless
403 // it's a dead implicit def.
409 // If we have already seen another instruction that defines the same
410 // register, then this is not safe.
411 if (++PhysRegDefs
[Reg
] > 1)
412 // MI defined register is seen defined by another instruction in
413 // the loop, it cannot be a LICM candidate.
415 for (const unsigned *AS
= TRI
->getAliasSet(Reg
); *AS
; ++AS
)
416 if (++PhysRegDefs
[*AS
] > 1)
420 // Only consider reloads for now and remats which do not have register
421 // operands. FIXME: Consider unfold load folding instructions.
422 if (Def
&& !RuledOut
) {
424 if ((!HasNonInvariantUse
&& IsLICMCandidate(*MI
)) ||
425 (TII
->isLoadFromStackSlot(MI
, FI
) && MFI
->isSpillSlotObjectIndex(FI
)))
426 Candidates
.push_back(CandidateInfo(MI
, Def
, FI
));
430 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
431 /// invariants out to the preheader.
432 void MachineLICM::HoistRegionPostRA() {
433 unsigned NumRegs
= TRI
->getNumRegs();
434 unsigned *PhysRegDefs
= new unsigned[NumRegs
];
435 std::fill(PhysRegDefs
, PhysRegDefs
+ NumRegs
, 0);
437 SmallVector
<CandidateInfo
, 32> Candidates
;
438 SmallSet
<int, 32> StoredFIs
;
440 // Walk the entire region, count number of defs for each register, and
441 // collect potential LICM candidates.
442 const std::vector
<MachineBasicBlock
*> Blocks
= CurLoop
->getBlocks();
443 for (unsigned i
= 0, e
= Blocks
.size(); i
!= e
; ++i
) {
444 MachineBasicBlock
*BB
= Blocks
[i
];
445 // Conservatively treat live-in's as an external def.
446 // FIXME: That means a reload that're reused in successor block(s) will not
448 for (MachineBasicBlock::livein_iterator I
= BB
->livein_begin(),
449 E
= BB
->livein_end(); I
!= E
; ++I
) {
452 for (const unsigned *AS
= TRI
->getAliasSet(Reg
); *AS
; ++AS
)
456 for (MachineBasicBlock::iterator
457 MII
= BB
->begin(), E
= BB
->end(); MII
!= E
; ++MII
) {
458 MachineInstr
*MI
= &*MII
;
459 ProcessMI(MI
, PhysRegDefs
, StoredFIs
, Candidates
);
463 // Now evaluate whether the potential candidates qualify.
464 // 1. Check if the candidate defined register is defined by another
465 // instruction in the loop.
466 // 2. If the candidate is a load from stack slot (always true for now),
467 // check if the slot is stored anywhere in the loop.
468 for (unsigned i
= 0, e
= Candidates
.size(); i
!= e
; ++i
) {
469 if (Candidates
[i
].FI
!= INT_MIN
&&
470 StoredFIs
.count(Candidates
[i
].FI
))
473 if (PhysRegDefs
[Candidates
[i
].Def
] == 1) {
475 MachineInstr
*MI
= Candidates
[i
].MI
;
476 for (unsigned j
= 0, ee
= MI
->getNumOperands(); j
!= ee
; ++j
) {
477 const MachineOperand
&MO
= MI
->getOperand(j
);
478 if (!MO
.isReg() || MO
.isDef() || !MO
.getReg())
480 if (PhysRegDefs
[MO
.getReg()]) {
481 // If it's using a non-loop-invariant register, then it's obviously
482 // not safe to hoist.
488 HoistPostRA(MI
, Candidates
[i
].Def
);
492 delete[] PhysRegDefs
;
495 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
496 /// loop, and make sure it is not killed by any instructions in the loop.
497 void MachineLICM::AddToLiveIns(unsigned Reg
) {
498 const std::vector
<MachineBasicBlock
*> Blocks
= CurLoop
->getBlocks();
499 for (unsigned i
= 0, e
= Blocks
.size(); i
!= e
; ++i
) {
500 MachineBasicBlock
*BB
= Blocks
[i
];
501 if (!BB
->isLiveIn(Reg
))
503 for (MachineBasicBlock::iterator
504 MII
= BB
->begin(), E
= BB
->end(); MII
!= E
; ++MII
) {
505 MachineInstr
*MI
= &*MII
;
506 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
507 MachineOperand
&MO
= MI
->getOperand(i
);
508 if (!MO
.isReg() || !MO
.getReg() || MO
.isDef()) continue;
509 if (MO
.getReg() == Reg
|| TRI
->isSuperRegister(Reg
, MO
.getReg()))
516 /// HoistPostRA - When an instruction is found to only use loop invariant
517 /// operands that is safe to hoist, this instruction is called to do the
519 void MachineLICM::HoistPostRA(MachineInstr
*MI
, unsigned Def
) {
520 MachineBasicBlock
*Preheader
= getCurPreheader();
521 if (!Preheader
) return;
523 // Now move the instructions to the predecessor, inserting it before any
524 // terminator instructions.
526 dbgs() << "Hoisting " << *MI
;
527 if (Preheader
->getBasicBlock())
528 dbgs() << " to MachineBasicBlock "
529 << Preheader
->getName();
530 if (MI
->getParent()->getBasicBlock())
531 dbgs() << " from MachineBasicBlock "
532 << MI
->getParent()->getName();
536 // Splice the instruction to the preheader.
537 MachineBasicBlock
*MBB
= MI
->getParent();
538 Preheader
->splice(Preheader
->getFirstTerminator(), MBB
, MI
);
540 // Add register to livein list to all the BBs in the current loop since a
541 // loop invariant must be kept live throughout the whole loop. This is
542 // important to ensure later passes do not scavenge the def register.
549 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
550 /// dominated by the specified block, and that are in the current loop) in depth
551 /// first order w.r.t the DominatorTree. This allows us to visit definitions
552 /// before uses, allowing us to hoist a loop body in one pass without iteration.
554 void MachineLICM::HoistRegion(MachineDomTreeNode
*N
, bool IsHeader
) {
555 assert(N
!= 0 && "Null dominator tree node?");
556 MachineBasicBlock
*BB
= N
->getBlock();
558 // If this subregion is not in the top level loop at all, exit.
559 if (!CurLoop
->contains(BB
)) return;
561 MachineBasicBlock
*Preheader
= getCurPreheader();
566 // Compute registers which are livein into the loop headers.
569 InitRegPressure(Preheader
);
572 // Remember livein register pressure.
573 BackTrace
.push_back(RegPressure
);
575 for (MachineBasicBlock::iterator
576 MII
= BB
->begin(), E
= BB
->end(); MII
!= E
; ) {
577 MachineBasicBlock::iterator NextMII
= MII
; ++NextMII
;
578 MachineInstr
*MI
= &*MII
;
579 if (!Hoist(MI
, Preheader
))
580 UpdateRegPressure(MI
);
584 // Don't hoist things out of a large switch statement. This often causes
585 // code to be hoisted that wasn't going to be executed, and increases
586 // register pressure in a situation where it's likely to matter.
587 if (BB
->succ_size() < 25) {
588 const std::vector
<MachineDomTreeNode
*> &Children
= N
->getChildren();
589 for (unsigned I
= 0, E
= Children
.size(); I
!= E
; ++I
)
590 HoistRegion(Children
[I
]);
593 BackTrace
.pop_back();
596 static bool isOperandKill(const MachineOperand
&MO
, MachineRegisterInfo
*MRI
) {
597 return MO
.isKill() || MRI
->hasOneNonDBGUse(MO
.getReg());
600 /// InitRegPressure - Find all virtual register references that are liveout of
601 /// the preheader to initialize the starting "register pressure". Note this
602 /// does not count live through (livein but not used) registers.
603 void MachineLICM::InitRegPressure(MachineBasicBlock
*BB
) {
604 std::fill(RegPressure
.begin(), RegPressure
.end(), 0);
606 // If the preheader has only a single predecessor and it ends with a
607 // fallthrough or an unconditional branch, then scan its predecessor for live
608 // defs as well. This happens whenever the preheader is created by splitting
609 // the critical edge from the loop predecessor to the loop header.
610 if (BB
->pred_size() == 1) {
611 MachineBasicBlock
*TBB
= 0, *FBB
= 0;
612 SmallVector
<MachineOperand
, 4> Cond
;
613 if (!TII
->AnalyzeBranch(*BB
, TBB
, FBB
, Cond
, false) && Cond
.empty())
614 InitRegPressure(*BB
->pred_begin());
617 for (MachineBasicBlock::iterator MII
= BB
->begin(), E
= BB
->end();
619 MachineInstr
*MI
= &*MII
;
620 for (unsigned i
= 0, e
= MI
->getDesc().getNumOperands(); i
!= e
; ++i
) {
621 const MachineOperand
&MO
= MI
->getOperand(i
);
622 if (!MO
.isReg() || MO
.isImplicit())
624 unsigned Reg
= MO
.getReg();
625 if (!Reg
|| TargetRegisterInfo::isPhysicalRegister(Reg
))
628 bool isNew
= RegSeen
.insert(Reg
);
629 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
630 EVT VT
= *RC
->vt_begin();
631 unsigned RCId
= TLI
->getRepRegClassFor(VT
)->getID();
633 RegPressure
[RCId
] += TLI
->getRepRegClassCostFor(VT
);
635 bool isKill
= isOperandKill(MO
, MRI
);
636 if (isNew
&& !isKill
)
637 // Haven't seen this, it must be a livein.
638 RegPressure
[RCId
] += TLI
->getRepRegClassCostFor(VT
);
639 else if (!isNew
&& isKill
)
640 RegPressure
[RCId
] -= TLI
->getRepRegClassCostFor(VT
);
646 /// UpdateRegPressure - Update estimate of register pressure after the
647 /// specified instruction.
648 void MachineLICM::UpdateRegPressure(const MachineInstr
*MI
) {
649 if (MI
->isImplicitDef())
652 SmallVector
<unsigned, 4> Defs
;
653 for (unsigned i
= 0, e
= MI
->getDesc().getNumOperands(); i
!= e
; ++i
) {
654 const MachineOperand
&MO
= MI
->getOperand(i
);
655 if (!MO
.isReg() || MO
.isImplicit())
657 unsigned Reg
= MO
.getReg();
658 if (!Reg
|| TargetRegisterInfo::isPhysicalRegister(Reg
))
661 bool isNew
= RegSeen
.insert(Reg
);
664 else if (!isNew
&& isOperandKill(MO
, MRI
)) {
665 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
666 EVT VT
= *RC
->vt_begin();
667 unsigned RCId
= TLI
->getRepRegClassFor(VT
)->getID();
668 unsigned RCCost
= TLI
->getRepRegClassCostFor(VT
);
670 if (RCCost
> RegPressure
[RCId
])
671 RegPressure
[RCId
] = 0;
673 RegPressure
[RCId
] -= RCCost
;
677 while (!Defs
.empty()) {
678 unsigned Reg
= Defs
.pop_back_val();
679 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
680 EVT VT
= *RC
->vt_begin();
681 unsigned RCId
= TLI
->getRepRegClassFor(VT
)->getID();
682 unsigned RCCost
= TLI
->getRepRegClassCostFor(VT
);
683 RegPressure
[RCId
] += RCCost
;
687 /// IsLICMCandidate - Returns true if the instruction may be a suitable
688 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
689 /// not safe to hoist it.
690 bool MachineLICM::IsLICMCandidate(MachineInstr
&I
) {
691 // Check if it's safe to move the instruction.
692 bool DontMoveAcrossStore
= true;
693 if (!I
.isSafeToMove(TII
, AA
, DontMoveAcrossStore
))
699 /// IsLoopInvariantInst - Returns true if the instruction is loop
700 /// invariant. I.e., all virtual register operands are defined outside of the
701 /// loop, physical registers aren't accessed explicitly, and there are no side
702 /// effects that aren't captured by the operands or other flags.
704 bool MachineLICM::IsLoopInvariantInst(MachineInstr
&I
) {
705 if (!IsLICMCandidate(I
))
708 // The instruction is loop invariant if all of its operands are.
709 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
) {
710 const MachineOperand
&MO
= I
.getOperand(i
);
715 unsigned Reg
= MO
.getReg();
716 if (Reg
== 0) continue;
718 // Don't hoist an instruction that uses or defines a physical register.
719 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
721 // If the physreg has no defs anywhere, it's just an ambient register
722 // and we can freely move its uses. Alternatively, if it's allocatable,
723 // it could get allocated to something with a def during allocation.
724 if (!MRI
->def_empty(Reg
))
726 if (AllocatableSet
.test(Reg
))
728 // Check for a def among the register's aliases too.
729 for (const unsigned *Alias
= TRI
->getAliasSet(Reg
); *Alias
; ++Alias
) {
730 unsigned AliasReg
= *Alias
;
731 if (!MRI
->def_empty(AliasReg
))
733 if (AllocatableSet
.test(AliasReg
))
736 // Otherwise it's safe to move.
738 } else if (!MO
.isDead()) {
739 // A def that isn't dead. We can't move it.
741 } else if (CurLoop
->getHeader()->isLiveIn(Reg
)) {
742 // If the reg is live into the loop, we can't hoist an instruction
743 // which would clobber it.
751 assert(MRI
->getVRegDef(Reg
) &&
752 "Machine instr not mapped for this vreg?!");
754 // If the loop contains the definition of an operand, then the instruction
755 // isn't loop invariant.
756 if (CurLoop
->contains(MRI
->getVRegDef(Reg
)))
760 // If we got this far, the instruction is loop invariant!
765 /// HasPHIUses - Return true if the specified register has any PHI use.
766 static bool HasPHIUses(unsigned Reg
, MachineRegisterInfo
*MRI
) {
767 for (MachineRegisterInfo::use_iterator UI
= MRI
->use_begin(Reg
),
768 UE
= MRI
->use_end(); UI
!= UE
; ++UI
) {
769 MachineInstr
*UseMI
= &*UI
;
776 /// isLoadFromConstantMemory - Return true if the given instruction is a
777 /// load from constant memory. Machine LICM will hoist these even if they are
778 /// not re-materializable.
779 bool MachineLICM::isLoadFromConstantMemory(MachineInstr
*MI
) {
780 if (!MI
->getDesc().mayLoad()) return false;
781 if (!MI
->hasOneMemOperand()) return false;
782 MachineMemOperand
*MMO
= *MI
->memoperands_begin();
783 if (MMO
->isVolatile()) return false;
784 if (!MMO
->getValue()) return false;
785 const PseudoSourceValue
*PSV
= dyn_cast
<PseudoSourceValue
>(MMO
->getValue());
787 MachineFunction
&MF
= *MI
->getParent()->getParent();
788 return PSV
->isConstant(MF
.getFrameInfo());
790 return AA
->pointsToConstantMemory(AliasAnalysis::Location(MMO
->getValue(),
792 MMO
->getTBAAInfo()));
796 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
797 /// and an use in the current loop, return true if the target considered
799 bool MachineLICM::HasHighOperandLatency(MachineInstr
&MI
,
800 unsigned DefIdx
, unsigned Reg
) const {
801 if (!InstrItins
|| InstrItins
->isEmpty() || MRI
->use_nodbg_empty(Reg
))
804 for (MachineRegisterInfo::use_nodbg_iterator I
= MRI
->use_nodbg_begin(Reg
),
805 E
= MRI
->use_nodbg_end(); I
!= E
; ++I
) {
806 MachineInstr
*UseMI
= &*I
;
807 if (UseMI
->isCopyLike())
809 if (!CurLoop
->contains(UseMI
->getParent()))
811 for (unsigned i
= 0, e
= UseMI
->getNumOperands(); i
!= e
; ++i
) {
812 const MachineOperand
&MO
= UseMI
->getOperand(i
);
813 if (!MO
.isReg() || !MO
.isUse())
815 unsigned MOReg
= MO
.getReg();
819 if (TII
->hasHighOperandLatency(InstrItins
, MRI
, &MI
, DefIdx
, UseMI
, i
))
823 // Only look at the first in loop use.
830 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
831 /// the operand latency between its def and a use is one or less.
832 bool MachineLICM::IsCheapInstruction(MachineInstr
&MI
) const {
833 if (MI
.getDesc().isAsCheapAsAMove() || MI
.isCopyLike())
835 if (!InstrItins
|| InstrItins
->isEmpty())
838 bool isCheap
= false;
839 unsigned NumDefs
= MI
.getDesc().getNumDefs();
840 for (unsigned i
= 0, e
= MI
.getNumOperands(); NumDefs
&& i
!= e
; ++i
) {
841 MachineOperand
&DefMO
= MI
.getOperand(i
);
842 if (!DefMO
.isReg() || !DefMO
.isDef())
845 unsigned Reg
= DefMO
.getReg();
846 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
849 if (!TII
->hasLowDefLatency(InstrItins
, &MI
, i
))
857 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
858 /// if hoisting an instruction of the given cost matrix can cause high
859 /// register pressure.
860 bool MachineLICM::CanCauseHighRegPressure(DenseMap
<unsigned, int> &Cost
) {
861 for (DenseMap
<unsigned, int>::iterator CI
= Cost
.begin(), CE
= Cost
.end();
866 unsigned RCId
= CI
->first
;
867 for (unsigned i
= BackTrace
.size(); i
!= 0; --i
) {
868 SmallVector
<unsigned, 8> &RP
= BackTrace
[i
-1];
869 if (RP
[RCId
] + CI
->second
>= RegLimit
[RCId
])
877 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
878 /// current block and update their register pressures to reflect the effect
879 /// of hoisting MI from the current block to the preheader.
880 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr
*MI
) {
881 if (MI
->isImplicitDef())
884 // First compute the 'cost' of the instruction, i.e. its contribution
885 // to register pressure.
886 DenseMap
<unsigned, int> Cost
;
887 for (unsigned i
= 0, e
= MI
->getDesc().getNumOperands(); i
!= e
; ++i
) {
888 const MachineOperand
&MO
= MI
->getOperand(i
);
889 if (!MO
.isReg() || MO
.isImplicit())
891 unsigned Reg
= MO
.getReg();
892 if (!Reg
|| TargetRegisterInfo::isPhysicalRegister(Reg
))
895 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
896 EVT VT
= *RC
->vt_begin();
897 unsigned RCId
= TLI
->getRepRegClassFor(VT
)->getID();
898 unsigned RCCost
= TLI
->getRepRegClassCostFor(VT
);
900 DenseMap
<unsigned, int>::iterator CI
= Cost
.find(RCId
);
901 if (CI
!= Cost
.end())
902 CI
->second
+= RCCost
;
904 Cost
.insert(std::make_pair(RCId
, RCCost
));
905 } else if (isOperandKill(MO
, MRI
)) {
906 DenseMap
<unsigned, int>::iterator CI
= Cost
.find(RCId
);
907 if (CI
!= Cost
.end())
908 CI
->second
-= RCCost
;
910 Cost
.insert(std::make_pair(RCId
, -RCCost
));
914 // Update register pressure of blocks from loop header to current block.
915 for (unsigned i
= 0, e
= BackTrace
.size(); i
!= e
; ++i
) {
916 SmallVector
<unsigned, 8> &RP
= BackTrace
[i
];
917 for (DenseMap
<unsigned, int>::iterator CI
= Cost
.begin(), CE
= Cost
.end();
919 unsigned RCId
= CI
->first
;
920 RP
[RCId
] += CI
->second
;
925 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
926 /// the given loop invariant.
927 bool MachineLICM::IsProfitableToHoist(MachineInstr
&MI
) {
928 if (MI
.isImplicitDef())
931 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
932 // will increase register pressure. It's probably not worth it if the
933 // instruction is cheap.
934 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
935 // these tend to help performance in low register pressure situation. The
936 // trade off is it may cause spill in high pressure situation. It will end up
937 // adding a store in the loop preheader. But the reload is no more expensive.
938 // The side benefit is these loads are frequently CSE'ed.
939 if (IsCheapInstruction(MI
)) {
940 if (!TII
->isTriviallyReMaterializable(&MI
, AA
))
943 // Estimate register pressure to determine whether to LICM the instruction.
944 // In low register pressure situation, we can be more aggressive about
945 // hoisting. Also, favors hoisting long latency instructions even in
946 // moderately high pressure situation.
947 DenseMap
<unsigned, int> Cost
;
948 for (unsigned i
= 0, e
= MI
.getDesc().getNumOperands(); i
!= e
; ++i
) {
949 const MachineOperand
&MO
= MI
.getOperand(i
);
950 if (!MO
.isReg() || MO
.isImplicit())
952 unsigned Reg
= MO
.getReg();
953 if (!Reg
|| TargetRegisterInfo::isPhysicalRegister(Reg
))
956 if (HasHighOperandLatency(MI
, i
, Reg
)) {
961 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
962 EVT VT
= *RC
->vt_begin();
963 unsigned RCId
= TLI
->getRepRegClassFor(VT
)->getID();
964 unsigned RCCost
= TLI
->getRepRegClassCostFor(VT
);
965 DenseMap
<unsigned, int>::iterator CI
= Cost
.find(RCId
);
966 if (CI
!= Cost
.end())
967 CI
->second
+= RCCost
;
969 Cost
.insert(std::make_pair(RCId
, RCCost
));
970 } else if (isOperandKill(MO
, MRI
)) {
971 // Is a virtual register use is a kill, hoisting it out of the loop
972 // may actually reduce register pressure or be register pressure
974 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
975 EVT VT
= *RC
->vt_begin();
976 unsigned RCId
= TLI
->getRepRegClassFor(VT
)->getID();
977 unsigned RCCost
= TLI
->getRepRegClassCostFor(VT
);
978 DenseMap
<unsigned, int>::iterator CI
= Cost
.find(RCId
);
979 if (CI
!= Cost
.end())
980 CI
->second
-= RCCost
;
982 Cost
.insert(std::make_pair(RCId
, -RCCost
));
986 // Visit BBs from header to current BB, if hoisting this doesn't cause
987 // high register pressure, then it's safe to proceed.
988 if (!CanCauseHighRegPressure(Cost
)) {
993 // High register pressure situation, only hoist if the instruction is going to
995 if (!TII
->isTriviallyReMaterializable(&MI
, AA
) &&
996 !isLoadFromConstantMemory(&MI
))
1000 // If result(s) of this instruction is used by PHIs, then don't hoist it.
1001 // The presence of joins makes it difficult for current register allocator
1002 // implementation to perform remat.
1003 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
1004 const MachineOperand
&MO
= MI
.getOperand(i
);
1005 if (!MO
.isReg() || !MO
.isDef())
1007 if (HasPHIUses(MO
.getReg(), MRI
))
1014 MachineInstr
*MachineLICM::ExtractHoistableLoad(MachineInstr
*MI
) {
1015 // Don't unfold simple loads.
1016 if (MI
->getDesc().canFoldAsLoad())
1019 // If not, we may be able to unfold a load and hoist that.
1020 // First test whether the instruction is loading from an amenable
1022 if (!isLoadFromConstantMemory(MI
))
1025 // Next determine the register class for a temporary register.
1026 unsigned LoadRegIndex
;
1028 TII
->getOpcodeAfterMemoryUnfold(MI
->getOpcode(),
1029 /*UnfoldLoad=*/true,
1030 /*UnfoldStore=*/false,
1032 if (NewOpc
== 0) return 0;
1033 const TargetInstrDesc
&TID
= TII
->get(NewOpc
);
1034 if (TID
.getNumDefs() != 1) return 0;
1035 const TargetRegisterClass
*RC
= TID
.OpInfo
[LoadRegIndex
].getRegClass(TRI
);
1036 // Ok, we're unfolding. Create a temporary register and do the unfold.
1037 unsigned Reg
= MRI
->createVirtualRegister(RC
);
1039 MachineFunction
&MF
= *MI
->getParent()->getParent();
1040 SmallVector
<MachineInstr
*, 2> NewMIs
;
1042 TII
->unfoldMemoryOperand(MF
, MI
, Reg
,
1043 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1047 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1049 assert(NewMIs
.size() == 2 &&
1050 "Unfolded a load into multiple instructions!");
1051 MachineBasicBlock
*MBB
= MI
->getParent();
1052 MBB
->insert(MI
, NewMIs
[0]);
1053 MBB
->insert(MI
, NewMIs
[1]);
1054 // If unfolding produced a load that wasn't loop-invariant or profitable to
1055 // hoist, discard the new instructions and bail.
1056 if (!IsLoopInvariantInst(*NewMIs
[0]) || !IsProfitableToHoist(*NewMIs
[0])) {
1057 NewMIs
[0]->eraseFromParent();
1058 NewMIs
[1]->eraseFromParent();
1062 // Update register pressure for the unfolded instruction.
1063 UpdateRegPressure(NewMIs
[1]);
1065 // Otherwise we successfully unfolded a load that we can hoist.
1066 MI
->eraseFromParent();
1070 void MachineLICM::InitCSEMap(MachineBasicBlock
*BB
) {
1071 for (MachineBasicBlock::iterator I
= BB
->begin(),E
= BB
->end(); I
!= E
; ++I
) {
1072 const MachineInstr
*MI
= &*I
;
1073 // FIXME: For now, only hoist re-materilizable instructions. LICM will
1074 // increase register pressure. We want to make sure it doesn't increase
1076 if (TII
->isTriviallyReMaterializable(MI
, AA
)) {
1077 unsigned Opcode
= MI
->getOpcode();
1078 DenseMap
<unsigned, std::vector
<const MachineInstr
*> >::iterator
1079 CI
= CSEMap
.find(Opcode
);
1080 if (CI
!= CSEMap
.end())
1081 CI
->second
.push_back(MI
);
1083 std::vector
<const MachineInstr
*> CSEMIs
;
1084 CSEMIs
.push_back(MI
);
1085 CSEMap
.insert(std::make_pair(Opcode
, CSEMIs
));
1092 MachineLICM::LookForDuplicate(const MachineInstr
*MI
,
1093 std::vector
<const MachineInstr
*> &PrevMIs
) {
1094 for (unsigned i
= 0, e
= PrevMIs
.size(); i
!= e
; ++i
) {
1095 const MachineInstr
*PrevMI
= PrevMIs
[i
];
1096 if (TII
->produceSameValue(MI
, PrevMI
))
1102 bool MachineLICM::EliminateCSE(MachineInstr
*MI
,
1103 DenseMap
<unsigned, std::vector
<const MachineInstr
*> >::iterator
&CI
) {
1104 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1105 // the undef property onto uses.
1106 if (CI
== CSEMap
.end() || MI
->isImplicitDef())
1109 if (const MachineInstr
*Dup
= LookForDuplicate(MI
, CI
->second
)) {
1110 DEBUG(dbgs() << "CSEing " << *MI
<< " with " << *Dup
);
1112 // Replace virtual registers defined by MI by their counterparts defined
1114 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1115 const MachineOperand
&MO
= MI
->getOperand(i
);
1117 // Physical registers may not differ here.
1118 assert((!MO
.isReg() || MO
.getReg() == 0 ||
1119 !TargetRegisterInfo::isPhysicalRegister(MO
.getReg()) ||
1120 MO
.getReg() == Dup
->getOperand(i
).getReg()) &&
1121 "Instructions with different phys regs are not identical!");
1123 if (MO
.isReg() && MO
.isDef() &&
1124 !TargetRegisterInfo::isPhysicalRegister(MO
.getReg())) {
1125 MRI
->replaceRegWith(MO
.getReg(), Dup
->getOperand(i
).getReg());
1126 MRI
->clearKillFlags(Dup
->getOperand(i
).getReg());
1129 MI
->eraseFromParent();
1136 /// Hoist - When an instruction is found to use only loop invariant operands
1137 /// that are safe to hoist, this instruction is called to do the dirty work.
1139 bool MachineLICM::Hoist(MachineInstr
*MI
, MachineBasicBlock
*Preheader
) {
1140 // First check whether we should hoist this instruction.
1141 if (!IsLoopInvariantInst(*MI
) || !IsProfitableToHoist(*MI
)) {
1142 // If not, try unfolding a hoistable load.
1143 MI
= ExtractHoistableLoad(MI
);
1144 if (!MI
) return false;
1147 // Now move the instructions to the predecessor, inserting it before any
1148 // terminator instructions.
1150 dbgs() << "Hoisting " << *MI
;
1151 if (Preheader
->getBasicBlock())
1152 dbgs() << " to MachineBasicBlock "
1153 << Preheader
->getName();
1154 if (MI
->getParent()->getBasicBlock())
1155 dbgs() << " from MachineBasicBlock "
1156 << MI
->getParent()->getName();
1160 // If this is the first instruction being hoisted to the preheader,
1161 // initialize the CSE map with potential common expressions.
1163 InitCSEMap(Preheader
);
1164 FirstInLoop
= false;
1167 // Look for opportunity to CSE the hoisted instruction.
1168 unsigned Opcode
= MI
->getOpcode();
1169 DenseMap
<unsigned, std::vector
<const MachineInstr
*> >::iterator
1170 CI
= CSEMap
.find(Opcode
);
1171 if (!EliminateCSE(MI
, CI
)) {
1172 // Otherwise, splice the instruction to the preheader.
1173 Preheader
->splice(Preheader
->getFirstTerminator(),MI
->getParent(),MI
);
1175 // Update register pressure for BBs from header to this block.
1176 UpdateBackTraceRegPressure(MI
);
1178 // Clear the kill flags of any register this instruction defines,
1179 // since they may need to be live throughout the entire loop
1180 // rather than just live for part of it.
1181 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1182 MachineOperand
&MO
= MI
->getOperand(i
);
1183 if (MO
.isReg() && MO
.isDef() && !MO
.isDead())
1184 MRI
->clearKillFlags(MO
.getReg());
1187 // Add to the CSE map.
1188 if (CI
!= CSEMap
.end())
1189 CI
->second
.push_back(MI
);
1191 std::vector
<const MachineInstr
*> CSEMIs
;
1192 CSEMIs
.push_back(MI
);
1193 CSEMap
.insert(std::make_pair(Opcode
, CSEMIs
));
1203 MachineBasicBlock
*MachineLICM::getCurPreheader() {
1204 // Determine the block to which to hoist instructions. If we can't find a
1205 // suitable loop predecessor, we can't do any hoisting.
1207 // If we've tried to get a preheader and failed, don't try again.
1208 if (CurPreheader
== reinterpret_cast<MachineBasicBlock
*>(-1))
1211 if (!CurPreheader
) {
1212 CurPreheader
= CurLoop
->getLoopPreheader();
1213 if (!CurPreheader
) {
1214 MachineBasicBlock
*Pred
= CurLoop
->getLoopPredecessor();
1216 CurPreheader
= reinterpret_cast<MachineBasicBlock
*>(-1);
1220 CurPreheader
= Pred
->SplitCriticalEdge(CurLoop
->getHeader(), this);
1221 if (!CurPreheader
) {
1222 CurPreheader
= reinterpret_cast<MachineBasicBlock
*>(-1);
1227 return CurPreheader
;