xref: /llvm-project/llvm/lib/CodeGen/PrologEpilogInserter.cpp (revision d06896138c8c3cf38f94091b2e928318546f80b2)
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/WinEHFuncInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <climits>
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "pei"
49 
50 namespace {
51 class PEI : public MachineFunctionPass {
52 public:
53   static char ID;
54   PEI() : MachineFunctionPass(ID) {
55     initializePEIPass(*PassRegistry::getPassRegistry());
56   }
57 
58   void getAnalysisUsage(AnalysisUsage &AU) const override;
59 
60   MachineFunctionProperties getRequiredProperties() const override {
61     return MachineFunctionProperties().set(
62         MachineFunctionProperties::Property::AllVRegsAllocated);
63   }
64 
65   /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
66   /// frame indexes with appropriate references.
67   ///
68   bool runOnMachineFunction(MachineFunction &Fn) override;
69 
70 private:
71   RegScavenger *RS;
72 
73   // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
74   // stack frame indexes.
75   unsigned MinCSFrameIndex, MaxCSFrameIndex;
76 
77   // Save and Restore blocks of the current function. Typically there is a
78   // single save block, unless Windows EH funclets are involved.
79   SmallVector<MachineBasicBlock *, 1> SaveBlocks;
80   SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
81 
82   // Flag to control whether to use the register scavenger to resolve
83   // frame index materialization registers. Set according to
84   // TRI->requiresFrameIndexScavenging() for the current function.
85   bool FrameIndexVirtualScavenging;
86 
87   void calculateSets(MachineFunction &Fn);
88   void calculateCallsInformation(MachineFunction &Fn);
89   void assignCalleeSavedSpillSlots(MachineFunction &Fn,
90                                    const BitVector &SavedRegs);
91   void insertCSRSpillsAndRestores(MachineFunction &Fn);
92   void calculateFrameObjectOffsets(MachineFunction &Fn);
93   void replaceFrameIndices(MachineFunction &Fn);
94   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
95                            int &SPAdj);
96   void scavengeFrameVirtualRegs(MachineFunction &Fn);
97   void insertPrologEpilogCode(MachineFunction &Fn);
98 };
99 } // namespace
100 
101 char PEI::ID = 0;
102 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
103 
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"
107                        " number"));
108 
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_END(PEI, "prologepilog",
115                     "Prologue/Epilogue Insertion & Frame Finalization",
116                     false, false)
117 
118 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
119 STATISTIC(NumBytesStackSpace,
120           "Number of bytes used for stack in all functions");
121 
122 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
123   AU.setPreservesCFG();
124   AU.addPreserved<MachineLoopInfo>();
125   AU.addPreserved<MachineDominatorTree>();
126   AU.addRequired<StackProtector>();
127   MachineFunctionPass::getAnalysisUsage(AU);
128 }
129 
130 /// Compute the set of return blocks
131 void PEI::calculateSets(MachineFunction &Fn) {
132   const MachineFrameInfo *MFI = Fn.getFrameInfo();
133 
134   // Even when we do not change any CSR, we still want to insert the
135   // prologue and epilogue of the function.
136   // So set the save points for those.
137 
138   // Use the points found by shrink-wrapping, if any.
139   if (MFI->getSavePoint()) {
140     SaveBlocks.push_back(MFI->getSavePoint());
141     assert(MFI->getRestorePoint() && "Both restore and save must be set");
142     MachineBasicBlock *RestoreBlock = MFI->getRestorePoint();
143     // If RestoreBlock does not have any successor and is not a return block
144     // then the end point is unreachable and we do not need to insert any
145     // epilogue.
146     if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
147       RestoreBlocks.push_back(RestoreBlock);
148     return;
149   }
150 
151   // Save refs to entry and return blocks.
152   SaveBlocks.push_back(&Fn.front());
153   for (MachineBasicBlock &MBB : Fn) {
154     if (MBB.isEHFuncletEntry())
155       SaveBlocks.push_back(&MBB);
156     if (MBB.isReturnBlock())
157       RestoreBlocks.push_back(&MBB);
158   }
159 }
160 
161 /// StackObjSet - A set of stack object indexes
162 typedef SmallSetVector<int, 8> StackObjSet;
163 
164 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
165 /// frame indexes with appropriate references.
166 ///
167 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
168   const Function* F = Fn.getFunction();
169   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
170   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
171 
172   assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
173 
174   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
175   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
176 
177   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
178   // function's frame information. Also eliminates call frame pseudo
179   // instructions.
180   calculateCallsInformation(Fn);
181 
182   // Determine which of the registers in the callee save list should be saved.
183   BitVector SavedRegs;
184   TFI->determineCalleeSaves(Fn, SavedRegs, RS);
185 
186   // Insert spill code for any callee saved registers that are modified.
187   assignCalleeSavedSpillSlots(Fn, SavedRegs);
188 
189   // Determine placement of CSR spill/restore code:
190   // place all spills in the entry block, all restores in return blocks.
191   calculateSets(Fn);
192 
193   // Add the code to save and restore the callee saved registers.
194   if (!F->hasFnAttribute(Attribute::Naked))
195     insertCSRSpillsAndRestores(Fn);
196 
197   // Allow the target machine to make final modifications to the function
198   // before the frame layout is finalized.
199   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
200 
201   // Calculate actual frame offsets for all abstract stack objects...
202   calculateFrameObjectOffsets(Fn);
203 
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);
211 
212   // Replace all MO_FrameIndex operands with physical register references
213   // and actual offsets.
214   //
215   replaceFrameIndices(Fn);
216 
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
219   // inserted.
220   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
221     scavengeFrameVirtualRegs(Fn);
222 
223   // Clear any vregs created by virtual scavenging.
224   Fn.getRegInfo().clearVirtRegs();
225 
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);
232   }
233 
234   delete RS;
235   SaveBlocks.clear();
236   RestoreBlocks.clear();
237   MFI->setSavePoint(nullptr);
238   MFI->setRestorePoint(nullptr);
239   return true;
240 }
241 
242 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
243 /// variables for the function's frame information and eliminate call frame
244 /// pseudo instructions.
245 void PEI::calculateCallsInformation(MachineFunction &Fn) {
246   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
247   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
248   MachineFrameInfo *MFI = Fn.getFrameInfo();
249 
250   unsigned MaxCallFrameSize = 0;
251   bool AdjustsStack = MFI->adjustsStack();
252 
253   // Get the function call frame set-up and tear-down instruction opcode
254   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
255   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
256 
257   // Early exit for targets which have no call frame setup/destroy pseudo
258   // instructions.
259   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
260     return;
261 
262   std::vector<MachineBasicBlock::iterator> FrameSDOps;
263   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
264     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
265       if (I->getOpcode() == FrameSetupOpcode ||
266           I->getOpcode() == FrameDestroyOpcode) {
267         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
268                " instructions should have a single immediate argument!");
269         unsigned Size = I->getOperand(0).getImm();
270         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
271         AdjustsStack = true;
272         FrameSDOps.push_back(I);
273       } else if (I->isInlineAsm()) {
274         // Some inline asm's need a stack frame, as indicated by operand 1.
275         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
276         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
277           AdjustsStack = true;
278       }
279 
280   MFI->setAdjustsStack(AdjustsStack);
281   MFI->setMaxCallFrameSize(MaxCallFrameSize);
282 
283   for (std::vector<MachineBasicBlock::iterator>::iterator
284          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
285     MachineBasicBlock::iterator I = *i;
286 
287     // If call frames are not being included as part of the stack frame, and
288     // the target doesn't indicate otherwise, remove the call frame pseudos
289     // here. The sub/add sp instruction pairs are still inserted, but we don't
290     // need to track the SP adjustment for frame index elimination.
291     if (TFI->canSimplifyCallFramePseudos(Fn))
292       TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
293   }
294 }
295 
296 void PEI::assignCalleeSavedSpillSlots(MachineFunction &F,
297                                       const BitVector &SavedRegs) {
298   // These are used to keep track the callee-save area. Initialize them.
299   MinCSFrameIndex = INT_MAX;
300   MaxCSFrameIndex = 0;
301 
302   if (SavedRegs.empty())
303     return;
304 
305   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
306   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
307 
308   std::vector<CalleeSavedInfo> CSI;
309   for (unsigned i = 0; CSRegs[i]; ++i) {
310     unsigned Reg = CSRegs[i];
311     if (SavedRegs.test(Reg))
312       CSI.push_back(CalleeSavedInfo(Reg));
313   }
314 
315   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
316   MachineFrameInfo *MFI = F.getFrameInfo();
317   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
318     // If target doesn't implement this, use generic code.
319 
320     if (CSI.empty())
321       return; // Early exit if no callee saved registers are modified!
322 
323     unsigned NumFixedSpillSlots;
324     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
325         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
326 
327     // Now that we know which registers need to be saved and restored, allocate
328     // stack slots for them.
329     for (auto &CS : CSI) {
330       unsigned Reg = CS.getReg();
331       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
332 
333       int FrameIdx;
334       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
335         CS.setFrameIdx(FrameIdx);
336         continue;
337       }
338 
339       // Check to see if this physreg must be spilled to a particular stack slot
340       // on this target.
341       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
342       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
343              FixedSlot->Reg != Reg)
344         ++FixedSlot;
345 
346       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
347         // Nope, just spill it anywhere convenient.
348         unsigned Align = RC->getAlignment();
349         unsigned StackAlign = TFI->getStackAlignment();
350 
351         // We may not be able to satisfy the desired alignment specification of
352         // the TargetRegisterClass if the stack alignment is smaller. Use the
353         // min.
354         Align = std::min(Align, StackAlign);
355         FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
356         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
357         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
358       } else {
359         // Spill it to the stack where we must.
360         FrameIdx =
361             MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
362       }
363 
364       CS.setFrameIdx(FrameIdx);
365     }
366   }
367 
368   MFI->setCalleeSavedInfo(CSI);
369 }
370 
371 /// Helper function to update the liveness information for the callee-saved
372 /// registers.
373 static void updateLiveness(MachineFunction &MF) {
374   MachineFrameInfo *MFI = MF.getFrameInfo();
375   // Visited will contain all the basic blocks that are in the region
376   // where the callee saved registers are alive:
377   // - Anything that is not Save or Restore -> LiveThrough.
378   // - Save -> LiveIn.
379   // - Restore -> LiveOut.
380   // The live-out is not attached to the block, so no need to keep
381   // Restore in this set.
382   SmallPtrSet<MachineBasicBlock *, 8> Visited;
383   SmallVector<MachineBasicBlock *, 8> WorkList;
384   MachineBasicBlock *Entry = &MF.front();
385   MachineBasicBlock *Save = MFI->getSavePoint();
386 
387   if (!Save)
388     Save = Entry;
389 
390   if (Entry != Save) {
391     WorkList.push_back(Entry);
392     Visited.insert(Entry);
393   }
394   Visited.insert(Save);
395 
396   MachineBasicBlock *Restore = MFI->getRestorePoint();
397   if (Restore)
398     // By construction Restore cannot be visited, otherwise it
399     // means there exists a path to Restore that does not go
400     // through Save.
401     WorkList.push_back(Restore);
402 
403   while (!WorkList.empty()) {
404     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
405     // By construction, the region that is after the save point is
406     // dominated by the Save and post-dominated by the Restore.
407     if (CurBB == Save && Save != Restore)
408       continue;
409     // Enqueue all the successors not already visited.
410     // Those are by construction either before Save or after Restore.
411     for (MachineBasicBlock *SuccBB : CurBB->successors())
412       if (Visited.insert(SuccBB).second)
413         WorkList.push_back(SuccBB);
414   }
415 
416   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
417 
418   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
419     for (MachineBasicBlock *MBB : Visited) {
420       MCPhysReg Reg = CSI[i].getReg();
421       // Add the callee-saved register as live-in.
422       // It's killed at the spill.
423       if (!MBB->isLiveIn(Reg))
424         MBB->addLiveIn(Reg);
425     }
426   }
427 }
428 
429 /// insertCSRSpillsAndRestores - Insert spill and restore code for
430 /// callee saved registers used in the function.
431 ///
432 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
433   // Get callee saved register information.
434   MachineFrameInfo *MFI = Fn.getFrameInfo();
435   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
436 
437   MFI->setCalleeSavedInfoValid(true);
438 
439   // Early exit if no callee saved registers are modified!
440   if (CSI.empty())
441     return;
442 
443   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
444   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
445   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
446   MachineBasicBlock::iterator I;
447 
448   // Spill using target interface.
449   for (MachineBasicBlock *SaveBlock : SaveBlocks) {
450     I = SaveBlock->begin();
451     if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
452       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
453         // Insert the spill to the stack frame.
454         unsigned Reg = CSI[i].getReg();
455         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
456         TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
457                                 RC, TRI);
458       }
459     }
460     // Update the live-in information of all the blocks up to the save point.
461     updateLiveness(Fn);
462   }
463 
464   // Restore using target interface.
465   for (MachineBasicBlock *MBB : RestoreBlocks) {
466     I = MBB->end();
467 
468     // Skip over all terminator instructions, which are part of the return
469     // sequence.
470     MachineBasicBlock::iterator I2 = I;
471     while (I2 != MBB->begin() && (--I2)->isTerminator())
472       I = I2;
473 
474     bool AtStart = I == MBB->begin();
475     MachineBasicBlock::iterator BeforeI = I;
476     if (!AtStart)
477       --BeforeI;
478 
479     // Restore all registers immediately before the return and any
480     // terminators that precede it.
481     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
482       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
483         unsigned Reg = CSI[i].getReg();
484         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
485         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
486         assert(I != MBB->begin() &&
487                "loadRegFromStackSlot didn't insert any code!");
488         // Insert in reverse order.  loadRegFromStackSlot can insert
489         // multiple instructions.
490         if (AtStart)
491           I = MBB->begin();
492         else {
493           I = BeforeI;
494           ++I;
495         }
496       }
497     }
498   }
499 }
500 
501 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
502 static inline void
503 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
504                   bool StackGrowsDown, int64_t &Offset,
505                   unsigned &MaxAlign, unsigned Skew) {
506   // If the stack grows down, add the object size to find the lowest address.
507   if (StackGrowsDown)
508     Offset += MFI->getObjectSize(FrameIdx);
509 
510   unsigned Align = MFI->getObjectAlignment(FrameIdx);
511 
512   // If the alignment of this object is greater than that of the stack, then
513   // increase the stack alignment to match.
514   MaxAlign = std::max(MaxAlign, Align);
515 
516   // Adjust to alignment boundary.
517   Offset = alignTo(Offset, Align, Skew);
518 
519   if (StackGrowsDown) {
520     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
521     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
522   } else {
523     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
524     MFI->setObjectOffset(FrameIdx, Offset);
525     Offset += MFI->getObjectSize(FrameIdx);
526   }
527 }
528 
529 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
530 /// those required to be close to the Stack Protector) to stack offsets.
531 static void
532 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
533                       SmallSet<int, 16> &ProtectedObjs,
534                       MachineFrameInfo *MFI, bool StackGrowsDown,
535                       int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
536 
537   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
538         E = UnassignedObjs.end(); I != E; ++I) {
539     int i = *I;
540     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
541     ProtectedObjs.insert(i);
542   }
543 }
544 
545 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
546 /// abstract stack objects.
547 ///
548 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
549   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
550   StackProtector *SP = &getAnalysis<StackProtector>();
551 
552   bool StackGrowsDown =
553     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
554 
555   // Loop over all of the stack objects, assigning sequential addresses...
556   MachineFrameInfo *MFI = Fn.getFrameInfo();
557 
558   // Start at the beginning of the local area.
559   // The Offset is the distance from the stack top in the direction
560   // of stack growth -- so it's always nonnegative.
561   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
562   if (StackGrowsDown)
563     LocalAreaOffset = -LocalAreaOffset;
564   assert(LocalAreaOffset >= 0
565          && "Local area offset should be in direction of stack growth");
566   int64_t Offset = LocalAreaOffset;
567 
568   // Skew to be applied to alignment.
569   unsigned Skew = TFI.getStackAlignmentSkew(Fn);
570 
571   // If there are fixed sized objects that are preallocated in the local area,
572   // non-fixed objects can't be allocated right at the start of local area.
573   // We currently don't support filling in holes in between fixed sized
574   // objects, so we adjust 'Offset' to point to the end of last fixed sized
575   // preallocated object.
576   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
577     int64_t FixedOff;
578     if (StackGrowsDown) {
579       // The maximum distance from the stack pointer is at lower address of
580       // the object -- which is given by offset. For down growing stack
581       // the offset is negative, so we negate the offset to get the distance.
582       FixedOff = -MFI->getObjectOffset(i);
583     } else {
584       // The maximum distance from the start pointer is at the upper
585       // address of the object.
586       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
587     }
588     if (FixedOff > Offset) Offset = FixedOff;
589   }
590 
591   // First assign frame offsets to stack objects that are used to spill
592   // callee saved registers.
593   if (StackGrowsDown) {
594     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
595       // If the stack grows down, we need to add the size to find the lowest
596       // address of the object.
597       Offset += MFI->getObjectSize(i);
598 
599       unsigned Align = MFI->getObjectAlignment(i);
600       // Adjust to alignment boundary
601       Offset = alignTo(Offset, Align, Skew);
602 
603       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
604       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
605     }
606   } else {
607     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
608     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
609       unsigned Align = MFI->getObjectAlignment(i);
610       // Adjust to alignment boundary
611       Offset = alignTo(Offset, Align, Skew);
612 
613       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
614       MFI->setObjectOffset(i, Offset);
615       Offset += MFI->getObjectSize(i);
616     }
617   }
618 
619   unsigned MaxAlign = MFI->getMaxAlignment();
620 
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, Skew);
635   }
636 
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();
643 
644     // Adjust to alignment boundary.
645     Offset = alignTo(Offset, Align, Skew);
646 
647     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
648 
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[" <<
654             FIOffset << "]\n");
655       MFI->setObjectOffset(Entry.first, FIOffset);
656     }
657     // Allocate the local block
658     Offset += MFI->getLocalFrameSize();
659 
660     MaxAlign = std::max(Align, MaxAlign);
661   }
662 
663   // Make sure that the stack protector comes before the local variables on the
664   // stack.
665   SmallSet<int, 16> ProtectedObjs;
666   if (MFI->getStackProtectorIndex() >= 0) {
667     StackObjSet LargeArrayObjs;
668     StackObjSet SmallArrayObjs;
669     StackObjSet AddrOfObjs;
670 
671     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
672                       Offset, MaxAlign, Skew);
673 
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())
678         continue;
679       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
680         continue;
681       if (RS && RS->isScavengingFrameIndex((int)i))
682         continue;
683       if (MFI->isDeadObjectIndex(i))
684         continue;
685       if (MFI->getStackProtectorIndex() == (int)i)
686         continue;
687 
688       switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
689       case StackProtector::SSPLK_None:
690         continue;
691       case StackProtector::SSPLK_SmallArray:
692         SmallArrayObjs.insert(i);
693         continue;
694       case StackProtector::SSPLK_AddrOf:
695         AddrOfObjs.insert(i);
696         continue;
697       case StackProtector::SSPLK_LargeArray:
698         LargeArrayObjs.insert(i);
699         continue;
700       }
701       llvm_unreachable("Unexpected SSPLayoutKind.");
702     }
703 
704     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
705                           Offset, MaxAlign, Skew);
706     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
707                           Offset, MaxAlign, Skew);
708     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
709                           Offset, MaxAlign, Skew);
710   }
711 
712   SmallVector<int, 8> ObjectsToAllocate;
713 
714   int EHRegNodeFrameIndex = INT_MAX;
715   if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
716     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
717 
718   // Then prepare to assign frame offsets to stack objects that are not used to
719   // spill callee saved registers.
720   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
721     if (MFI->isObjectPreAllocated(i) &&
722         MFI->getUseLocalStackAllocationBlock())
723       continue;
724     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
725       continue;
726     if (RS && RS->isScavengingFrameIndex((int)i))
727       continue;
728     if (MFI->isDeadObjectIndex(i))
729       continue;
730     if (MFI->getStackProtectorIndex() == (int)i)
731       continue;
732     if (EHRegNodeFrameIndex == (int)i)
733       continue;
734     if (ProtectedObjs.count(i))
735       continue;
736 
737     // Add the objects that we need to allocate to our working set.
738     ObjectsToAllocate.push_back(i);
739   }
740 
741   // Allocate the EH registration node first if one is present.
742   if (EHRegNodeFrameIndex != INT_MAX)
743     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
744                       MaxAlign, Skew);
745 
746   // Give the targets a chance to order the objects the way they like it.
747   if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
748       Fn.getTarget().Options.StackSymbolOrdering)
749     TFI.orderFrameObjects(Fn, ObjectsToAllocate);
750 
751   // Now walk the objects and actually assign base offsets to them.
752   for (auto &Object : ObjectsToAllocate)
753     AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
754 
755   // Make sure the special register scavenging spill slot is closest to the
756   // stack pointer.
757   if (RS && !EarlyScavengingSlots) {
758     SmallVector<int, 2> SFIs;
759     RS->getScavengingFrameIndices(SFIs);
760     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
761            IE = SFIs.end(); I != IE; ++I)
762       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
763   }
764 
765   if (!TFI.targetHandlesStackFrameRounding()) {
766     // If we have reserved argument space for call sites in the function
767     // immediately on entry to the current function, count it as part of the
768     // overall stack size.
769     if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
770       Offset += MFI->getMaxCallFrameSize();
771 
772     // Round up the size to a multiple of the alignment.  If the function has
773     // any calls or alloca's, align to the target's StackAlignment value to
774     // ensure that the callee's frame or the alloca data is suitably aligned;
775     // otherwise, for leaf functions, align to the TransientStackAlignment
776     // value.
777     unsigned StackAlign;
778     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
779         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
780       StackAlign = TFI.getStackAlignment();
781     else
782       StackAlign = TFI.getTransientStackAlignment();
783 
784     // If the frame pointer is eliminated, all frame offsets will be relative to
785     // SP not FP. Align to MaxAlign so this works.
786     StackAlign = std::max(StackAlign, MaxAlign);
787     Offset = alignTo(Offset, StackAlign, Skew);
788   }
789 
790   // Update frame info to pretend that this is part of the stack...
791   int64_t StackSize = Offset - LocalAreaOffset;
792   MFI->setStackSize(StackSize);
793   NumBytesStackSpace += StackSize;
794 }
795 
796 /// insertPrologEpilogCode - Scan the function for modified callee saved
797 /// registers, insert spill code for these callee saved registers, then add
798 /// prolog and epilog code to the function.
799 ///
800 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
801   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
802 
803   // Add prologue to the function...
804   for (MachineBasicBlock *SaveBlock : SaveBlocks)
805     TFI.emitPrologue(Fn, *SaveBlock);
806 
807   // Add epilogue to restore the callee-save registers in each exiting block.
808   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
809     TFI.emitEpilogue(Fn, *RestoreBlock);
810 
811   for (MachineBasicBlock *SaveBlock : SaveBlocks)
812     TFI.inlineStackProbe(Fn, *SaveBlock);
813 
814   // Emit additional code that is required to support segmented stacks, if
815   // we've been asked for it.  This, when linked with a runtime with support
816   // for segmented stacks (libgcc is one), will result in allocating stack
817   // space in small chunks instead of one large contiguous block.
818   if (Fn.shouldSplitStack()) {
819     for (MachineBasicBlock *SaveBlock : SaveBlocks)
820       TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
821   }
822 
823   // Emit additional code that is required to explicitly handle the stack in
824   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
825   // approach is rather similar to that of Segmented Stacks, but it uses a
826   // different conditional check and another BIF for allocating more stack
827   // space.
828   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
829     for (MachineBasicBlock *SaveBlock : SaveBlocks)
830       TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
831 }
832 
833 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
834 /// register references and actual offsets.
835 ///
836 void PEI::replaceFrameIndices(MachineFunction &Fn) {
837   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
838   if (!TFI.needsFrameIndexResolution(Fn)) return;
839 
840   // Store SPAdj at exit of a basic block.
841   SmallVector<int, 8> SPState;
842   SPState.resize(Fn.getNumBlockIDs());
843   SmallPtrSet<MachineBasicBlock*, 8> Reachable;
844 
845   // Iterate over the reachable blocks in DFS order.
846   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
847        DFI != DFE; ++DFI) {
848     int SPAdj = 0;
849     // Check the exit state of the DFS stack predecessor.
850     if (DFI.getPathLength() >= 2) {
851       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
852       assert(Reachable.count(StackPred) &&
853              "DFS stack predecessor is already visited.\n");
854       SPAdj = SPState[StackPred->getNumber()];
855     }
856     MachineBasicBlock *BB = *DFI;
857     replaceFrameIndices(BB, Fn, SPAdj);
858     SPState[BB->getNumber()] = SPAdj;
859   }
860 
861   // Handle the unreachable blocks.
862   for (auto &BB : Fn) {
863     if (Reachable.count(&BB))
864       // Already handled in DFS traversal.
865       continue;
866     int SPAdj = 0;
867     replaceFrameIndices(&BB, Fn, SPAdj);
868   }
869 }
870 
871 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
872                               int &SPAdj) {
873   assert(Fn.getSubtarget().getRegisterInfo() &&
874          "getRegisterInfo() must be implemented!");
875   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
876   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
877   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
878   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
879   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
880 
881   if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(*BB);
882 
883   bool InsideCallSequence = false;
884 
885   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
886 
887     if (I->getOpcode() == FrameSetupOpcode ||
888         I->getOpcode() == FrameDestroyOpcode) {
889       InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
890       SPAdj += TII.getSPAdjust(I);
891 
892       I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
893       continue;
894     }
895 
896     MachineInstr *MI = I;
897     bool DoIncr = true;
898     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
899       if (!MI->getOperand(i).isFI())
900         continue;
901 
902       // Frame indices in debug values are encoded in a target independent
903       // way with simply the frame index and offset rather than any
904       // target-specific addressing mode.
905       if (MI->isDebugValue()) {
906         assert(i == 0 && "Frame indices can only appear as the first "
907                          "operand of a DBG_VALUE machine instruction");
908         unsigned Reg;
909         MachineOperand &Offset = MI->getOperand(1);
910         Offset.setImm(Offset.getImm() +
911                       TFI->getFrameIndexReference(
912                           Fn, MI->getOperand(0).getIndex(), Reg));
913         MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
914         continue;
915       }
916 
917       // TODO: This code should be commoned with the code for
918       // PATCHPOINT. There's no good reason for the difference in
919       // implementation other than historical accident.  The only
920       // remaining difference is the unconditional use of the stack
921       // pointer as the base register.
922       if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
923         assert((!MI->isDebugValue() || i == 0) &&
924                "Frame indicies can only appear as the first operand of a "
925                "DBG_VALUE machine instruction");
926         unsigned Reg;
927         MachineOperand &Offset = MI->getOperand(i + 1);
928         const unsigned refOffset =
929           TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
930                                             Reg);
931 
932         Offset.setImm(Offset.getImm() + refOffset);
933         MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
934         continue;
935       }
936 
937       // Some instructions (e.g. inline asm instructions) can have
938       // multiple frame indices and/or cause eliminateFrameIndex
939       // to insert more than one instruction. We need the register
940       // scavenger to go through all of these instructions so that
941       // it can update its register information. We keep the
942       // iterator at the point before insertion so that we can
943       // revisit them in full.
944       bool AtBeginning = (I == BB->begin());
945       if (!AtBeginning) --I;
946 
947       // If this instruction has a FrameIndex operand, we need to
948       // use that target machine register info object to eliminate
949       // it.
950       TRI.eliminateFrameIndex(MI, SPAdj, i,
951                               FrameIndexVirtualScavenging ?  nullptr : RS);
952 
953       // Reset the iterator if we were at the beginning of the BB.
954       if (AtBeginning) {
955         I = BB->begin();
956         DoIncr = false;
957       }
958 
959       MI = nullptr;
960       break;
961     }
962 
963     // If we are looking at a call sequence, we need to keep track of
964     // the SP adjustment made by each instruction in the sequence.
965     // This includes both the frame setup/destroy pseudos (handled above),
966     // as well as other instructions that have side effects w.r.t the SP.
967     // Note that this must come after eliminateFrameIndex, because
968     // if I itself referred to a frame index, we shouldn't count its own
969     // adjustment.
970     if (MI && InsideCallSequence)
971       SPAdj += TII.getSPAdjust(MI);
972 
973     if (DoIncr && I != BB->end()) ++I;
974 
975     // Update register states.
976     if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
977   }
978 }
979 
980 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
981 /// with physical registers. Use the register scavenger to find an
982 /// appropriate register to use.
983 ///
984 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
985 /// iterate over the vreg use list, which at this point only contains machine
986 /// operands for which eliminateFrameIndex need a new scratch reg.
987 void
988 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
989   // Run through the instructions and find any virtual registers.
990   for (MachineFunction::iterator BB = Fn.begin(),
991        E = Fn.end(); BB != E; ++BB) {
992     RS->enterBasicBlock(*BB);
993 
994     int SPAdj = 0;
995 
996     // The instruction stream may change in the loop, so check BB->end()
997     // directly.
998     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
999       // We might end up here again with a NULL iterator if we scavenged a
1000       // register for which we inserted spill code for definition by what was
1001       // originally the first instruction in BB.
1002       if (I == MachineBasicBlock::iterator(nullptr))
1003         I = BB->begin();
1004 
1005       MachineInstr *MI = I;
1006       MachineBasicBlock::iterator J = std::next(I);
1007       MachineBasicBlock::iterator P =
1008                          I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1009                                           : std::prev(I);
1010 
1011       // RS should process this instruction before we might scavenge at this
1012       // location. This is because we might be replacing a virtual register
1013       // defined by this instruction, and if so, registers killed by this
1014       // instruction are available, and defined registers are not.
1015       RS->forward(I);
1016 
1017       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1018         if (MI->getOperand(i).isReg()) {
1019           MachineOperand &MO = MI->getOperand(i);
1020           unsigned Reg = MO.getReg();
1021           if (Reg == 0)
1022             continue;
1023           if (!TargetRegisterInfo::isVirtualRegister(Reg))
1024             continue;
1025 
1026           // When we first encounter a new virtual register, it
1027           // must be a definition.
1028           assert(MI->getOperand(i).isDef() &&
1029                  "frame index virtual missing def!");
1030           // Scavenge a new scratch register
1031           const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1032           unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1033 
1034           ++NumScavengedRegs;
1035 
1036           // Replace this reference to the virtual register with the
1037           // scratch register.
1038           assert (ScratchReg && "Missing scratch register!");
1039           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1040 
1041           // Because this instruction was processed by the RS before this
1042           // register was allocated, make sure that the RS now records the
1043           // register as being used.
1044           RS->setRegUsed(ScratchReg);
1045         }
1046       }
1047 
1048       // If the scavenger needed to use one of its spill slots, the
1049       // spill code will have been inserted in between I and J. This is a
1050       // problem because we need the spill code before I: Move I to just
1051       // prior to J.
1052       if (I != std::prev(J)) {
1053         BB->splice(J, &*BB, I);
1054 
1055         // Before we move I, we need to prepare the RS to visit I again.
1056         // Specifically, RS will assert if it sees uses of registers that
1057         // it believes are undefined. Because we have already processed
1058         // register kills in I, when it visits I again, it will believe that
1059         // those registers are undefined. To avoid this situation, unprocess
1060         // the instruction I.
1061         assert(RS->getCurrentPosition() == I &&
1062           "The register scavenger has an unexpected position");
1063         I = P;
1064         RS->unprocess(P);
1065       } else
1066         ++I;
1067     }
1068   }
1069 }
1070