1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
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 is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
17 // This pass provides an optional shrink wrapping variant of prolog/epilog
18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
20 //===----------------------------------------------------------------------===//
22 #include "PrologEpilogInserter.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetFrameInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/STLExtras.h"
43 static RegisterPass<PEI>
44 X("prologepilog", "Prologue/Epilogue Insertion");
46 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
47 /// prolog and epilog code, and eliminates abstract frame references.
49 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
51 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
52 /// frame indexes with appropriate references.
54 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
55 const Function* F = Fn.getFunction();
56 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
57 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
58 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
59 FrameConstantRegMap.clear();
61 // Calculate the MaxCallFrameSize and HasCalls variables for the function's
62 // frame information. Also eliminates call frame pseudo instructions.
63 calculateCallsInformation(Fn);
65 // Allow the target machine to make some adjustments to the function
66 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
67 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
69 // Scan the function for modified callee saved registers and insert spill code
70 // for any callee saved registers that are modified.
71 calculateCalleeSavedRegisters(Fn);
73 // Determine placement of CSR spill/restore code:
74 // - with shrink wrapping, place spills and restores to tightly
75 // enclose regions in the Machine CFG of the function where
76 // they are used. Without shrink wrapping
77 // - default (no shrink wrapping), place all spills in the
78 // entry block, all restores in return blocks.
79 placeCSRSpillsAndRestores(Fn);
81 // Add the code to save and restore the callee saved registers
82 if (!F->hasFnAttr(Attribute::Naked))
83 insertCSRSpillsAndRestores(Fn);
85 // Allow the target machine to make final modifications to the function
86 // before the frame layout is finalized.
87 TRI->processFunctionBeforeFrameFinalized(Fn);
89 // Calculate actual frame offsets for all abstract stack objects...
90 calculateFrameObjectOffsets(Fn);
92 // Add prolog and epilog code to the function. This function is required
93 // to align the stack frame as necessary for any stack variables or
94 // called functions. Because of this, calculateCalleeSavedRegisters
95 // must be called before this function in order to set the HasCalls
96 // and MaxCallFrameSize variables.
97 if (!F->hasFnAttr(Attribute::Naked))
98 insertPrologEpilogCode(Fn);
100 // Replace all MO_FrameIndex operands with physical register references
101 // and actual offsets.
103 replaceFrameIndices(Fn);
105 // If register scavenging is needed, as we've enabled doing it as a
106 // post-pass, scavenge the virtual registers that frame index elimiation
108 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
109 scavengeFrameVirtualRegs(Fn);
117 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
118 AU.setPreservesCFG();
119 if (ShrinkWrapping || ShrinkWrapFunc != "") {
120 AU.addRequired<MachineLoopInfo>();
121 AU.addRequired<MachineDominatorTree>();
123 AU.addPreserved<MachineLoopInfo>();
124 AU.addPreserved<MachineDominatorTree>();
125 MachineFunctionPass::getAnalysisUsage(AU);
129 /// calculateCallsInformation - Calculate the MaxCallFrameSize and HasCalls
130 /// variables for the function's frame information and eliminate call frame
131 /// pseudo instructions.
132 void PEI::calculateCallsInformation(MachineFunction &Fn) {
133 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
134 MachineFrameInfo *MFI = Fn.getFrameInfo();
136 unsigned MaxCallFrameSize = 0;
137 bool HasCalls = MFI->hasCalls();
139 // Get the function call frame set-up and tear-down instruction opcode
140 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
141 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
143 // Early exit for targets which have no call frame setup/destroy pseudo
145 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
148 std::vector<MachineBasicBlock::iterator> FrameSDOps;
149 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
150 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
151 if (I->getOpcode() == FrameSetupOpcode ||
152 I->getOpcode() == FrameDestroyOpcode) {
153 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
154 " instructions should have a single immediate argument!");
155 unsigned Size = I->getOperand(0).getImm();
156 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
158 FrameSDOps.push_back(I);
159 } else if (I->isInlineAsm()) {
160 // An InlineAsm might be a call; assume it is to get the stack frame
161 // aligned correctly for calls.
165 MFI->setHasCalls(HasCalls);
166 MFI->setMaxCallFrameSize(MaxCallFrameSize);
168 for (std::vector<MachineBasicBlock::iterator>::iterator
169 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
170 MachineBasicBlock::iterator I = *i;
172 // If call frames are not being included as part of the stack frame, and
173 // the target doesn't indicate otherwise, remove the call frame pseudos
174 // here. The sub/add sp instruction pairs are still inserted, but we don't
175 // need to track the SP adjustment for frame index elimination.
176 if (RegInfo->canSimplifyCallFramePseudos(Fn))
177 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
182 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
184 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
185 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
186 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
187 MachineFrameInfo *MFI = Fn.getFrameInfo();
189 // Get the callee saved register list...
190 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
192 // These are used to keep track the callee-save area. Initialize them.
193 MinCSFrameIndex = INT_MAX;
196 // Early exit for targets which have no callee saved registers.
197 if (CSRegs == 0 || CSRegs[0] == 0)
200 // Figure out which *callee saved* registers are modified by the current
201 // function, thus needing to be saved and restored in the prolog/epilog.
202 const TargetRegisterClass * const *CSRegClasses =
203 RegInfo->getCalleeSavedRegClasses(&Fn);
205 std::vector<CalleeSavedInfo> CSI;
206 for (unsigned i = 0; CSRegs[i]; ++i) {
207 unsigned Reg = CSRegs[i];
208 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
209 // If the reg is modified, save it!
210 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
212 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
213 *AliasSet; ++AliasSet) { // Check alias registers too.
214 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
215 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
223 return; // Early exit if no callee saved registers are modified!
225 unsigned NumFixedSpillSlots;
226 const TargetFrameInfo::SpillSlot *FixedSpillSlots =
227 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
229 // Now that we know which registers need to be saved and restored, allocate
230 // stack slots for them.
231 for (std::vector<CalleeSavedInfo>::iterator
232 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
233 unsigned Reg = I->getReg();
234 const TargetRegisterClass *RC = I->getRegClass();
237 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
238 I->setFrameIdx(FrameIdx);
242 // Check to see if this physreg must be spilled to a particular stack slot
244 const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
245 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
246 FixedSlot->Reg != Reg)
249 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
250 // Nope, just spill it anywhere convenient.
251 unsigned Align = RC->getAlignment();
252 unsigned StackAlign = TFI->getStackAlignment();
254 // We may not be able to satisfy the desired alignment specification of
255 // the TargetRegisterClass if the stack alignment is smaller. Use the
257 Align = std::min(Align, StackAlign);
258 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
259 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
260 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
262 // Spill it to the stack where we must.
263 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset,
267 I->setFrameIdx(FrameIdx);
270 MFI->setCalleeSavedInfo(CSI);
273 /// insertCSRSpillsAndRestores - Insert spill and restore code for
274 /// callee saved registers used in the function, handling shrink wrapping.
276 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
277 // Get callee saved register information.
278 MachineFrameInfo *MFI = Fn.getFrameInfo();
279 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
281 MFI->setCalleeSavedInfoValid(true);
283 // Early exit if no callee saved registers are modified!
287 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
288 MachineBasicBlock::iterator I;
290 if (! ShrinkWrapThisFunction) {
291 // Spill using target interface.
292 I = EntryBlock->begin();
293 if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
294 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
295 // Add the callee-saved register as live-in.
296 // It's killed at the spill.
297 EntryBlock->addLiveIn(CSI[i].getReg());
299 // Insert the spill to the stack frame.
300 TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
301 CSI[i].getFrameIdx(), CSI[i].getRegClass());
305 // Restore using target interface.
306 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
307 MachineBasicBlock* MBB = ReturnBlocks[ri];
310 // Skip over all terminator instructions, which are part of the return
312 MachineBasicBlock::iterator I2 = I;
313 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
316 bool AtStart = I == MBB->begin();
317 MachineBasicBlock::iterator BeforeI = I;
321 // Restore all registers immediately before the return and any
322 // terminators that preceed it.
323 if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
324 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
325 TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
326 CSI[i].getFrameIdx(),
327 CSI[i].getRegClass());
328 assert(I != MBB->begin() &&
329 "loadRegFromStackSlot didn't insert any code!");
330 // Insert in reverse order. loadRegFromStackSlot can insert
331 // multiple instructions.
345 std::vector<CalleeSavedInfo> blockCSI;
346 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
347 BE = CSRSave.end(); BI != BE; ++BI) {
348 MachineBasicBlock* MBB = BI->first;
349 CSRegSet save = BI->second;
355 for (CSRegSet::iterator RI = save.begin(),
356 RE = save.end(); RI != RE; ++RI) {
357 blockCSI.push_back(CSI[*RI]);
359 assert(blockCSI.size() > 0 &&
360 "Could not collect callee saved register info");
364 // When shrink wrapping, use stack slot stores/loads.
365 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
366 // Add the callee-saved register as live-in.
367 // It's killed at the spill.
368 MBB->addLiveIn(blockCSI[i].getReg());
370 // Insert the spill to the stack frame.
371 TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
373 blockCSI[i].getFrameIdx(),
374 blockCSI[i].getRegClass());
378 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
379 BE = CSRRestore.end(); BI != BE; ++BI) {
380 MachineBasicBlock* MBB = BI->first;
381 CSRegSet restore = BI->second;
387 for (CSRegSet::iterator RI = restore.begin(),
388 RE = restore.end(); RI != RE; ++RI) {
389 blockCSI.push_back(CSI[*RI]);
391 assert(blockCSI.size() > 0 &&
392 "Could not find callee saved register info");
394 // If MBB is empty and needs restores, insert at the _beginning_.
401 // Skip over all terminator instructions, which are part of the
403 if (! I->getDesc().isTerminator()) {
406 MachineBasicBlock::iterator I2 = I;
407 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
412 bool AtStart = I == MBB->begin();
413 MachineBasicBlock::iterator BeforeI = I;
417 // Restore all registers immediately before the return and any
418 // terminators that preceed it.
419 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
420 TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
421 blockCSI[i].getFrameIdx(),
422 blockCSI[i].getRegClass());
423 assert(I != MBB->begin() &&
424 "loadRegFromStackSlot didn't insert any code!");
425 // Insert in reverse order. loadRegFromStackSlot can insert
426 // multiple instructions.
437 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
439 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
440 bool StackGrowsDown, int64_t &Offset,
441 unsigned &MaxAlign) {
442 // If the stack grows down, add the object size to find the lowest address.
444 Offset += MFI->getObjectSize(FrameIdx);
446 unsigned Align = MFI->getObjectAlignment(FrameIdx);
448 // If the alignment of this object is greater than that of the stack, then
449 // increase the stack alignment to match.
450 MaxAlign = std::max(MaxAlign, Align);
452 // Adjust to alignment boundary.
453 Offset = (Offset + Align - 1) / Align * Align;
455 if (StackGrowsDown) {
456 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
458 MFI->setObjectOffset(FrameIdx, Offset);
459 Offset += MFI->getObjectSize(FrameIdx);
463 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
464 /// abstract stack objects.
466 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
467 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
469 bool StackGrowsDown =
470 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
472 // Loop over all of the stack objects, assigning sequential addresses...
473 MachineFrameInfo *MFI = Fn.getFrameInfo();
475 // Start at the beginning of the local area.
476 // The Offset is the distance from the stack top in the direction
477 // of stack growth -- so it's always nonnegative.
478 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
480 LocalAreaOffset = -LocalAreaOffset;
481 assert(LocalAreaOffset >= 0
482 && "Local area offset should be in direction of stack growth");
483 int64_t Offset = LocalAreaOffset;
485 // If there are fixed sized objects that are preallocated in the local area,
486 // non-fixed objects can't be allocated right at the start of local area.
487 // We currently don't support filling in holes in between fixed sized
488 // objects, so we adjust 'Offset' to point to the end of last fixed sized
489 // preallocated object.
490 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
492 if (StackGrowsDown) {
493 // The maximum distance from the stack pointer is at lower address of
494 // the object -- which is given by offset. For down growing stack
495 // the offset is negative, so we negate the offset to get the distance.
496 FixedOff = -MFI->getObjectOffset(i);
498 // The maximum distance from the start pointer is at the upper
499 // address of the object.
500 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
502 if (FixedOff > Offset) Offset = FixedOff;
505 // First assign frame offsets to stack objects that are used to spill
506 // callee saved registers.
507 if (StackGrowsDown) {
508 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
509 // If stack grows down, we need to add size of find the lowest
510 // address of the object.
511 Offset += MFI->getObjectSize(i);
513 unsigned Align = MFI->getObjectAlignment(i);
514 // Adjust to alignment boundary
515 Offset = (Offset+Align-1)/Align*Align;
517 MFI->setObjectOffset(i, -Offset); // Set the computed offset
520 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
521 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
522 unsigned Align = MFI->getObjectAlignment(i);
523 // Adjust to alignment boundary
524 Offset = (Offset+Align-1)/Align*Align;
526 MFI->setObjectOffset(i, Offset);
527 Offset += MFI->getObjectSize(i);
531 unsigned MaxAlign = MFI->getMaxAlignment();
533 // Make sure the special register scavenging spill slot is closest to the
534 // frame pointer if a frame pointer is required.
535 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
536 if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
537 int SFI = RS->getScavengingFrameIndex();
539 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
542 // Make sure that the stack protector comes before the local variables on the
544 if (MFI->getStackProtectorIndex() >= 0)
545 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
548 // Then assign frame offsets to stack objects that are not used to spill
549 // callee saved registers.
550 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
551 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
553 if (RS && (int)i == RS->getScavengingFrameIndex())
555 if (MFI->isDeadObjectIndex(i))
557 if (MFI->getStackProtectorIndex() == (int)i)
560 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
563 // Make sure the special register scavenging spill slot is closest to the
565 if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
566 int SFI = RS->getScavengingFrameIndex();
568 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
571 if (!RegInfo->targetHandlesStackFrameRounding()) {
572 // If we have reserved argument space for call sites in the function
573 // immediately on entry to the current function, count it as part of the
574 // overall stack size.
575 if (MFI->hasCalls() && RegInfo->hasReservedCallFrame(Fn))
576 Offset += MFI->getMaxCallFrameSize();
578 // Round up the size to a multiple of the alignment. If the function has
579 // any calls or alloca's, align to the target's StackAlignment value to
580 // ensure that the callee's frame or the alloca data is suitably aligned;
581 // otherwise, for leaf functions, align to the TransientStackAlignment
584 if (MFI->hasCalls() || MFI->hasVarSizedObjects() ||
585 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
586 StackAlign = TFI.getStackAlignment();
588 StackAlign = TFI.getTransientStackAlignment();
589 // If the frame pointer is eliminated, all frame offsets will be relative
590 // to SP not FP; align to MaxAlign so this works.
591 StackAlign = std::max(StackAlign, MaxAlign);
592 unsigned AlignMask = StackAlign - 1;
593 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
596 // Update frame info to pretend that this is part of the stack...
597 MFI->setStackSize(Offset - LocalAreaOffset);
601 /// insertPrologEpilogCode - Scan the function for modified callee saved
602 /// registers, insert spill code for these callee saved registers, then add
603 /// prolog and epilog code to the function.
605 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
606 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
608 // Add prologue to the function...
609 TRI->emitPrologue(Fn);
611 // Add epilogue to restore the callee-save registers in each exiting block
612 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
613 // If last instruction is a return instruction, add an epilogue
614 if (!I->empty() && I->back().getDesc().isReturn())
615 TRI->emitEpilogue(Fn, *I);
620 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
621 /// register references and actual offsets.
623 void PEI::replaceFrameIndices(MachineFunction &Fn) {
624 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
626 const TargetMachine &TM = Fn.getTarget();
627 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
628 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
629 const TargetFrameInfo *TFI = TM.getFrameInfo();
630 bool StackGrowsDown =
631 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
632 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
633 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
635 for (MachineFunction::iterator BB = Fn.begin(),
636 E = Fn.end(); BB != E; ++BB) {
637 int SPAdj = 0; // SP offset due to call frame setup / destroy.
638 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
640 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
642 if (I->getOpcode() == FrameSetupOpcode ||
643 I->getOpcode() == FrameDestroyOpcode) {
644 // Remember how much SP has been adjusted to create the call
646 int Size = I->getOperand(0).getImm();
648 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
649 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
654 MachineBasicBlock::iterator PrevI = BB->end();
655 if (I != BB->begin()) PrevI = prior(I);
656 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
658 // Visit the instructions created by eliminateCallFramePseudoInstr().
659 if (PrevI == BB->end())
660 I = BB->begin(); // The replaced instr was the first in the block.
662 I = llvm::next(PrevI);
666 MachineInstr *MI = I;
668 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
669 if (MI->getOperand(i).isFI()) {
670 // Some instructions (e.g. inline asm instructions) can have
671 // multiple frame indices and/or cause eliminateFrameIndex
672 // to insert more than one instruction. We need the register
673 // scavenger to go through all of these instructions so that
674 // it can update its register information. We keep the
675 // iterator at the point before insertion so that we can
676 // revisit them in full.
677 bool AtBeginning = (I == BB->begin());
678 if (!AtBeginning) --I;
680 // If this instruction has a FrameIndex operand, we need to
681 // use that target machine register info object to eliminate
683 TargetRegisterInfo::FrameIndexValue Value;
685 TRI.eliminateFrameIndex(MI, SPAdj, &Value,
686 FrameIndexVirtualScavenging ? NULL : RS);
688 assert (FrameIndexVirtualScavenging &&
689 "Not scavenging, but virtual returned from "
690 "eliminateFrameIndex()!");
691 FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
694 // Reset the iterator if we were at the beginning of the BB.
704 if (DoIncr && I != BB->end()) ++I;
706 // Update register states.
707 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
710 assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
714 /// findLastUseReg - find the killing use of the specified register within
715 /// the instruciton range. Return the operand number of the kill in Operand.
716 static MachineBasicBlock::iterator
717 findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
719 // Scan forward to find the last use of this virtual register
720 for (++I; I != ME; ++I) {
721 MachineInstr *MI = I;
722 bool isDefInsn = false;
723 bool isKillInsn = false;
724 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
725 if (MI->getOperand(i).isReg()) {
726 unsigned OpReg = MI->getOperand(i).getReg();
727 if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
730 && "overlapping use of scavenged index register!");
731 // If this is the killing use, we have a candidate.
732 if (MI->getOperand(i).isKill())
734 else if (MI->getOperand(i).isDef())
737 if (isKillInsn && !isDefInsn)
740 // If we hit the end of the basic block, there was no kill of
741 // the virtual register, which is wrong.
742 assert (0 && "scavenged index register never killed!");
746 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
747 /// with physical registers. Use the register scavenger to find an
748 /// appropriate register to use.
749 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
750 // Run through the instructions and find any virtual registers.
751 for (MachineFunction::iterator BB = Fn.begin(),
752 E = Fn.end(); BB != E; ++BB) {
753 RS->enterBasicBlock(BB);
755 // FIXME: The logic flow in this function is still too convoluted.
756 // It needs a cleanup refactoring. Do that in preparation for tracking
757 // more than one scratch register value and using ranges to find
758 // available scratch registers.
759 unsigned CurrentVirtReg = 0;
760 unsigned CurrentScratchReg = 0;
761 bool havePrevValue = false;
762 TargetRegisterInfo::FrameIndexValue PrevValue(0,0);
763 TargetRegisterInfo::FrameIndexValue Value(0,0);
764 MachineInstr *PrevLastUseMI = NULL;
765 unsigned PrevLastUseOp = 0;
766 bool trackingCurrentValue = false;
769 // The instruction stream may change in the loop, so check BB->end()
771 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
772 MachineInstr *MI = I;
773 bool isDefInsn = false;
774 bool isKillInsn = false;
775 bool clobbersScratchReg = false;
777 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
778 if (MI->getOperand(i).isReg()) {
779 MachineOperand &MO = MI->getOperand(i);
780 unsigned Reg = MO.getReg();
783 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
784 // If we have a previous scratch reg, check and see if anything
785 // here kills whatever value is in there.
786 if (Reg == CurrentScratchReg) {
788 // Two-address operands implicitly kill
789 if (MO.isKill() || MI->isRegTiedToDefOperand(i))
790 clobbersScratchReg = true;
793 clobbersScratchReg = true;
798 // If this is a def, remember that this insn defines the value.
799 // This lets us properly consider insns which re-use the scratch
800 // register, such as r2 = sub r2, #imm, in the middle of the
805 // Have we already allocated a scratch register for this virtual?
806 if (Reg != CurrentVirtReg) {
807 // When we first encounter a new virtual register, it
808 // must be a definition.
809 assert(MI->getOperand(i).isDef() &&
810 "frame index virtual missing def!");
811 // We can't have nested virtual register live ranges because
812 // there's only a guarantee of one scavenged register at a time.
813 assert (CurrentVirtReg == 0 &&
814 "overlapping frame index virtual registers!");
816 // If the target gave us information about what's in the register,
817 // we can use that to re-use scratch regs.
818 DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
819 FrameConstantRegMap.find(Reg);
820 trackingCurrentValue = Entry != FrameConstantRegMap.end();
821 if (trackingCurrentValue) {
822 SPAdj = (*Entry).second.second;
823 Value = (*Entry).second.first;
830 // If the scratch register from the last allocation is still
831 // available, see if the value matches. If it does, just re-use it.
832 if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
833 // FIXME: This assumes that the instructions in the live range
834 // for the virtual register are exclusively for the purpose
835 // of populating the value in the register. That's reasonable
836 // for these frame index registers, but it's still a very, very
837 // strong assumption. rdar://7322732. Better would be to
838 // explicitly check each instruction in the range for references
839 // to the virtual register. Only delete those insns that
840 // touch the virtual register.
842 // Find the last use of the new virtual register. Remove all
843 // instruction between here and there, and update the current
844 // instruction to reference the last use insn instead.
845 MachineBasicBlock::iterator LastUseMI =
846 findLastUseReg(I, BB->end(), Reg);
848 // Remove all instructions up 'til the last use, since they're
849 // just calculating the value we already have.
850 BB->erase(I, LastUseMI);
853 // Extend the live range of the scratch register
854 PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
855 RS->setUsed(CurrentScratchReg);
856 CurrentVirtReg = Reg;
858 // We deleted the instruction we were scanning the operands of.
859 // Jump back to the instruction iterator loop. Don't increment
860 // past this instruction since we updated the iterator already.
865 // Scavenge a new scratch register
866 CurrentVirtReg = Reg;
867 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
868 CurrentScratchReg = RS->FindUnusedReg(RC);
869 if (CurrentScratchReg == 0)
870 // No register is "free". Scavenge a register.
871 CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
875 // replace this reference to the virtual register with the
877 assert (CurrentScratchReg && "Missing scratch register!");
878 MI->getOperand(i).setReg(CurrentScratchReg);
880 if (MI->getOperand(i).isKill()) {
887 // If this is the last use of the scratch, stop tracking it. The
888 // last use will be a kill operand in an instruction that does
889 // not also define the scratch register.
890 if (isKillInsn && !isDefInsn) {
892 havePrevValue = trackingCurrentValue;
894 // Similarly, notice if instruction clobbered the value in the
895 // register we're tracking for possible later reuse. This is noted
896 // above, but enforced here since the value is still live while we
897 // process the rest of the operands of the instruction.
898 if (clobbersScratchReg) {
899 havePrevValue = false;
900 CurrentScratchReg = 0;