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. Typically there is a
75 // single save block, unless Windows EH funclets are involved.
76 SmallVector<MachineBasicBlock *, 1> SaveBlocks;
77 SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
79 // Flag to control whether to use the register scavenger to resolve
80 // frame index materialization registers. Set according to
81 // TRI->requiresFrameIndexScavenging() for the current function.
82 bool FrameIndexVirtualScavenging;
84 void calculateSets(MachineFunction &Fn);
85 void calculateCallsInformation(MachineFunction &Fn);
86 void assignCalleeSavedSpillSlots(MachineFunction &Fn,
87 const BitVector &SavedRegs);
88 void insertCSRSpillsAndRestores(MachineFunction &Fn);
89 void calculateFrameObjectOffsets(MachineFunction &Fn);
90 void replaceFrameIndices(MachineFunction &Fn);
91 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
93 void scavengeFrameVirtualRegs(MachineFunction &Fn);
94 void insertPrologEpilogCode(MachineFunction &Fn);
96 // Convenience for recognizing return blocks.
97 bool isReturnBlock(const MachineBasicBlock *MBB) const;
102 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
104 static cl::opt<unsigned>
105 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
106 cl::desc("Warn for stack size bigger than the given"
109 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
110 "Prologue/Epilogue Insertion", false, false)
111 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
112 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
113 INITIALIZE_PASS_DEPENDENCY(StackProtector)
114 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
115 INITIALIZE_PASS_END(PEI, "prologepilog",
116 "Prologue/Epilogue Insertion & Frame Finalization",
119 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
120 STATISTIC(NumBytesStackSpace,
121 "Number of bytes used for stack in all functions");
123 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
124 AU.setPreservesCFG();
125 AU.addPreserved<MachineLoopInfo>();
126 AU.addPreserved<MachineDominatorTree>();
127 AU.addRequired<StackProtector>();
128 AU.addRequired<TargetPassConfig>();
129 MachineFunctionPass::getAnalysisUsage(AU);
132 bool PEI::isReturnBlock(const MachineBasicBlock* MBB) const {
133 return (MBB && !MBB->empty() && MBB->back().isReturn());
136 /// Compute the set of return blocks
137 void PEI::calculateSets(MachineFunction &Fn) {
138 const MachineFrameInfo *MFI = Fn.getFrameInfo();
140 // Even when we do not change any CSR, we still want to insert the
141 // prologue and epilogue of the function.
142 // So set the save points for those.
144 // Use the points found by shrink-wrapping, if any.
145 if (MFI->getSavePoint()) {
146 SaveBlocks.push_back(MFI->getSavePoint());
147 assert(MFI->getRestorePoint() && "Both restore and save must be set");
148 MachineBasicBlock *RestoreBlock = MFI->getRestorePoint();
149 // If RestoreBlock does not have any successor and is not a return block
150 // then the end point is unreachable and we do not need to insert any
152 if (!RestoreBlock->succ_empty() || isReturnBlock(RestoreBlock))
153 RestoreBlocks.push_back(RestoreBlock);
157 // Save refs to entry and return blocks.
158 SaveBlocks.push_back(Fn.begin());
159 for (MachineBasicBlock &MBB : Fn) {
160 if (MBB.isEHFuncletEntry())
161 SaveBlocks.push_back(&MBB);
162 if (isReturnBlock(&MBB))
163 RestoreBlocks.push_back(&MBB);
167 /// StackObjSet - A set of stack object indexes
168 typedef SmallSetVector<int, 8> StackObjSet;
170 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
171 /// frame indexes with appropriate references.
173 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
174 const Function* F = Fn.getFunction();
175 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
176 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
178 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
180 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
181 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
183 // Calculate the MaxCallFrameSize and AdjustsStack variables for the
184 // function's frame information. Also eliminates call frame pseudo
186 calculateCallsInformation(Fn);
188 // Determine which of the registers in the callee save list should be saved.
190 TFI->determineCalleeSaves(Fn, SavedRegs, RS);
192 // Insert spill code for any callee saved registers that are modified.
193 assignCalleeSavedSpillSlots(Fn, SavedRegs);
195 // Determine placement of CSR spill/restore code:
196 // place all spills in the entry block, all restores in return blocks.
199 // Add the code to save and restore the callee saved registers
200 if (!F->hasFnAttribute(Attribute::Naked))
201 insertCSRSpillsAndRestores(Fn);
203 // Allow the target machine to make final modifications to the function
204 // before the frame layout is finalized.
205 TFI->processFunctionBeforeFrameFinalized(Fn, RS);
207 // Calculate actual frame offsets for all abstract stack objects...
208 calculateFrameObjectOffsets(Fn);
210 // Add prolog and epilog code to the function. This function is required
211 // to align the stack frame as necessary for any stack variables or
212 // called functions. Because of this, calculateCalleeSavedRegisters()
213 // must be called before this function in order to set the AdjustsStack
214 // and MaxCallFrameSize variables.
215 if (!F->hasFnAttribute(Attribute::Naked))
216 insertPrologEpilogCode(Fn);
218 // Replace all MO_FrameIndex operands with physical register references
219 // and actual offsets.
221 replaceFrameIndices(Fn);
223 // If register scavenging is needed, as we've enabled doing it as a
224 // post-pass, scavenge the virtual registers that frame index elimination
226 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
227 scavengeFrameVirtualRegs(Fn);
229 // Clear any vregs created by virtual scavenging.
230 Fn.getRegInfo().clearVirtRegs();
232 // Warn on stack size when we exceeds the given limit.
233 MachineFrameInfo *MFI = Fn.getFrameInfo();
234 uint64_t StackSize = MFI->getStackSize();
235 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
236 DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
237 F->getContext().diagnose(DiagStackSize);
242 RestoreBlocks.clear();
246 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
247 /// variables for the function's frame information and eliminate call frame
248 /// pseudo instructions.
249 void PEI::calculateCallsInformation(MachineFunction &Fn) {
250 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
251 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
252 MachineFrameInfo *MFI = Fn.getFrameInfo();
254 unsigned MaxCallFrameSize = 0;
255 bool AdjustsStack = MFI->adjustsStack();
257 // Get the function call frame set-up and tear-down instruction opcode
258 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
259 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
261 // Early exit for targets which have no call frame setup/destroy pseudo
263 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
266 std::vector<MachineBasicBlock::iterator> FrameSDOps;
267 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
268 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
269 if (I->getOpcode() == FrameSetupOpcode ||
270 I->getOpcode() == FrameDestroyOpcode) {
271 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
272 " instructions should have a single immediate argument!");
273 unsigned Size = I->getOperand(0).getImm();
274 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
276 FrameSDOps.push_back(I);
277 } else if (I->isInlineAsm()) {
278 // Some inline asm's need a stack frame, as indicated by operand 1.
279 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
280 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
284 MFI->setAdjustsStack(AdjustsStack);
285 MFI->setMaxCallFrameSize(MaxCallFrameSize);
287 for (std::vector<MachineBasicBlock::iterator>::iterator
288 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
289 MachineBasicBlock::iterator I = *i;
291 // If call frames are not being included as part of the stack frame, and
292 // the target doesn't indicate otherwise, remove the call frame pseudos
293 // here. The sub/add sp instruction pairs are still inserted, but we don't
294 // need to track the SP adjustment for frame index elimination.
295 if (TFI->canSimplifyCallFramePseudos(Fn))
296 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
300 void PEI::assignCalleeSavedSpillSlots(MachineFunction &F,
301 const BitVector &SavedRegs) {
302 // These are used to keep track the callee-save area. Initialize them.
303 MinCSFrameIndex = INT_MAX;
306 if (SavedRegs.empty())
309 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
310 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
312 std::vector<CalleeSavedInfo> CSI;
313 for (unsigned i = 0; CSRegs[i]; ++i) {
314 unsigned Reg = CSRegs[i];
315 if (SavedRegs.test(Reg))
316 CSI.push_back(CalleeSavedInfo(Reg));
319 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
320 MachineFrameInfo *MFI = F.getFrameInfo();
321 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
322 // If target doesn't implement this, use generic code.
325 return; // Early exit if no callee saved registers are modified!
327 unsigned NumFixedSpillSlots;
328 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
329 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
331 // Now that we know which registers need to be saved and restored, allocate
332 // stack slots for them.
333 for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
335 unsigned Reg = I->getReg();
336 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
339 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
340 I->setFrameIdx(FrameIdx);
344 // Check to see if this physreg must be spilled to a particular stack slot
346 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
347 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
348 FixedSlot->Reg != Reg)
351 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
352 // Nope, just spill it anywhere convenient.
353 unsigned Align = RC->getAlignment();
354 unsigned StackAlign = TFI->getStackAlignment();
356 // We may not be able to satisfy the desired alignment specification of
357 // the TargetRegisterClass if the stack alignment is smaller. Use the
359 Align = std::min(Align, StackAlign);
360 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
361 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
362 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
364 // Spill it to the stack where we must.
366 MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
369 I->setFrameIdx(FrameIdx);
373 MFI->setCalleeSavedInfo(CSI);
376 /// Helper function to update the liveness information for the callee-saved
378 static void updateLiveness(MachineFunction &MF) {
379 MachineFrameInfo *MFI = MF.getFrameInfo();
380 // Visited will contain all the basic blocks that are in the region
381 // where the callee saved registers are alive:
382 // - Anything that is not Save or Restore -> LiveThrough.
384 // - Restore -> LiveOut.
385 // The live-out is not attached to the block, so no need to keep
386 // Restore in this set.
387 SmallPtrSet<MachineBasicBlock *, 8> Visited;
388 SmallVector<MachineBasicBlock *, 8> WorkList;
389 MachineBasicBlock *Entry = &MF.front();
390 MachineBasicBlock *Save = MFI->getSavePoint();
396 WorkList.push_back(Entry);
397 Visited.insert(Entry);
399 Visited.insert(Save);
401 MachineBasicBlock *Restore = MFI->getRestorePoint();
403 // By construction Restore cannot be visited, otherwise it
404 // means there exists a path to Restore that does not go
406 WorkList.push_back(Restore);
408 while (!WorkList.empty()) {
409 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
410 // By construction, the region that is after the save point is
411 // dominated by the Save and post-dominated by the Restore.
414 // Enqueue all the successors not already visited.
415 // Those are by construction either before Save or after Restore.
416 for (MachineBasicBlock *SuccBB : CurBB->successors())
417 if (Visited.insert(SuccBB).second)
418 WorkList.push_back(SuccBB);
421 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
423 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
424 for (MachineBasicBlock *MBB : Visited)
425 // Add the callee-saved register as live-in.
426 // It's killed at the spill.
427 MBB->addLiveIn(CSI[i].getReg());
431 /// insertCSRSpillsAndRestores - Insert spill and restore code for
432 /// callee saved registers used in the function.
434 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
435 // Get callee saved register information.
436 MachineFrameInfo *MFI = Fn.getFrameInfo();
437 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
439 MFI->setCalleeSavedInfoValid(true);
441 // Early exit if no callee saved registers are modified!
445 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
446 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
447 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
448 MachineBasicBlock::iterator I;
450 // Spill using target interface.
451 for (MachineBasicBlock *SaveBlock : SaveBlocks) {
452 I = SaveBlock->begin();
453 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
454 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
455 // Insert the spill to the stack frame.
456 unsigned Reg = CSI[i].getReg();
457 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
458 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
462 // Update the live-in information of all the blocks up to the save point.
466 // Restore using target interface.
467 for (MachineBasicBlock *MBB : RestoreBlocks) {
470 // Skip over all terminator instructions, which are part of the return
472 MachineBasicBlock::iterator I2 = I;
473 while (I2 != MBB->begin() && (--I2)->isTerminator())
476 bool AtStart = I == MBB->begin();
477 MachineBasicBlock::iterator BeforeI = I;
481 // Restore all registers immediately before the return and any
482 // terminators that precede it.
483 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
484 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
485 unsigned Reg = CSI[i].getReg();
486 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
487 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
488 assert(I != MBB->begin() &&
489 "loadRegFromStackSlot didn't insert any code!");
490 // Insert in reverse order. loadRegFromStackSlot can insert
491 // multiple instructions.
503 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
505 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
506 bool StackGrowsDown, int64_t &Offset,
507 unsigned &MaxAlign) {
508 // If the stack grows down, add the object size to find the lowest address.
510 Offset += MFI->getObjectSize(FrameIdx);
512 unsigned Align = MFI->getObjectAlignment(FrameIdx);
514 // If the alignment of this object is greater than that of the stack, then
515 // increase the stack alignment to match.
516 MaxAlign = std::max(MaxAlign, Align);
518 // Adjust to alignment boundary.
519 Offset = (Offset + Align - 1) / Align * Align;
521 if (StackGrowsDown) {
522 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
523 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
525 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
526 MFI->setObjectOffset(FrameIdx, Offset);
527 Offset += MFI->getObjectSize(FrameIdx);
531 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
532 /// those required to be close to the Stack Protector) to stack offsets.
534 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
535 SmallSet<int, 16> &ProtectedObjs,
536 MachineFrameInfo *MFI, bool StackGrowsDown,
537 int64_t &Offset, unsigned &MaxAlign) {
539 for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
540 E = UnassignedObjs.end(); I != E; ++I) {
542 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
543 ProtectedObjs.insert(i);
547 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
548 /// abstract stack objects.
550 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
551 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
552 StackProtector *SP = &getAnalysis<StackProtector>();
554 bool StackGrowsDown =
555 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
557 // Loop over all of the stack objects, assigning sequential addresses...
558 MachineFrameInfo *MFI = Fn.getFrameInfo();
560 // Start at the beginning of the local area.
561 // The Offset is the distance from the stack top in the direction
562 // of stack growth -- so it's always nonnegative.
563 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
565 LocalAreaOffset = -LocalAreaOffset;
566 assert(LocalAreaOffset >= 0
567 && "Local area offset should be in direction of stack growth");
568 int64_t Offset = LocalAreaOffset;
570 // If there are fixed sized objects that are preallocated in the local area,
571 // non-fixed objects can't be allocated right at the start of local area.
572 // We currently don't support filling in holes in between fixed sized
573 // objects, so we adjust 'Offset' to point to the end of last fixed sized
574 // preallocated object.
575 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
577 if (StackGrowsDown) {
578 // The maximum distance from the stack pointer is at lower address of
579 // the object -- which is given by offset. For down growing stack
580 // the offset is negative, so we negate the offset to get the distance.
581 FixedOff = -MFI->getObjectOffset(i);
583 // The maximum distance from the start pointer is at the upper
584 // address of the object.
585 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
587 if (FixedOff > Offset) Offset = FixedOff;
590 // First assign frame offsets to stack objects that are used to spill
591 // callee saved registers.
592 if (StackGrowsDown) {
593 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
594 // If the stack grows down, we need to add the size to find the lowest
595 // address of the object.
596 Offset += MFI->getObjectSize(i);
598 unsigned Align = MFI->getObjectAlignment(i);
599 // Adjust to alignment boundary
600 Offset = RoundUpToAlignment(Offset, Align);
602 MFI->setObjectOffset(i, -Offset); // Set the computed offset
605 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
606 for (int i = MaxCSFI; i >= MinCSFI ; --i) {
607 unsigned Align = MFI->getObjectAlignment(i);
608 // Adjust to alignment boundary
609 Offset = RoundUpToAlignment(Offset, Align);
611 MFI->setObjectOffset(i, Offset);
612 Offset += MFI->getObjectSize(i);
616 unsigned MaxAlign = MFI->getMaxAlignment();
618 // Make sure the special register scavenging spill slot is closest to the
619 // incoming stack pointer if a frame pointer is required and is closer
620 // to the incoming rather than the final stack pointer.
621 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
622 bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
623 TFI.isFPCloseToIncomingSP() &&
624 RegInfo->useFPForScavengingIndex(Fn) &&
625 !RegInfo->needsStackRealignment(Fn));
626 if (RS && EarlyScavengingSlots) {
627 SmallVector<int, 2> SFIs;
628 RS->getScavengingFrameIndices(SFIs);
629 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
630 IE = SFIs.end(); I != IE; ++I)
631 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
634 // FIXME: Once this is working, then enable flag will change to a target
635 // check for whether the frame is large enough to want to use virtual
636 // frame index registers. Functions which don't want/need this optimization
637 // will continue to use the existing code path.
638 if (MFI->getUseLocalStackAllocationBlock()) {
639 unsigned Align = MFI->getLocalFrameMaxAlign();
641 // Adjust to alignment boundary.
642 Offset = RoundUpToAlignment(Offset, Align);
644 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
646 // Resolve offsets for objects in the local block.
647 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
648 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
649 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
650 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
652 MFI->setObjectOffset(Entry.first, FIOffset);
654 // Allocate the local block
655 Offset += MFI->getLocalFrameSize();
657 MaxAlign = std::max(Align, MaxAlign);
660 // Make sure that the stack protector comes before the local variables on the
662 SmallSet<int, 16> ProtectedObjs;
663 if (MFI->getStackProtectorIndex() >= 0) {
664 StackObjSet LargeArrayObjs;
665 StackObjSet SmallArrayObjs;
666 StackObjSet AddrOfObjs;
668 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
671 // Assign large stack objects first.
672 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
673 if (MFI->isObjectPreAllocated(i) &&
674 MFI->getUseLocalStackAllocationBlock())
676 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
678 if (RS && RS->isScavengingFrameIndex((int)i))
680 if (MFI->isDeadObjectIndex(i))
682 if (MFI->getStackProtectorIndex() == (int)i)
685 switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
686 case StackProtector::SSPLK_None:
688 case StackProtector::SSPLK_SmallArray:
689 SmallArrayObjs.insert(i);
691 case StackProtector::SSPLK_AddrOf:
692 AddrOfObjs.insert(i);
694 case StackProtector::SSPLK_LargeArray:
695 LargeArrayObjs.insert(i);
698 llvm_unreachable("Unexpected SSPLayoutKind.");
701 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
703 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
705 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
709 // Then assign frame offsets to stack objects that are not used to spill
710 // callee saved registers.
711 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
712 if (MFI->isObjectPreAllocated(i) &&
713 MFI->getUseLocalStackAllocationBlock())
715 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
717 if (RS && RS->isScavengingFrameIndex((int)i))
719 if (MFI->isDeadObjectIndex(i))
721 if (MFI->getStackProtectorIndex() == (int)i)
723 if (ProtectedObjs.count(i))
726 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
729 // Make sure the special register scavenging spill slot is closest to the
731 if (RS && !EarlyScavengingSlots) {
732 SmallVector<int, 2> SFIs;
733 RS->getScavengingFrameIndices(SFIs);
734 for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
735 IE = SFIs.end(); I != IE; ++I)
736 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
739 if (!TFI.targetHandlesStackFrameRounding()) {
740 // If we have reserved argument space for call sites in the function
741 // immediately on entry to the current function, count it as part of the
742 // overall stack size.
743 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
744 Offset += MFI->getMaxCallFrameSize();
746 // Round up the size to a multiple of the alignment. If the function has
747 // any calls or alloca's, align to the target's StackAlignment value to
748 // ensure that the callee's frame or the alloca data is suitably aligned;
749 // otherwise, for leaf functions, align to the TransientStackAlignment
752 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
753 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
754 StackAlign = TFI.getStackAlignment();
756 StackAlign = TFI.getTransientStackAlignment();
758 // If the frame pointer is eliminated, all frame offsets will be relative to
759 // SP not FP. Align to MaxAlign so this works.
760 StackAlign = std::max(StackAlign, MaxAlign);
761 Offset = RoundUpToAlignment(Offset, StackAlign);
764 // Update frame info to pretend that this is part of the stack...
765 int64_t StackSize = Offset - LocalAreaOffset;
766 MFI->setStackSize(StackSize);
767 NumBytesStackSpace += StackSize;
770 /// insertPrologEpilogCode - Scan the function for modified callee saved
771 /// registers, insert spill code for these callee saved registers, then add
772 /// prolog and epilog code to the function.
774 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
775 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
777 // Add prologue to the function...
778 for (MachineBasicBlock *SaveBlock : SaveBlocks)
779 TFI.emitPrologue(Fn, *SaveBlock);
781 // Add epilogue to restore the callee-save registers in each exiting block.
782 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
783 TFI.emitEpilogue(Fn, *RestoreBlock);
785 // Emit additional code that is required to support segmented stacks, if
786 // we've been asked for it. This, when linked with a runtime with support
787 // for segmented stacks (libgcc is one), will result in allocating stack
788 // space in small chunks instead of one large contiguous block.
789 if (Fn.shouldSplitStack()) {
790 for (MachineBasicBlock *SaveBlock : SaveBlocks)
791 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 for (MachineBasicBlock *SaveBlock : SaveBlocks)
801 TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
804 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
805 /// register references and actual offsets.
807 void PEI::replaceFrameIndices(MachineFunction &Fn) {
808 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
809 if (!TFI.needsFrameIndexResolution(Fn)) return;
811 MachineModuleInfo &MMI = Fn.getMMI();
812 const Function *F = Fn.getFunction();
813 const Function *ParentF = MMI.getWinEHParent(F);
816 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
817 // FIXME: This should be unconditional but we have bugs in the preparation
819 if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
820 FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
821 Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
822 } else if (MMI.hasWinEHFuncInfo(F)) {
823 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
824 auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F);
825 if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end())
826 FuncInfo.CatchHandlerParentFrameObjOffset[F] =
827 TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg);
830 // Store SPAdj at exit of a basic block.
831 SmallVector<int, 8> SPState;
832 SPState.resize(Fn.getNumBlockIDs());
833 SmallPtrSet<MachineBasicBlock*, 8> Reachable;
835 // Iterate over the reachable blocks in DFS order.
836 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
839 // Check the exit state of the DFS stack predecessor.
840 if (DFI.getPathLength() >= 2) {
841 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
842 assert(Reachable.count(StackPred) &&
843 "DFS stack predecessor is already visited.\n");
844 SPAdj = SPState[StackPred->getNumber()];
846 MachineBasicBlock *BB = *DFI;
847 replaceFrameIndices(BB, Fn, SPAdj);
848 SPState[BB->getNumber()] = SPAdj;
851 // Handle the unreachable blocks.
852 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
853 if (Reachable.count(BB))
854 // Already handled in DFS traversal.
857 replaceFrameIndices(BB, Fn, SPAdj);
861 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
863 assert(Fn.getSubtarget().getRegisterInfo() &&
864 "getRegisterInfo() must be implemented!");
865 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
866 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
867 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
868 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
869 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
871 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
873 bool InsideCallSequence = false;
875 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
877 if (I->getOpcode() == FrameSetupOpcode ||
878 I->getOpcode() == FrameDestroyOpcode) {
879 InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
880 SPAdj += TII.getSPAdjust(I);
882 MachineBasicBlock::iterator PrevI = BB->end();
883 if (I != BB->begin()) PrevI = std::prev(I);
884 TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
886 // Visit the instructions created by eliminateCallFramePseudoInstr().
887 if (PrevI == BB->end())
888 I = BB->begin(); // The replaced instr was the first in the block.
890 I = std::next(PrevI);
894 MachineInstr *MI = I;
896 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
897 if (!MI->getOperand(i).isFI())
900 // Frame indicies in debug values are encoded in a target independent
901 // way with simply the frame index and offset rather than any
902 // target-specific addressing mode.
903 if (MI->isDebugValue()) {
904 assert(i == 0 && "Frame indicies can only appear as the first "
905 "operand of a DBG_VALUE machine instruction");
907 MachineOperand &Offset = MI->getOperand(1);
908 Offset.setImm(Offset.getImm() +
909 TFI->getFrameIndexReference(
910 Fn, MI->getOperand(0).getIndex(), Reg));
911 MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
915 // TODO: This code should be commoned with the code for
916 // PATCHPOINT. There's no good reason for the difference in
917 // implementation other than historical accident. The only
918 // remaining difference is the unconditional use of the stack
919 // pointer as the base register.
920 if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
921 assert((!MI->isDebugValue() || i == 0) &&
922 "Frame indicies can only appear as the first operand of a "
923 "DBG_VALUE machine instruction");
925 MachineOperand &Offset = MI->getOperand(i + 1);
926 const unsigned refOffset =
927 TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
930 Offset.setImm(Offset.getImm() + refOffset);
931 MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
935 // Some instructions (e.g. inline asm instructions) can have
936 // multiple frame indices and/or cause eliminateFrameIndex
937 // to insert more than one instruction. We need the register
938 // scavenger to go through all of these instructions so that
939 // it can update its register information. We keep the
940 // iterator at the point before insertion so that we can
941 // revisit them in full.
942 bool AtBeginning = (I == BB->begin());
943 if (!AtBeginning) --I;
945 // If this instruction has a FrameIndex operand, we need to
946 // use that target machine register info object to eliminate
948 TRI.eliminateFrameIndex(MI, SPAdj, i,
949 FrameIndexVirtualScavenging ? nullptr : RS);
951 // Reset the iterator if we were at the beginning of the BB.
961 // If we are looking at a call sequence, we need to keep track of
962 // the SP adjustment made by each instruction in the sequence.
963 // This includes both the frame setup/destroy pseudos (handled above),
964 // as well as other instructions that have side effects w.r.t the SP.
965 // Note that this must come after eliminateFrameIndex, because
966 // if I itself referred to a frame index, we shouldn't count its own
968 if (MI && InsideCallSequence)
969 SPAdj += TII.getSPAdjust(MI);
971 if (DoIncr && I != BB->end()) ++I;
973 // Update register states.
974 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
978 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
979 /// with physical registers. Use the register scavenger to find an
980 /// appropriate register to use.
982 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
983 /// iterate over the vreg use list, which at this point only contains machine
984 /// operands for which eliminateFrameIndex need a new scratch reg.
986 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
987 // Run through the instructions and find any virtual registers.
988 for (MachineFunction::iterator BB = Fn.begin(),
989 E = Fn.end(); BB != E; ++BB) {
990 RS->enterBasicBlock(BB);
994 // The instruction stream may change in the loop, so check BB->end()
996 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
997 // We might end up here again with a NULL iterator if we scavenged a
998 // register for which we inserted spill code for definition by what was
999 // originally the first instruction in BB.
1000 if (I == MachineBasicBlock::iterator(nullptr))
1003 MachineInstr *MI = I;
1004 MachineBasicBlock::iterator J = std::next(I);
1005 MachineBasicBlock::iterator P =
1006 I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1009 // RS should process this instruction before we might scavenge at this
1010 // location. This is because we might be replacing a virtual register
1011 // defined by this instruction, and if so, registers killed by this
1012 // instruction are available, and defined registers are not.
1015 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1016 if (MI->getOperand(i).isReg()) {
1017 MachineOperand &MO = MI->getOperand(i);
1018 unsigned Reg = MO.getReg();
1021 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1024 // When we first encounter a new virtual register, it
1025 // must be a definition.
1026 assert(MI->getOperand(i).isDef() &&
1027 "frame index virtual missing def!");
1028 // Scavenge a new scratch register
1029 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1030 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1034 // Replace this reference to the virtual register with the
1035 // scratch register.
1036 assert (ScratchReg && "Missing scratch register!");
1037 Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1039 // Because this instruction was processed by the RS before this
1040 // register was allocated, make sure that the RS now records the
1041 // register as being used.
1042 RS->setRegUsed(ScratchReg);
1046 // If the scavenger needed to use one of its spill slots, the
1047 // spill code will have been inserted in between I and J. This is a
1048 // problem because we need the spill code before I: Move I to just
1050 if (I != std::prev(J)) {
1051 BB->splice(J, BB, I);
1053 // Before we move I, we need to prepare the RS to visit I again.
1054 // Specifically, RS will assert if it sees uses of registers that
1055 // it believes are undefined. Because we have already processed
1056 // register kills in I, when it visits I again, it will believe that
1057 // those registers are undefined. To avoid this situation, unprocess
1058 // the instruction I.
1059 assert(RS->getCurrentPosition() == I &&
1060 "The register scavenger has an unexpected position");