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