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/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegisterScavenging.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetFrameInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/ADT/IndexedMap.h"
37 #include "llvm/ADT/STLExtras.h"
44 static RegisterPass<PEI>
45 X("prologepilog", "Prologue/Epilogue Insertion");
47 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
48 /// prolog and epilog code, and eliminates abstract frame references.
50 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
52 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
53 /// frame indexes with appropriate references.
55 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
56 const Function* F = Fn.getFunction();
57 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
58 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
59 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
60 FrameConstantRegMap.clear();
62 // Get MachineModuleInfo so that we can track the construction of the
64 if (MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>())
65 Fn.getFrameInfo()->setMachineModuleInfo(MMI);
67 // Calculate the MaxCallFrameSize and HasCalls variables for the function's
68 // frame information. Also eliminates call frame pseudo instructions.
69 calculateCallsInformation(Fn);
71 // Allow the target machine to make some adjustments to the function
72 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
73 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS);
75 // Scan the function for modified callee saved registers and insert spill code
76 // for any callee saved registers that are modified.
77 calculateCalleeSavedRegisters(Fn);
79 // Determine placement of CSR spill/restore code:
80 // - with shrink wrapping, place spills and restores to tightly
81 // enclose regions in the Machine CFG of the function where
82 // they are used. Without shrink wrapping
83 // - default (no shrink wrapping), place all spills in the
84 // entry block, all restores in return blocks.
85 placeCSRSpillsAndRestores(Fn);
87 // Add the code to save and restore the callee saved registers
88 if (!F->hasFnAttr(Attribute::Naked))
89 insertCSRSpillsAndRestores(Fn);
91 // Allow the target machine to make final modifications to the function
92 // before the frame layout is finalized.
93 TRI->processFunctionBeforeFrameFinalized(Fn);
95 // Calculate actual frame offsets for all abstract stack objects...
96 calculateFrameObjectOffsets(Fn);
98 // Add prolog and epilog code to the function. This function is required
99 // to align the stack frame as necessary for any stack variables or
100 // called functions. Because of this, calculateCalleeSavedRegisters
101 // must be called before this function in order to set the HasCalls
102 // and MaxCallFrameSize variables.
103 if (!F->hasFnAttr(Attribute::Naked))
104 insertPrologEpilogCode(Fn);
106 // Replace all MO_FrameIndex operands with physical register references
107 // and actual offsets.
109 replaceFrameIndices(Fn);
111 // If register scavenging is needed, as we've enabled doing it as a
112 // post-pass, scavenge the virtual registers that frame index elimiation
114 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
115 scavengeFrameVirtualRegs(Fn);
123 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
124 AU.setPreservesCFG();
125 if (ShrinkWrapping || ShrinkWrapFunc != "") {
126 AU.addRequired<MachineLoopInfo>();
127 AU.addRequired<MachineDominatorTree>();
129 AU.addPreserved<MachineLoopInfo>();
130 AU.addPreserved<MachineDominatorTree>();
131 MachineFunctionPass::getAnalysisUsage(AU);
135 /// calculateCallsInformation - Calculate the MaxCallFrameSize and HasCalls
136 /// variables for the function's frame information and eliminate call frame
137 /// pseudo instructions.
138 void PEI::calculateCallsInformation(MachineFunction &Fn) {
139 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
140 MachineFrameInfo *FFI = Fn.getFrameInfo();
142 unsigned MaxCallFrameSize = 0;
143 bool HasCalls = FFI->hasCalls();
145 // Get the function call frame set-up and tear-down instruction opcode
146 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
147 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
149 // Early exit for targets which have no call frame setup/destroy pseudo
151 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
154 std::vector<MachineBasicBlock::iterator> FrameSDOps;
155 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
156 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
157 if (I->getOpcode() == FrameSetupOpcode ||
158 I->getOpcode() == FrameDestroyOpcode) {
159 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
160 " instructions should have a single immediate argument!");
161 unsigned Size = I->getOperand(0).getImm();
162 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
164 FrameSDOps.push_back(I);
165 } else if (I->isInlineAsm()) {
166 // An InlineAsm might be a call; assume it is to get the stack frame
167 // aligned correctly for calls.
171 FFI->setHasCalls(HasCalls);
172 FFI->setMaxCallFrameSize(MaxCallFrameSize);
174 for (std::vector<MachineBasicBlock::iterator>::iterator
175 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
176 MachineBasicBlock::iterator I = *i;
178 // If call frames are not being included as part of the stack frame, and
179 // the target doesn't indicate otherwise, remove the call frame pseudos
180 // here. The sub/add sp instruction pairs are still inserted, but we don't
181 // need to track the SP adjustment for frame index elimination.
182 if (RegInfo->canSimplifyCallFramePseudos(Fn))
183 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
188 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
190 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
191 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
192 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
193 MachineFrameInfo *FFI = Fn.getFrameInfo();
195 // Get the callee saved register list...
196 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
198 // These are used to keep track the callee-save area. Initialize them.
199 MinCSFrameIndex = INT_MAX;
202 // Early exit for targets which have no callee saved registers.
203 if (CSRegs == 0 || CSRegs[0] == 0)
206 // Figure out which *callee saved* registers are modified by the current
207 // function, thus needing to be saved and restored in the prolog/epilog.
208 const TargetRegisterClass * const *CSRegClasses =
209 RegInfo->getCalleeSavedRegClasses(&Fn);
211 std::vector<CalleeSavedInfo> CSI;
212 for (unsigned i = 0; CSRegs[i]; ++i) {
213 unsigned Reg = CSRegs[i];
214 if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
215 // If the reg is modified, save it!
216 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
218 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
219 *AliasSet; ++AliasSet) { // Check alias registers too.
220 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
221 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i]));
229 return; // Early exit if no callee saved registers are modified!
231 unsigned NumFixedSpillSlots;
232 const TargetFrameInfo::SpillSlot *FixedSpillSlots =
233 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
235 // Now that we know which registers need to be saved and restored, allocate
236 // stack slots for them.
237 for (std::vector<CalleeSavedInfo>::iterator
238 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
239 unsigned Reg = I->getReg();
240 const TargetRegisterClass *RC = I->getRegClass();
243 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
244 I->setFrameIdx(FrameIdx);
248 // Check to see if this physreg must be spilled to a particular stack slot
250 const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots;
251 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
252 FixedSlot->Reg != Reg)
255 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
256 // Nope, just spill it anywhere convenient.
257 unsigned Align = RC->getAlignment();
258 unsigned StackAlign = TFI->getStackAlignment();
260 // We may not be able to satisfy the desired alignment specification of
261 // the TargetRegisterClass if the stack alignment is smaller. Use the
263 Align = std::min(Align, StackAlign);
264 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align, true);
265 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
266 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
268 // Spill it to the stack where we must.
269 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset,
273 I->setFrameIdx(FrameIdx);
276 FFI->setCalleeSavedInfo(CSI);
279 /// insertCSRSpillsAndRestores - Insert spill and restore code for
280 /// callee saved registers used in the function, handling shrink wrapping.
282 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
283 // Get callee saved register information.
284 MachineFrameInfo *FFI = Fn.getFrameInfo();
285 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
287 FFI->setCalleeSavedInfoValid(true);
289 // Early exit if no callee saved registers are modified!
293 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
294 MachineBasicBlock::iterator I;
296 if (! ShrinkWrapThisFunction) {
297 // Spill using target interface.
298 I = EntryBlock->begin();
299 if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) {
300 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
301 // Add the callee-saved register as live-in.
302 // It's killed at the spill.
303 EntryBlock->addLiveIn(CSI[i].getReg());
305 // Insert the spill to the stack frame.
306 TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true,
307 CSI[i].getFrameIdx(), CSI[i].getRegClass());
311 // Restore using target interface.
312 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
313 MachineBasicBlock* MBB = ReturnBlocks[ri];
316 // Skip over all terminator instructions, which are part of the return
318 MachineBasicBlock::iterator I2 = I;
319 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
322 bool AtStart = I == MBB->begin();
323 MachineBasicBlock::iterator BeforeI = I;
327 // Restore all registers immediately before the return and any
328 // terminators that preceed it.
329 if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) {
330 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
331 TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(),
332 CSI[i].getFrameIdx(),
333 CSI[i].getRegClass());
334 assert(I != MBB->begin() &&
335 "loadRegFromStackSlot didn't insert any code!");
336 // Insert in reverse order. loadRegFromStackSlot can insert
337 // multiple instructions.
351 std::vector<CalleeSavedInfo> blockCSI;
352 for (CSRegBlockMap::iterator BI = CSRSave.begin(),
353 BE = CSRSave.end(); BI != BE; ++BI) {
354 MachineBasicBlock* MBB = BI->first;
355 CSRegSet save = BI->second;
361 for (CSRegSet::iterator RI = save.begin(),
362 RE = save.end(); RI != RE; ++RI) {
363 blockCSI.push_back(CSI[*RI]);
365 assert(blockCSI.size() > 0 &&
366 "Could not collect callee saved register info");
370 // When shrink wrapping, use stack slot stores/loads.
371 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
372 // Add the callee-saved register as live-in.
373 // It's killed at the spill.
374 MBB->addLiveIn(blockCSI[i].getReg());
376 // Insert the spill to the stack frame.
377 TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(),
379 blockCSI[i].getFrameIdx(),
380 blockCSI[i].getRegClass());
384 for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
385 BE = CSRRestore.end(); BI != BE; ++BI) {
386 MachineBasicBlock* MBB = BI->first;
387 CSRegSet restore = BI->second;
393 for (CSRegSet::iterator RI = restore.begin(),
394 RE = restore.end(); RI != RE; ++RI) {
395 blockCSI.push_back(CSI[*RI]);
397 assert(blockCSI.size() > 0 &&
398 "Could not find callee saved register info");
400 // If MBB is empty and needs restores, insert at the _beginning_.
407 // Skip over all terminator instructions, which are part of the
409 if (! I->getDesc().isTerminator()) {
412 MachineBasicBlock::iterator I2 = I;
413 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator())
418 bool AtStart = I == MBB->begin();
419 MachineBasicBlock::iterator BeforeI = I;
423 // Restore all registers immediately before the return and any
424 // terminators that preceed it.
425 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
426 TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(),
427 blockCSI[i].getFrameIdx(),
428 blockCSI[i].getRegClass());
429 assert(I != MBB->begin() &&
430 "loadRegFromStackSlot didn't insert any code!");
431 // Insert in reverse order. loadRegFromStackSlot can insert
432 // multiple instructions.
443 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
445 AdjustStackOffset(MachineFrameInfo *FFI, int FrameIdx,
446 bool StackGrowsDown, int64_t &Offset,
447 unsigned &MaxAlign) {
448 // If the stack grows down, add the object size to find the lowest address.
450 Offset += FFI->getObjectSize(FrameIdx);
452 unsigned Align = FFI->getObjectAlignment(FrameIdx);
454 // If the alignment of this object is greater than that of the stack, then
455 // increase the stack alignment to match.
456 MaxAlign = std::max(MaxAlign, Align);
458 // Adjust to alignment boundary.
459 Offset = (Offset + Align - 1) / Align * Align;
461 if (StackGrowsDown) {
462 FFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
464 FFI->setObjectOffset(FrameIdx, Offset);
465 Offset += FFI->getObjectSize(FrameIdx);
469 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
470 /// abstract stack objects.
472 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
473 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
475 bool StackGrowsDown =
476 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
478 // Loop over all of the stack objects, assigning sequential addresses...
479 MachineFrameInfo *FFI = Fn.getFrameInfo();
481 // Start at the beginning of the local area.
482 // The Offset is the distance from the stack top in the direction
483 // of stack growth -- so it's always nonnegative.
484 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
486 LocalAreaOffset = -LocalAreaOffset;
487 assert(LocalAreaOffset >= 0
488 && "Local area offset should be in direction of stack growth");
489 int64_t Offset = LocalAreaOffset;
491 // If there are fixed sized objects that are preallocated in the local area,
492 // non-fixed objects can't be allocated right at the start of local area.
493 // We currently don't support filling in holes in between fixed sized
494 // objects, so we adjust 'Offset' to point to the end of last fixed sized
495 // preallocated object.
496 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
498 if (StackGrowsDown) {
499 // The maximum distance from the stack pointer is at lower address of
500 // the object -- which is given by offset. For down growing stack
501 // the offset is negative, so we negate the offset to get the distance.
502 FixedOff = -FFI->getObjectOffset(i);
504 // The maximum distance from the start pointer is at the upper
505 // address of the object.
506 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
508 if (FixedOff > Offset) Offset = FixedOff;
511 // First assign frame offsets to stack objects that are used to spill
512 // callee saved registers.
513 if (StackGrowsDown) {
514 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
515 // If stack grows down, we need to add size of find the lowest
516 // address of the object.
517 Offset += FFI->getObjectSize(i);
519 unsigned Align = FFI->getObjectAlignment(i);
520 // Adjust to alignment boundary
521 Offset = (Offset+Align-1)/Align*Align;
523 FFI->setObjectOffset(i, -Offset); // Set the computed offset
526 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
527 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
528 unsigned Align = FFI->getObjectAlignment(i);
529 // Adjust to alignment boundary
530 Offset = (Offset+Align-1)/Align*Align;
532 FFI->setObjectOffset(i, Offset);
533 Offset += FFI->getObjectSize(i);
537 unsigned MaxAlign = FFI->getMaxAlignment();
539 // Make sure the special register scavenging spill slot is closest to the
540 // frame pointer if a frame pointer is required.
541 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
542 if (RS && RegInfo->hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) {
543 int SFI = RS->getScavengingFrameIndex();
545 AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
548 // Make sure that the stack protector comes before the local variables on the
550 if (FFI->getStackProtectorIndex() >= 0)
551 AdjustStackOffset(FFI, FFI->getStackProtectorIndex(), StackGrowsDown,
554 // Then assign frame offsets to stack objects that are not used to spill
555 // callee saved registers.
556 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
557 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
559 if (RS && (int)i == RS->getScavengingFrameIndex())
561 if (FFI->isDeadObjectIndex(i))
563 if (FFI->getStackProtectorIndex() == (int)i)
566 AdjustStackOffset(FFI, i, StackGrowsDown, Offset, MaxAlign);
569 // Make sure the special register scavenging spill slot is closest to the
571 if (RS && (!RegInfo->hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) {
572 int SFI = RS->getScavengingFrameIndex();
574 AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign);
577 if (!RegInfo->targetHandlesStackFrameRounding()) {
578 // If we have reserved argument space for call sites in the function
579 // immediately on entry to the current function, count it as part of the
580 // overall stack size.
581 if (FFI->hasCalls() && RegInfo->hasReservedCallFrame(Fn))
582 Offset += FFI->getMaxCallFrameSize();
584 // Round up the size to a multiple of the alignment. If the function has
585 // any calls or alloca's, align to the target's StackAlignment value to
586 // ensure that the callee's frame or the alloca data is suitably aligned;
587 // otherwise, for leaf functions, align to the TransientStackAlignment
590 if (FFI->hasCalls() || FFI->hasVarSizedObjects() ||
591 (RegInfo->needsStackRealignment(Fn) && FFI->getObjectIndexEnd() != 0))
592 StackAlign = TFI.getStackAlignment();
594 StackAlign = TFI.getTransientStackAlignment();
595 // If the frame pointer is eliminated, all frame offsets will be relative
596 // to SP not FP; align to MaxAlign so this works.
597 StackAlign = std::max(StackAlign, MaxAlign);
598 unsigned AlignMask = StackAlign - 1;
599 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
602 // Update frame info to pretend that this is part of the stack...
603 FFI->setStackSize(Offset - LocalAreaOffset);
607 /// insertPrologEpilogCode - Scan the function for modified callee saved
608 /// registers, insert spill code for these callee saved registers, then add
609 /// prolog and epilog code to the function.
611 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
612 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
614 // Add prologue to the function...
615 TRI->emitPrologue(Fn);
617 // Add epilogue to restore the callee-save registers in each exiting block
618 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
619 // If last instruction is a return instruction, add an epilogue
620 if (!I->empty() && I->back().getDesc().isReturn())
621 TRI->emitEpilogue(Fn, *I);
626 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
627 /// register references and actual offsets.
629 void PEI::replaceFrameIndices(MachineFunction &Fn) {
630 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
632 const TargetMachine &TM = Fn.getTarget();
633 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
634 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
635 const TargetFrameInfo *TFI = TM.getFrameInfo();
636 bool StackGrowsDown =
637 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
638 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode();
639 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode();
641 for (MachineFunction::iterator BB = Fn.begin(),
642 E = Fn.end(); BB != E; ++BB) {
643 int SPAdj = 0; // SP offset due to call frame setup / destroy.
644 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
646 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
648 if (I->getOpcode() == FrameSetupOpcode ||
649 I->getOpcode() == FrameDestroyOpcode) {
650 // Remember how much SP has been adjusted to create the call
652 int Size = I->getOperand(0).getImm();
654 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
655 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
660 MachineBasicBlock::iterator PrevI = BB->end();
661 if (I != BB->begin()) PrevI = prior(I);
662 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
664 // Visit the instructions created by eliminateCallFramePseudoInstr().
665 if (PrevI == BB->end())
666 I = BB->begin(); // The replaced instr was the first in the block.
668 I = llvm::next(PrevI);
672 MachineInstr *MI = I;
674 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
675 if (MI->getOperand(i).isFI()) {
676 // Some instructions (e.g. inline asm instructions) can have
677 // multiple frame indices and/or cause eliminateFrameIndex
678 // to insert more than one instruction. We need the register
679 // scavenger to go through all of these instructions so that
680 // it can update its register information. We keep the
681 // iterator at the point before insertion so that we can
682 // revisit them in full.
683 bool AtBeginning = (I == BB->begin());
684 if (!AtBeginning) --I;
686 // If this instruction has a FrameIndex operand, we need to
687 // use that target machine register info object to eliminate
689 TargetRegisterInfo::FrameIndexValue Value;
691 TRI.eliminateFrameIndex(MI, SPAdj, &Value,
692 FrameIndexVirtualScavenging ? NULL : RS);
694 assert (FrameIndexVirtualScavenging &&
695 "Not scavenging, but virtual returned from "
696 "eliminateFrameIndex()!");
697 FrameConstantRegMap[VReg] = FrameConstantEntry(Value, SPAdj);
700 // Reset the iterator if we were at the beginning of the BB.
710 if (DoIncr && I != BB->end()) ++I;
712 // Update register states.
713 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
716 assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?");
720 /// findLastUseReg - find the killing use of the specified register within
721 /// the instruciton range. Return the operand number of the kill in Operand.
722 static MachineBasicBlock::iterator
723 findLastUseReg(MachineBasicBlock::iterator I, MachineBasicBlock::iterator ME,
725 // Scan forward to find the last use of this virtual register
726 for (++I; I != ME; ++I) {
727 MachineInstr *MI = I;
728 bool isDefInsn = false;
729 bool isKillInsn = false;
730 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
731 if (MI->getOperand(i).isReg()) {
732 unsigned OpReg = MI->getOperand(i).getReg();
733 if (OpReg == 0 || !TargetRegisterInfo::isVirtualRegister(OpReg))
736 && "overlapping use of scavenged index register!");
737 // If this is the killing use, we have a candidate.
738 if (MI->getOperand(i).isKill())
740 else if (MI->getOperand(i).isDef())
743 if (isKillInsn && !isDefInsn)
746 // If we hit the end of the basic block, there was no kill of
747 // the virtual register, which is wrong.
748 assert (0 && "scavenged index register never killed!");
752 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
753 /// with physical registers. Use the register scavenger to find an
754 /// appropriate register to use.
755 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
756 // Run through the instructions and find any virtual registers.
757 for (MachineFunction::iterator BB = Fn.begin(),
758 E = Fn.end(); BB != E; ++BB) {
759 RS->enterBasicBlock(BB);
761 // FIXME: The logic flow in this function is still too convoluted.
762 // It needs a cleanup refactoring. Do that in preparation for tracking
763 // more than one scratch register value and using ranges to find
764 // available scratch registers.
765 unsigned CurrentVirtReg = 0;
766 unsigned CurrentScratchReg = 0;
767 bool havePrevValue = false;
768 TargetRegisterInfo::FrameIndexValue PrevValue(0,0);
769 TargetRegisterInfo::FrameIndexValue Value(0,0);
770 MachineInstr *PrevLastUseMI = NULL;
771 unsigned PrevLastUseOp = 0;
772 bool trackingCurrentValue = false;
775 // The instruction stream may change in the loop, so check BB->end()
777 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
778 MachineInstr *MI = I;
779 bool isDefInsn = false;
780 bool isKillInsn = false;
781 bool clobbersScratchReg = false;
783 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
784 if (MI->getOperand(i).isReg()) {
785 MachineOperand &MO = MI->getOperand(i);
786 unsigned Reg = MO.getReg();
789 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
790 // If we have a previous scratch reg, check and see if anything
791 // here kills whatever value is in there.
792 if (Reg == CurrentScratchReg) {
794 // Two-address operands implicitly kill
795 if (MO.isKill() || MI->isRegTiedToDefOperand(i))
796 clobbersScratchReg = true;
799 clobbersScratchReg = true;
804 // If this is a def, remember that this insn defines the value.
805 // This lets us properly consider insns which re-use the scratch
806 // register, such as r2 = sub r2, #imm, in the middle of the
811 // Have we already allocated a scratch register for this virtual?
812 if (Reg != CurrentVirtReg) {
813 // When we first encounter a new virtual register, it
814 // must be a definition.
815 assert(MI->getOperand(i).isDef() &&
816 "frame index virtual missing def!");
817 // We can't have nested virtual register live ranges because
818 // there's only a guarantee of one scavenged register at a time.
819 assert (CurrentVirtReg == 0 &&
820 "overlapping frame index virtual registers!");
822 // If the target gave us information about what's in the register,
823 // we can use that to re-use scratch regs.
824 DenseMap<unsigned, FrameConstantEntry>::iterator Entry =
825 FrameConstantRegMap.find(Reg);
826 trackingCurrentValue = Entry != FrameConstantRegMap.end();
827 if (trackingCurrentValue) {
828 SPAdj = (*Entry).second.second;
829 Value = (*Entry).second.first;
836 // If the scratch register from the last allocation is still
837 // available, see if the value matches. If it does, just re-use it.
838 if (trackingCurrentValue && havePrevValue && PrevValue == Value) {
839 // FIXME: This assumes that the instructions in the live range
840 // for the virtual register are exclusively for the purpose
841 // of populating the value in the register. That's reasonable
842 // for these frame index registers, but it's still a very, very
843 // strong assumption. rdar://7322732. Better would be to
844 // explicitly check each instruction in the range for references
845 // to the virtual register. Only delete those insns that
846 // touch the virtual register.
848 // Find the last use of the new virtual register. Remove all
849 // instruction between here and there, and update the current
850 // instruction to reference the last use insn instead.
851 MachineBasicBlock::iterator LastUseMI =
852 findLastUseReg(I, BB->end(), Reg);
854 // Remove all instructions up 'til the last use, since they're
855 // just calculating the value we already have.
856 BB->erase(I, LastUseMI);
859 // Extend the live range of the scratch register
860 PrevLastUseMI->getOperand(PrevLastUseOp).setIsKill(false);
861 RS->setUsed(CurrentScratchReg);
862 CurrentVirtReg = Reg;
864 // We deleted the instruction we were scanning the operands of.
865 // Jump back to the instruction iterator loop. Don't increment
866 // past this instruction since we updated the iterator already.
871 // Scavenge a new scratch register
872 CurrentVirtReg = Reg;
873 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
874 CurrentScratchReg = RS->FindUnusedReg(RC);
875 if (CurrentScratchReg == 0)
876 // No register is "free". Scavenge a register.
877 CurrentScratchReg = RS->scavengeRegister(RC, I, SPAdj);
881 // replace this reference to the virtual register with the
883 assert (CurrentScratchReg && "Missing scratch register!");
884 MI->getOperand(i).setReg(CurrentScratchReg);
886 if (MI->getOperand(i).isKill()) {
893 // If this is the last use of the scratch, stop tracking it. The
894 // last use will be a kill operand in an instruction that does
895 // not also define the scratch register.
896 if (isKillInsn && !isDefInsn) {
898 havePrevValue = trackingCurrentValue;
900 // Similarly, notice if instruction clobbered the value in the
901 // register we're tracking for possible later reuse. This is noted
902 // above, but enforced here since the value is still live while we
903 // process the rest of the operands of the instruction.
904 if (clobbersScratchReg) {
905 havePrevValue = false;
906 CurrentScratchReg = 0;