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 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/IndexedMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/CodeGen/StackProtector.h"
33 #include "llvm/CodeGen/WinEHFuncInfo.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetFrameLowering.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
50 #define DEBUG_TYPE "pei"
53 class PEI : public MachineFunctionPass {
56 PEI() : MachineFunctionPass(ID) {
57 initializePEIPass(*PassRegistry::getPassRegistry());
60 void getAnalysisUsage(AnalysisUsage &AU) const override;
62 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
63 /// frame indexes with appropriate references.
65 bool runOnMachineFunction(MachineFunction &Fn) override;
70 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
71 // stack frame indexes.
72 unsigned MinCSFrameIndex, MaxCSFrameIndex;
74 // Save and Restore blocks of the current function.
75 MachineBasicBlock *SaveBlock;
76 SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
78 // Flag to control whether to use the register scavenger to resolve
79 // frame index materialization registers. Set according to
80 // TRI->requiresFrameIndexScavenging() for the current function.
81 bool FrameIndexVirtualScavenging;
83 void calculateSets(MachineFunction &Fn);
84 void calculateCallsInformation(MachineFunction &Fn);
85 void calculateCalleeSavedRegisters(MachineFunction &Fn);
86 void insertCSRSpillsAndRestores(MachineFunction &Fn);
87 void calculateFrameObjectOffsets(MachineFunction &Fn);
88 void replaceFrameIndices(MachineFunction &Fn);
89 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
91 void scavengeFrameVirtualRegs(MachineFunction &Fn);
92 void insertPrologEpilogCode(MachineFunction &Fn);
94 // Convenience for recognizing return blocks.
95 bool isReturnBlock(MachineBasicBlock *MBB);
100 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
102 static cl::opt<unsigned>
103 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
104 cl::desc("Warn for stack size bigger than the given"
107 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
108 "Prologue/Epilogue Insertion", false, false)
109 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
110 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
111 INITIALIZE_PASS_DEPENDENCY(StackProtector)
112 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
113 INITIALIZE_PASS_END(PEI, "prologepilog",
114 "Prologue/Epilogue Insertion & Frame Finalization",
117 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
118 STATISTIC(NumBytesStackSpace,
119 "Number of bytes used for stack in all functions");
121 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.setPreservesCFG();
123 AU.addPreserved<MachineLoopInfo>();
124 AU.addPreserved<MachineDominatorTree>();
125 AU.addRequired<StackProtector>();
126 AU.addRequired<TargetPassConfig>();
127 MachineFunctionPass::getAnalysisUsage(AU);
130 bool PEI::isReturnBlock(MachineBasicBlock* MBB) {
131 return (MBB && !MBB->empty() && MBB->back().isReturn());
134 /// Compute the set of return blocks
135 void PEI::calculateSets(MachineFunction &Fn) {
136 const MachineFrameInfo *MFI = Fn.getFrameInfo();
138 // Even when we do not change any CSR, we still want to insert the
139 // prologue and epilogue of the function.
140 // So set the save points for those.
142 // Use the points found by shrink-wrapping, if any.
143 if (MFI->getSavePoint()) {
144 SaveBlock = MFI->getSavePoint();
145 assert(MFI->getRestorePoint() && "Both restore and save must be set");
146 RestoreBlocks.push_back(MFI->getRestorePoint());
150 // Save refs to entry and return blocks.
151 SaveBlock = Fn.begin();
152 for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
154 if (isReturnBlock(MBB))
155 RestoreBlocks.push_back(MBB);
160 /// StackObjSet - A set of stack object indexes
161 typedef SmallSetVector<int, 8> StackObjSet;
163 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
164 /// frame indexes with appropriate references.
166 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
167 const Function* F = Fn.getFunction();
168 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
169 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
171 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
173 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
174 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
176 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
177 // function's frame information. Also eliminates call frame pseudo
179 calculateCallsInformation(Fn);
181 // Allow the target machine to make some adjustments to the function
182 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
183 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
185 // Scan the function for modified callee saved registers and insert spill code
186 // for any callee saved registers that are modified.
187 calculateCalleeSavedRegisters(Fn);
189 // Determine placement of CSR spill/restore code:
190 // place all spills in the entry block, all restores in return blocks.
193 // Add the code to save and restore the callee saved registers
194 if (!F->hasFnAttribute(Attribute::Naked))
195 insertCSRSpillsAndRestores(Fn);
197 // Allow the target machine to make final modifications to the function
198 // before the frame layout is finalized.
199 TFI->processFunctionBeforeFrameFinalized(Fn, RS);
201 // Calculate actual frame offsets for all abstract stack objects...
202 calculateFrameObjectOffsets(Fn);
204 // Add prolog and epilog code to the function. This function is required
205 // to align the stack frame as necessary for any stack variables or
206 // called functions. Because of this, calculateCalleeSavedRegisters()
207 // must be called before this function in order to set the AdjustsStack
208 // and MaxCallFrameSize variables.
209 if (!F->hasFnAttribute(Attribute::Naked))
210 insertPrologEpilogCode(Fn);
212 // Replace all MO_FrameIndex operands with physical register references
213 // and actual offsets.
215 replaceFrameIndices(Fn);
217 // If register scavenging is needed, as we've enabled doing it as a
218 // post-pass, scavenge the virtual registers that frame index elimination
220 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
221 scavengeFrameVirtualRegs(Fn);
223 // Clear any vregs created by virtual scavenging.
224 Fn.getRegInfo().clearVirtRegs();
226 // Warn on stack size when we exceeds the given limit.
227 MachineFrameInfo *MFI = Fn.getFrameInfo();
228 uint64_t StackSize = MFI->getStackSize();
229 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
230 DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
231 F->getContext().diagnose(DiagStackSize);
235 RestoreBlocks.clear();
239 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
240 /// variables for the function's frame information and eliminate call frame
241 /// pseudo instructions.
242 void PEI::calculateCallsInformation(MachineFunction &Fn) {
243 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
244 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
245 MachineFrameInfo *MFI = Fn.getFrameInfo();
247 unsigned MaxCallFrameSize = 0;
248 bool AdjustsStack = MFI->adjustsStack();
250 // Get the function call frame set-up and tear-down instruction opcode
251 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
252 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
254 // Early exit for targets which have no call frame setup/destroy pseudo
256 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
259 std::vector<MachineBasicBlock::iterator> FrameSDOps;
260 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
261 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
262 if (I->getOpcode() == FrameSetupOpcode ||
263 I->getOpcode() == FrameDestroyOpcode) {
264 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
265 " instructions should have a single immediate argument!");
266 unsigned Size = I->getOperand(0).getImm();
267 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
269 FrameSDOps.push_back(I);
270 } else if (I->isInlineAsm()) {
271 // Some inline asm's need a stack frame, as indicated by operand 1.
272 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
273 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
277 MFI->setAdjustsStack(AdjustsStack);
278 MFI->setMaxCallFrameSize(MaxCallFrameSize);
280 for (std::vector<MachineBasicBlock::iterator>::iterator
281 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
282 MachineBasicBlock::iterator I = *i;
284 // If call frames are not being included as part of the stack frame, and
285 // the target doesn't indicate otherwise, remove the call frame pseudos
286 // here. The sub/add sp instruction pairs are still inserted, but we don't
287 // need to track the SP adjustment for frame index elimination.
288 if (TFI->canSimplifyCallFramePseudos(Fn))
289 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
294 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
296 void PEI::calculateCalleeSavedRegisters(MachineFunction &F) {
297 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
298 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
299 MachineFrameInfo *MFI = F.getFrameInfo();
301 // Get the callee saved register list...
302 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
304 // These are used to keep track the callee-save area. Initialize them.
305 MinCSFrameIndex = INT_MAX;
308 // Early exit for targets which have no callee saved registers.
309 if (!CSRegs || CSRegs[0] == 0)
312 // In Naked functions we aren't going to save any registers.
313 if (F.getFunction()->hasFnAttribute(Attribute::Naked))
316 std::vector<CalleeSavedInfo> CSI;
317 for (unsigned i = 0; CSRegs[i]; ++i) {
318 unsigned Reg = CSRegs[i];
319 // Functions which call __builtin_unwind_init get all their registers saved.
320 if (F.getRegInfo().isPhysRegUsed(Reg) || F.getMMI().callsUnwindInit()) {
321 // If the reg is modified, save it!
322 CSI.push_back(CalleeSavedInfo(Reg));
326 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
327 // If target doesn't implement this, use generic code.
330 return; // Early exit if no callee saved registers are modified!
332 unsigned NumFixedSpillSlots;
333 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
334 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
336 // Now that we know which registers need to be saved and restored, allocate
337 // stack slots for them.
338 for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
340 unsigned Reg = I->getReg();
341 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
344 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
345 I->setFrameIdx(FrameIdx);
349 // Check to see if this physreg must be spilled to a particular stack slot
351 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
352 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
353 FixedSlot->Reg != Reg)
356 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
357 // Nope, just spill it anywhere convenient.
358 unsigned Align = RC->getAlignment();
359 unsigned StackAlign = TFI->getStackAlignment();
361 // We may not be able to satisfy the desired alignment specification of
362 // the TargetRegisterClass if the stack alignment is smaller. Use the
364 Align = std::min(Align, StackAlign);
365 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
366 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
367 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
369 // Spill it to the stack where we must.
371 MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
374 I->setFrameIdx(FrameIdx);
378 MFI->setCalleeSavedInfo(CSI);
381 /// Helper function to update the liveness information for the callee-saved
383 static void updateLiveness(MachineFunction &MF) {
384 MachineFrameInfo *MFI = MF.getFrameInfo();
385 // Visited will contain all the basic blocks that are in the region
386 // where the callee saved registers are alive:
387 // - Anything that is not Save or Restore -> LiveThrough.
389 // - Restore -> LiveOut.
390 // The live-out is not attached to the block, so no need to keep
391 // Restore in this set.
392 SmallPtrSet<MachineBasicBlock *, 8> Visited;
393 SmallVector<MachineBasicBlock *, 8> WorkList;
394 MachineBasicBlock *Entry = &MF.front();
395 MachineBasicBlock *Save = MFI->getSavePoint();
401 WorkList.push_back(Entry);
402 Visited.insert(Entry);
404 Visited.insert(Save);
406 MachineBasicBlock *Restore = MFI->getRestorePoint();
408 // By construction Restore cannot be visited, otherwise it
409 // means there exists a path to Restore that does not go
411 WorkList.push_back(Restore);
413 while (!WorkList.empty()) {
414 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
415 // By construction, the region that is after the save point is
416 // dominated by the Save and post-dominated by the Restore.
419 // Enqueue all the successors not already visited.
420 // Those are by construction either before Save or after Restore.
421 for (MachineBasicBlock *SuccBB : CurBB->successors())
422 if (Visited.insert(SuccBB).second)
423 WorkList.push_back(SuccBB);
426 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
428 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
429 for (MachineBasicBlock *MBB : Visited)
430 // Add the callee-saved register as live-in.
431 // It's killed at the spill.
432 MBB->addLiveIn(CSI[i].getReg());
436 /// insertCSRSpillsAndRestores - Insert spill and restore code for
437 /// callee saved registers used in the function.
439 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
440 // Get callee saved register information.
441 MachineFrameInfo *MFI = Fn.getFrameInfo();
442 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
444 MFI->setCalleeSavedInfoValid(true);
446 // Early exit if no callee saved registers are modified!
450 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
451 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
452 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
453 MachineBasicBlock::iterator I;
455 // Spill using target interface.
456 I = SaveBlock->begin();
457 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
458 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
459 // Insert the spill to the stack frame.
460 unsigned Reg = CSI[i].getReg();
461 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
462 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
466 // Update the live-in information of all the blocks up to the save point.
469 // Restore using target interface.
470 for (MachineBasicBlock *MBB : RestoreBlocks) {
473 // Skip over all terminator instructions, which are part of the return
475 MachineBasicBlock::iterator I2 = I;
476 while (I2 != MBB->begin() && (--I2)->isTerminator())
479 bool AtStart = I == MBB->begin();
480 MachineBasicBlock::iterator BeforeI = I;
484 // Restore all registers immediately before the return and any
485 // terminators that precede it.
486 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
487 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
488 unsigned Reg = CSI[i].getReg();
489 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
490 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
491 assert(I != MBB->begin() &&
492 "loadRegFromStackSlot didn't insert any code!");
493 // Insert in reverse order. loadRegFromStackSlot can insert
494 // multiple instructions.
506 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
508 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
509 bool StackGrowsDown, int64_t &Offset,
510 unsigned &MaxAlign) {
511 // If the stack grows down, add the object size to find the lowest address.
513 Offset += MFI->getObjectSize(FrameIdx);
515 unsigned Align = MFI->getObjectAlignment(FrameIdx);
517 // If the alignment of this object is greater than that of the stack, then
518 // increase the stack alignment to match.
519 MaxAlign = std::max(MaxAlign, Align);
521 // Adjust to alignment boundary.
522 Offset = (Offset + Align - 1) / Align * Align;
524 if (StackGrowsDown) {
525 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
526 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
528 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
529 MFI->setObjectOffset(FrameIdx, Offset);
530 Offset += MFI->getObjectSize(FrameIdx);
534 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
535 /// those required to be close to the Stack Protector) to stack offsets.
537 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
538 SmallSet<int, 16> &ProtectedObjs,
539 MachineFrameInfo *MFI, bool StackGrowsDown,
540 int64_t &Offset, unsigned &MaxAlign) {
542 for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
543 E = UnassignedObjs.end(); I != E; ++I) {
545 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
546 ProtectedObjs.insert(i);
550 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
551 /// abstract stack objects.
553 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
554 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
555 StackProtector *SP = &getAnalysis<StackProtector>();
557 bool StackGrowsDown =
558 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
560 // Loop over all of the stack objects, assigning sequential addresses...
561 MachineFrameInfo *MFI = Fn.getFrameInfo();
563 // Start at the beginning of the local area.
564 // The Offset is the distance from the stack top in the direction
565 // of stack growth -- so it's always nonnegative.
566 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
568 LocalAreaOffset = -LocalAreaOffset;
569 assert(LocalAreaOffset >= 0
570 && "Local area offset should be in direction of stack growth");
571 int64_t Offset = LocalAreaOffset;
573 // If there are fixed sized objects that are preallocated in the local area,
574 // non-fixed objects can't be allocated right at the start of local area.
575 // We currently don't support filling in holes in between fixed sized
576 // objects, so we adjust 'Offset' to point to the end of last fixed sized
577 // preallocated object.
578 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
580 if (StackGrowsDown) {
581 // The maximum distance from the stack pointer is at lower address of
582 // the object -- which is given by offset. For down growing stack
583 // the offset is negative, so we negate the offset to get the distance.
584 FixedOff = -MFI->getObjectOffset(i);
586 // The maximum distance from the start pointer is at the upper
587 // address of the object.
588 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
590 if (FixedOff > Offset) Offset = FixedOff;
593 // First assign frame offsets to stack objects that are used to spill
594 // callee saved registers.
595 if (StackGrowsDown) {
596 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
597 // If the stack grows down, we need to add the size to find the lowest
598 // address of the object.
599 Offset += MFI->getObjectSize(i);
601 unsigned Align = MFI->getObjectAlignment(i);
602 // Adjust to alignment boundary
603 Offset = RoundUpToAlignment(Offset, Align);
605 MFI->setObjectOffset(i, -Offset); // Set the computed offset
608 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
609 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
610 unsigned Align = MFI->getObjectAlignment(i);
611 // Adjust to alignment boundary
612 Offset = RoundUpToAlignment(Offset, Align);
614 MFI->setObjectOffset(i, Offset);
615 Offset += MFI->getObjectSize(i);
619 unsigned MaxAlign = MFI->getMaxAlignment();
621 // Make sure the special register scavenging spill slot is closest to the
622 // incoming stack pointer if a frame pointer is required and is closer
623 // to the incoming rather than the final stack pointer.
624 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
625 bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
626 TFI.isFPCloseToIncomingSP() &&
627 RegInfo->useFPForScavengingIndex(Fn) &&
628 !RegInfo->needsStackRealignment(Fn));
629 if (RS && EarlyScavengingSlots) {
630 SmallVector<int, 2> SFIs;
631 RS->getScavengingFrameIndices(SFIs);
632 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
633 IE = SFIs.end(); I != IE; ++I)
634 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
637 // FIXME: Once this is working, then enable flag will change to a target
638 // check for whether the frame is large enough to want to use virtual
639 // frame index registers. Functions which don't want/need this optimization
640 // will continue to use the existing code path.
641 if (MFI->getUseLocalStackAllocationBlock()) {
642 unsigned Align = MFI->getLocalFrameMaxAlign();
644 // Adjust to alignment boundary.
645 Offset = RoundUpToAlignment(Offset, Align);
647 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
649 // Resolve offsets for objects in the local block.
650 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
651 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
652 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
653 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
655 MFI->setObjectOffset(Entry.first, FIOffset);
657 // Allocate the local block
658 Offset += MFI->getLocalFrameSize();
660 MaxAlign = std::max(Align, MaxAlign);
663 // Make sure that the stack protector comes before the local variables on the
665 SmallSet<int, 16> ProtectedObjs;
666 if (MFI->getStackProtectorIndex() >= 0) {
667 StackObjSet LargeArrayObjs;
668 StackObjSet SmallArrayObjs;
669 StackObjSet AddrOfObjs;
671 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
674 // Assign large stack objects first.
675 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
676 if (MFI->isObjectPreAllocated(i) &&
677 MFI->getUseLocalStackAllocationBlock())
679 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
681 if (RS && RS->isScavengingFrameIndex((int)i))
683 if (MFI->isDeadObjectIndex(i))
685 if (MFI->getStackProtectorIndex() == (int)i)
688 switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
689 case StackProtector::SSPLK_None:
691 case StackProtector::SSPLK_SmallArray:
692 SmallArrayObjs.insert(i);
694 case StackProtector::SSPLK_AddrOf:
695 AddrOfObjs.insert(i);
697 case StackProtector::SSPLK_LargeArray:
698 LargeArrayObjs.insert(i);
701 llvm_unreachable("Unexpected SSPLayoutKind.");
704 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
706 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
708 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
712 // Then assign frame offsets to stack objects that are not used to spill
713 // callee saved registers.
714 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
715 if (MFI->isObjectPreAllocated(i) &&
716 MFI->getUseLocalStackAllocationBlock())
718 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
720 if (RS && RS->isScavengingFrameIndex((int)i))
722 if (MFI->isDeadObjectIndex(i))
724 if (MFI->getStackProtectorIndex() == (int)i)
726 if (ProtectedObjs.count(i))
729 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
732 // Make sure the special register scavenging spill slot is closest to the
734 if (RS && !EarlyScavengingSlots) {
735 SmallVector<int, 2> SFIs;
736 RS->getScavengingFrameIndices(SFIs);
737 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
738 IE = SFIs.end(); I != IE; ++I)
739 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
742 if (!TFI.targetHandlesStackFrameRounding()) {
743 // If we have reserved argument space for call sites in the function
744 // immediately on entry to the current function, count it as part of the
745 // overall stack size.
746 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
747 Offset += MFI->getMaxCallFrameSize();
749 // Round up the size to a multiple of the alignment. If the function has
750 // any calls or alloca's, align to the target's StackAlignment value to
751 // ensure that the callee's frame or the alloca data is suitably aligned;
752 // otherwise, for leaf functions, align to the TransientStackAlignment
755 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
756 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
757 StackAlign = TFI.getStackAlignment();
759 StackAlign = TFI.getTransientStackAlignment();
761 // If the frame pointer is eliminated, all frame offsets will be relative to
762 // SP not FP. Align to MaxAlign so this works.
763 StackAlign = std::max(StackAlign, MaxAlign);
764 Offset = RoundUpToAlignment(Offset, StackAlign);
767 // Update frame info to pretend that this is part of the stack...
768 int64_t StackSize = Offset - LocalAreaOffset;
769 MFI->setStackSize(StackSize);
770 NumBytesStackSpace += StackSize;
773 /// insertPrologEpilogCode - Scan the function for modified callee saved
774 /// registers, insert spill code for these callee saved registers, then add
775 /// prolog and epilog code to the function.
777 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
778 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
780 // Add prologue to the function...
781 TFI.emitPrologue(Fn, *SaveBlock);
783 // Add epilogue to restore the callee-save registers in each exiting block.
784 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
785 TFI.emitEpilogue(Fn, *RestoreBlock);
787 // Emit additional code that is required to support segmented stacks, if
788 // we've been asked for it. This, when linked with a runtime with support
789 // for segmented stacks (libgcc is one), will result in allocating stack
790 // space in small chunks instead of one large contiguous block.
791 if (Fn.shouldSplitStack())
792 TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
794 // Emit additional code that is required to explicitly handle the stack in
795 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
796 // approach is rather similar to that of Segmented Stacks, but it uses a
797 // different conditional check and another BIF for allocating more stack
799 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
800 TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
803 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
804 /// register references and actual offsets.
806 void PEI::replaceFrameIndices(MachineFunction &Fn) {
807 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
808 if (!TFI.needsFrameIndexResolution(Fn)) return;
810 MachineModuleInfo &MMI = Fn.getMMI();
811 const Function *F = Fn.getFunction();
812 const Function *ParentF = MMI.getWinEHParent(F);
815 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
816 // FIXME: This should be unconditional but we have bugs in the preparation
818 if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
819 FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
820 Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
821 } else if (MMI.hasWinEHFuncInfo(F)) {
822 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
823 auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F);
824 if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end())
825 FuncInfo.CatchHandlerParentFrameObjOffset[F] =
826 TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg);
829 // Store SPAdj at exit of a basic block.
830 SmallVector<int, 8> SPState;
831 SPState.resize(Fn.getNumBlockIDs());
832 SmallPtrSet<MachineBasicBlock*, 8> Reachable;
834 // Iterate over the reachable blocks in DFS order.
835 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
838 // Check the exit state of the DFS stack predecessor.
839 if (DFI.getPathLength() >= 2) {
840 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
841 assert(Reachable.count(StackPred) &&
842 "DFS stack predecessor is already visited.\n");
843 SPAdj = SPState[StackPred->getNumber()];
845 MachineBasicBlock *BB = *DFI;
846 replaceFrameIndices(BB, Fn, SPAdj);
847 SPState[BB->getNumber()] = SPAdj;
850 // Handle the unreachable blocks.
851 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
852 if (Reachable.count(BB))
853 // Already handled in DFS traversal.
856 replaceFrameIndices(BB, Fn, SPAdj);
860 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
862 assert(Fn.getSubtarget().getRegisterInfo() &&
863 "getRegisterInfo() must be implemented!");
864 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
865 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
866 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
867 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
868 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
870 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
872 bool InsideCallSequence = false;
874 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
876 if (I->getOpcode() == FrameSetupOpcode ||
877 I->getOpcode() == FrameDestroyOpcode) {
878 InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
879 SPAdj += TII.getSPAdjust(I);
881 MachineBasicBlock::iterator PrevI = BB->end();
882 if (I != BB->begin()) PrevI = std::prev(I);
883 TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
885 // Visit the instructions created by eliminateCallFramePseudoInstr().
886 if (PrevI == BB->end())
887 I = BB->begin(); // The replaced instr was the first in the block.
889 I = std::next(PrevI);
893 MachineInstr *MI = I;
895 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
896 if (!MI->getOperand(i).isFI())
899 // Frame indicies in debug values are encoded in a target independent
900 // way with simply the frame index and offset rather than any
901 // target-specific addressing mode.
902 if (MI->isDebugValue()) {
903 assert(i == 0 && "Frame indicies can only appear as the first "
904 "operand of a DBG_VALUE machine instruction");
906 MachineOperand &Offset = MI->getOperand(1);
907 Offset.setImm(Offset.getImm() +
908 TFI->getFrameIndexReference(
909 Fn, MI->getOperand(0).getIndex(), Reg));
910 MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
914 // TODO: This code should be commoned with the code for
915 // PATCHPOINT. There's no good reason for the difference in
916 // implementation other than historical accident. The only
917 // remaining difference is the unconditional use of the stack
918 // pointer as the base register.
919 if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
920 assert((!MI->isDebugValue() || i == 0) &&
921 "Frame indicies can only appear as the first operand of a "
922 "DBG_VALUE machine instruction");
924 MachineOperand &Offset = MI->getOperand(i + 1);
925 const unsigned refOffset =
926 TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
929 Offset.setImm(Offset.getImm() + refOffset);
930 MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
934 // Some instructions (e.g. inline asm instructions) can have
935 // multiple frame indices and/or cause eliminateFrameIndex
936 // to insert more than one instruction. We need the register
937 // scavenger to go through all of these instructions so that
938 // it can update its register information. We keep the
939 // iterator at the point before insertion so that we can
940 // revisit them in full.
941 bool AtBeginning = (I == BB->begin());
942 if (!AtBeginning) --I;
944 // If this instruction has a FrameIndex operand, we need to
945 // use that target machine register info object to eliminate
947 TRI.eliminateFrameIndex(MI, SPAdj, i,
948 FrameIndexVirtualScavenging ? nullptr : RS);
950 // Reset the iterator if we were at the beginning of the BB.
960 // If we are looking at a call sequence, we need to keep track of
961 // the SP adjustment made by each instruction in the sequence.
962 // This includes both the frame setup/destroy pseudos (handled above),
963 // as well as other instructions that have side effects w.r.t the SP.
964 // Note that this must come after eliminateFrameIndex, because
965 // if I itself referred to a frame index, we shouldn't count its own
967 if (MI && InsideCallSequence)
968 SPAdj += TII.getSPAdjust(MI);
970 if (DoIncr && I != BB->end()) ++I;
972 // Update register states.
973 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
977 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
978 /// with physical registers. Use the register scavenger to find an
979 /// appropriate register to use.
981 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
982 /// iterate over the vreg use list, which at this point only contains machine
983 /// operands for which eliminateFrameIndex need a new scratch reg.
985 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
986 // Run through the instructions and find any virtual registers.
987 for (MachineFunction::iterator BB = Fn.begin(),
988 E = Fn.end(); BB != E; ++BB) {
989 RS->enterBasicBlock(BB);
993 // The instruction stream may change in the loop, so check BB->end()
995 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
996 // We might end up here again with a NULL iterator if we scavenged a
997 // register for which we inserted spill code for definition by what was
998 // originally the first instruction in BB.
999 if (I == MachineBasicBlock::iterator(nullptr))
1002 MachineInstr *MI = I;
1003 MachineBasicBlock::iterator J = std::next(I);
1004 MachineBasicBlock::iterator P =
1005 I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1008 // RS should process this instruction before we might scavenge at this
1009 // location. This is because we might be replacing a virtual register
1010 // defined by this instruction, and if so, registers killed by this
1011 // instruction are available, and defined registers are not.
1014 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1015 if (MI->getOperand(i).isReg()) {
1016 MachineOperand &MO = MI->getOperand(i);
1017 unsigned Reg = MO.getReg();
1020 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1023 // When we first encounter a new virtual register, it
1024 // must be a definition.
1025 assert(MI->getOperand(i).isDef() &&
1026 "frame index virtual missing def!");
1027 // Scavenge a new scratch register
1028 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1029 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1033 // Replace this reference to the virtual register with the
1034 // scratch register.
1035 assert (ScratchReg && "Missing scratch register!");
1036 MachineRegisterInfo &MRI = Fn.getRegInfo();
1037 Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1039 // Make sure MRI now accounts this register as used.
1040 MRI.setPhysRegUsed(ScratchReg);
1042 // Because this instruction was processed by the RS before this
1043 // register was allocated, make sure that the RS now records the
1044 // register as being used.
1045 RS->setRegUsed(ScratchReg);
1049 // If the scavenger needed to use one of its spill slots, the
1050 // spill code will have been inserted in between I and J. This is a
1051 // problem because we need the spill code before I: Move I to just
1053 if (I != std::prev(J)) {
1054 BB->splice(J, BB, I);
1056 // Before we move I, we need to prepare the RS to visit I again.
1057 // Specifically, RS will assert if it sees uses of registers that
1058 // it believes are undefined. Because we have already processed
1059 // register kills in I, when it visits I again, it will believe that
1060 // those registers are undefined. To avoid this situation, unprocess
1061 // the instruction I.
1062 assert(RS->getCurrentPosition() == I &&
1063 "The register scavenger has an unexpected position");