xref: /llvm-project/llvm/lib/CodeGen/PrologEpilogInserter.cpp (revision 263f314ba77c381f0fb9e4d3a867a863b7a78687)
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   MFI->setSavePoint(nullptr);
242   MFI->setRestorePoint(nullptr);
243   return true;
244 }
245 
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();
253 
254   unsigned MaxCallFrameSize = 0;
255   bool AdjustsStack = MFI->adjustsStack();
256 
257   // Get the function call frame set-up and tear-down instruction opcode
258   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
259   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
260 
261   // Early exit for targets which have no call frame setup/destroy pseudo
262   // instructions.
263   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
264     return;
265 
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;
275         AdjustsStack = true;
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)
281           AdjustsStack = true;
282       }
283 
284   MFI->setAdjustsStack(AdjustsStack);
285   MFI->setMaxCallFrameSize(MaxCallFrameSize);
286 
287   for (std::vector<MachineBasicBlock::iterator>::iterator
288          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
289     MachineBasicBlock::iterator I = *i;
290 
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);
297   }
298 }
299 
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;
304   MaxCSFrameIndex = 0;
305 
306   if (SavedRegs.empty())
307     return;
308 
309   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
310   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
311 
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));
317   }
318 
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.
323 
324     if (CSI.empty())
325       return; // Early exit if no callee saved registers are modified!
326 
327     unsigned NumFixedSpillSlots;
328     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
329         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
330 
331     // Now that we know which registers need to be saved and restored, allocate
332     // stack slots for them.
333     for (auto &CS : CSI) {
334       unsigned Reg = CS.getReg();
335       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
336 
337       int FrameIdx;
338       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
339         CS.setFrameIdx(FrameIdx);
340         continue;
341       }
342 
343       // Check to see if this physreg must be spilled to a particular stack slot
344       // on this target.
345       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
346       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
347              FixedSlot->Reg != Reg)
348         ++FixedSlot;
349 
350       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
351         // Nope, just spill it anywhere convenient.
352         unsigned Align = RC->getAlignment();
353         unsigned StackAlign = TFI->getStackAlignment();
354 
355         // We may not be able to satisfy the desired alignment specification of
356         // the TargetRegisterClass if the stack alignment is smaller. Use the
357         // min.
358         Align = std::min(Align, StackAlign);
359         FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
360         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
361         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
362       } else {
363         // Spill it to the stack where we must.
364         FrameIdx =
365             MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
366       }
367 
368       CS.setFrameIdx(FrameIdx);
369     }
370   }
371 
372   MFI->setCalleeSavedInfo(CSI);
373 }
374 
375 /// Helper function to update the liveness information for the callee-saved
376 /// registers.
377 static void updateLiveness(MachineFunction &MF) {
378   MachineFrameInfo *MFI = MF.getFrameInfo();
379   // Visited will contain all the basic blocks that are in the region
380   // where the callee saved registers are alive:
381   // - Anything that is not Save or Restore -> LiveThrough.
382   // - Save -> LiveIn.
383   // - Restore -> LiveOut.
384   // The live-out is not attached to the block, so no need to keep
385   // Restore in this set.
386   SmallPtrSet<MachineBasicBlock *, 8> Visited;
387   SmallVector<MachineBasicBlock *, 8> WorkList;
388   MachineBasicBlock *Entry = &MF.front();
389   MachineBasicBlock *Save = MFI->getSavePoint();
390 
391   if (!Save)
392     Save = Entry;
393 
394   if (Entry != Save) {
395     WorkList.push_back(Entry);
396     Visited.insert(Entry);
397   }
398   Visited.insert(Save);
399 
400   MachineBasicBlock *Restore = MFI->getRestorePoint();
401   if (Restore)
402     // By construction Restore cannot be visited, otherwise it
403     // means there exists a path to Restore that does not go
404     // through Save.
405     WorkList.push_back(Restore);
406 
407   while (!WorkList.empty()) {
408     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
409     // By construction, the region that is after the save point is
410     // dominated by the Save and post-dominated by the Restore.
411     if (CurBB == Save && Save != Restore)
412       continue;
413     // Enqueue all the successors not already visited.
414     // Those are by construction either before Save or after Restore.
415     for (MachineBasicBlock *SuccBB : CurBB->successors())
416       if (Visited.insert(SuccBB).second)
417         WorkList.push_back(SuccBB);
418   }
419 
420   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
421 
422   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
423     for (MachineBasicBlock *MBB : Visited) {
424       MCPhysReg Reg = CSI[i].getReg();
425       // Add the callee-saved register as live-in.
426       // It's killed at the spill.
427       if (!MBB->isLiveIn(Reg))
428         MBB->addLiveIn(Reg);
429     }
430   }
431 }
432 
433 /// insertCSRSpillsAndRestores - Insert spill and restore code for
434 /// callee saved registers used in the function.
435 ///
436 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
437   // Get callee saved register information.
438   MachineFrameInfo *MFI = Fn.getFrameInfo();
439   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
440 
441   MFI->setCalleeSavedInfoValid(true);
442 
443   // Early exit if no callee saved registers are modified!
444   if (CSI.empty())
445     return;
446 
447   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
448   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
449   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
450   MachineBasicBlock::iterator I;
451 
452   // Spill using target interface.
453   for (MachineBasicBlock *SaveBlock : SaveBlocks) {
454     I = SaveBlock->begin();
455     if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
456       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
457         // Insert the spill to the stack frame.
458         unsigned Reg = CSI[i].getReg();
459         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
460         TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
461                                 RC, TRI);
462       }
463     }
464     // Update the live-in information of all the blocks up to the save point.
465     updateLiveness(Fn);
466   }
467 
468   // Restore using target interface.
469   for (MachineBasicBlock *MBB : RestoreBlocks) {
470     I = MBB->end();
471 
472     // Skip over all terminator instructions, which are part of the return
473     // sequence.
474     MachineBasicBlock::iterator I2 = I;
475     while (I2 != MBB->begin() && (--I2)->isTerminator())
476       I = I2;
477 
478     bool AtStart = I == MBB->begin();
479     MachineBasicBlock::iterator BeforeI = I;
480     if (!AtStart)
481       --BeforeI;
482 
483     // Restore all registers immediately before the return and any
484     // terminators that precede it.
485     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
486       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
487         unsigned Reg = CSI[i].getReg();
488         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
489         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
490         assert(I != MBB->begin() &&
491                "loadRegFromStackSlot didn't insert any code!");
492         // Insert in reverse order.  loadRegFromStackSlot can insert
493         // multiple instructions.
494         if (AtStart)
495           I = MBB->begin();
496         else {
497           I = BeforeI;
498           ++I;
499         }
500       }
501     }
502   }
503 }
504 
505 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
506 static inline void
507 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
508                   bool StackGrowsDown, int64_t &Offset,
509                   unsigned &MaxAlign, unsigned Skew) {
510   // If the stack grows down, add the object size to find the lowest address.
511   if (StackGrowsDown)
512     Offset += MFI->getObjectSize(FrameIdx);
513 
514   unsigned Align = MFI->getObjectAlignment(FrameIdx);
515 
516   // If the alignment of this object is greater than that of the stack, then
517   // increase the stack alignment to match.
518   MaxAlign = std::max(MaxAlign, Align);
519 
520   // Adjust to alignment boundary.
521   Offset = alignTo(Offset, Align, Skew);
522 
523   if (StackGrowsDown) {
524     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
525     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
526   } else {
527     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
528     MFI->setObjectOffset(FrameIdx, Offset);
529     Offset += MFI->getObjectSize(FrameIdx);
530   }
531 }
532 
533 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
534 /// those required to be close to the Stack Protector) to stack offsets.
535 static void
536 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
537                       SmallSet<int, 16> &ProtectedObjs,
538                       MachineFrameInfo *MFI, bool StackGrowsDown,
539                       int64_t &Offset, unsigned &MaxAlign, unsigned Skew) {
540 
541   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
542         E = UnassignedObjs.end(); I != E; ++I) {
543     int i = *I;
544     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew);
545     ProtectedObjs.insert(i);
546   }
547 }
548 
549 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
550 /// abstract stack objects.
551 ///
552 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
553   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
554   StackProtector *SP = &getAnalysis<StackProtector>();
555 
556   bool StackGrowsDown =
557     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
558 
559   // Loop over all of the stack objects, assigning sequential addresses...
560   MachineFrameInfo *MFI = Fn.getFrameInfo();
561 
562   // Start at the beginning of the local area.
563   // The Offset is the distance from the stack top in the direction
564   // of stack growth -- so it's always nonnegative.
565   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
566   if (StackGrowsDown)
567     LocalAreaOffset = -LocalAreaOffset;
568   assert(LocalAreaOffset >= 0
569          && "Local area offset should be in direction of stack growth");
570   int64_t Offset = LocalAreaOffset;
571 
572   // Skew to be applied to alignment.
573   unsigned Skew = TFI.getStackAlignmentSkew(Fn);
574 
575   // If there are fixed sized objects that are preallocated in the local area,
576   // non-fixed objects can't be allocated right at the start of local area.
577   // We currently don't support filling in holes in between fixed sized
578   // objects, so we adjust 'Offset' to point to the end of last fixed sized
579   // preallocated object.
580   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
581     int64_t FixedOff;
582     if (StackGrowsDown) {
583       // The maximum distance from the stack pointer is at lower address of
584       // the object -- which is given by offset. For down growing stack
585       // the offset is negative, so we negate the offset to get the distance.
586       FixedOff = -MFI->getObjectOffset(i);
587     } else {
588       // The maximum distance from the start pointer is at the upper
589       // address of the object.
590       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
591     }
592     if (FixedOff > Offset) Offset = FixedOff;
593   }
594 
595   // First assign frame offsets to stack objects that are used to spill
596   // callee saved registers.
597   if (StackGrowsDown) {
598     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
599       // If the stack grows down, we need to add the size to find the lowest
600       // address of the object.
601       Offset += MFI->getObjectSize(i);
602 
603       unsigned Align = MFI->getObjectAlignment(i);
604       // Adjust to alignment boundary
605       Offset = alignTo(Offset, Align, Skew);
606 
607       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n");
608       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
609     }
610   } else {
611     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
612     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
613       unsigned Align = MFI->getObjectAlignment(i);
614       // Adjust to alignment boundary
615       Offset = alignTo(Offset, Align, Skew);
616 
617       DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n");
618       MFI->setObjectOffset(i, Offset);
619       Offset += MFI->getObjectSize(i);
620     }
621   }
622 
623   unsigned MaxAlign = MFI->getMaxAlignment();
624 
625   // Make sure the special register scavenging spill slot is closest to the
626   // incoming stack pointer if a frame pointer is required and is closer
627   // to the incoming rather than the final stack pointer.
628   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
629   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
630                                TFI.isFPCloseToIncomingSP() &&
631                                RegInfo->useFPForScavengingIndex(Fn) &&
632                                !RegInfo->needsStackRealignment(Fn));
633   if (RS && EarlyScavengingSlots) {
634     SmallVector<int, 2> SFIs;
635     RS->getScavengingFrameIndices(SFIs);
636     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
637            IE = SFIs.end(); I != IE; ++I)
638       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
639   }
640 
641   // FIXME: Once this is working, then enable flag will change to a target
642   // check for whether the frame is large enough to want to use virtual
643   // frame index registers. Functions which don't want/need this optimization
644   // will continue to use the existing code path.
645   if (MFI->getUseLocalStackAllocationBlock()) {
646     unsigned Align = MFI->getLocalFrameMaxAlign();
647 
648     // Adjust to alignment boundary.
649     Offset = alignTo(Offset, Align, Skew);
650 
651     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
652 
653     // Resolve offsets for objects in the local block.
654     for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
655       std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
656       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
657       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
658             FIOffset << "]\n");
659       MFI->setObjectOffset(Entry.first, FIOffset);
660     }
661     // Allocate the local block
662     Offset += MFI->getLocalFrameSize();
663 
664     MaxAlign = std::max(Align, MaxAlign);
665   }
666 
667   // Make sure that the stack protector comes before the local variables on the
668   // stack.
669   SmallSet<int, 16> ProtectedObjs;
670   if (MFI->getStackProtectorIndex() >= 0) {
671     StackObjSet LargeArrayObjs;
672     StackObjSet SmallArrayObjs;
673     StackObjSet AddrOfObjs;
674 
675     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
676                       Offset, MaxAlign, Skew);
677 
678     // Assign large stack objects first.
679     for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
680       if (MFI->isObjectPreAllocated(i) &&
681           MFI->getUseLocalStackAllocationBlock())
682         continue;
683       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
684         continue;
685       if (RS && RS->isScavengingFrameIndex((int)i))
686         continue;
687       if (MFI->isDeadObjectIndex(i))
688         continue;
689       if (MFI->getStackProtectorIndex() == (int)i)
690         continue;
691 
692       switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
693       case StackProtector::SSPLK_None:
694         continue;
695       case StackProtector::SSPLK_SmallArray:
696         SmallArrayObjs.insert(i);
697         continue;
698       case StackProtector::SSPLK_AddrOf:
699         AddrOfObjs.insert(i);
700         continue;
701       case StackProtector::SSPLK_LargeArray:
702         LargeArrayObjs.insert(i);
703         continue;
704       }
705       llvm_unreachable("Unexpected SSPLayoutKind.");
706     }
707 
708     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
709                           Offset, MaxAlign, Skew);
710     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
711                           Offset, MaxAlign, Skew);
712     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
713                           Offset, MaxAlign, Skew);
714   }
715 
716   SmallVector<int, 8> ObjectsToAllocate;
717 
718   int EHRegNodeFrameIndex = INT_MAX;
719   if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo())
720     EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
721 
722   // Then prepare to assign frame offsets to stack objects that are not used to
723   // spill callee saved registers.
724   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
725     if (MFI->isObjectPreAllocated(i) &&
726         MFI->getUseLocalStackAllocationBlock())
727       continue;
728     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
729       continue;
730     if (RS && RS->isScavengingFrameIndex((int)i))
731       continue;
732     if (MFI->isDeadObjectIndex(i))
733       continue;
734     if (MFI->getStackProtectorIndex() == (int)i)
735       continue;
736     if (EHRegNodeFrameIndex == (int)i)
737       continue;
738     if (ProtectedObjs.count(i))
739       continue;
740 
741     // Add the objects that we need to allocate to our working set.
742     ObjectsToAllocate.push_back(i);
743   }
744 
745   // Allocate the EH registration node first if one is present.
746   if (EHRegNodeFrameIndex != INT_MAX)
747     AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
748                       MaxAlign, Skew);
749 
750   // Give the targets a chance to order the objects the way they like it.
751   if (Fn.getTarget().getOptLevel() != CodeGenOpt::None &&
752       Fn.getTarget().Options.StackSymbolOrdering)
753     TFI.orderFrameObjects(Fn, ObjectsToAllocate);
754 
755   // Now walk the objects and actually assign base offsets to them.
756   for (auto &Object : ObjectsToAllocate)
757     AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew);
758 
759   // Make sure the special register scavenging spill slot is closest to the
760   // stack pointer.
761   if (RS && !EarlyScavengingSlots) {
762     SmallVector<int, 2> SFIs;
763     RS->getScavengingFrameIndices(SFIs);
764     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
765            IE = SFIs.end(); I != IE; ++I)
766       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew);
767   }
768 
769   if (!TFI.targetHandlesStackFrameRounding()) {
770     // If we have reserved argument space for call sites in the function
771     // immediately on entry to the current function, count it as part of the
772     // overall stack size.
773     if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
774       Offset += MFI->getMaxCallFrameSize();
775 
776     // Round up the size to a multiple of the alignment.  If the function has
777     // any calls or alloca's, align to the target's StackAlignment value to
778     // ensure that the callee's frame or the alloca data is suitably aligned;
779     // otherwise, for leaf functions, align to the TransientStackAlignment
780     // value.
781     unsigned StackAlign;
782     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
783         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
784       StackAlign = TFI.getStackAlignment();
785     else
786       StackAlign = TFI.getTransientStackAlignment();
787 
788     // If the frame pointer is eliminated, all frame offsets will be relative to
789     // SP not FP. Align to MaxAlign so this works.
790     StackAlign = std::max(StackAlign, MaxAlign);
791     Offset = alignTo(Offset, StackAlign, Skew);
792   }
793 
794   // Update frame info to pretend that this is part of the stack...
795   int64_t StackSize = Offset - LocalAreaOffset;
796   MFI->setStackSize(StackSize);
797   NumBytesStackSpace += StackSize;
798 }
799 
800 /// insertPrologEpilogCode - Scan the function for modified callee saved
801 /// registers, insert spill code for these callee saved registers, then add
802 /// prolog and epilog code to the function.
803 ///
804 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
805   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
806 
807   // Add prologue to the function...
808   for (MachineBasicBlock *SaveBlock : SaveBlocks)
809     TFI.emitPrologue(Fn, *SaveBlock);
810 
811   // Add epilogue to restore the callee-save registers in each exiting block.
812   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
813     TFI.emitEpilogue(Fn, *RestoreBlock);
814 
815   for (MachineBasicBlock *SaveBlock : SaveBlocks)
816     TFI.inlineStackProbe(Fn, *SaveBlock);
817 
818   // Emit additional code that is required to support segmented stacks, if
819   // we've been asked for it.  This, when linked with a runtime with support
820   // for segmented stacks (libgcc is one), will result in allocating stack
821   // space in small chunks instead of one large contiguous block.
822   if (Fn.shouldSplitStack()) {
823     for (MachineBasicBlock *SaveBlock : SaveBlocks)
824       TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
825   }
826 
827   // Emit additional code that is required to explicitly handle the stack in
828   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
829   // approach is rather similar to that of Segmented Stacks, but it uses a
830   // different conditional check and another BIF for allocating more stack
831   // space.
832   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
833     for (MachineBasicBlock *SaveBlock : SaveBlocks)
834       TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
835 }
836 
837 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
838 /// register references and actual offsets.
839 ///
840 void PEI::replaceFrameIndices(MachineFunction &Fn) {
841   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
842   if (!TFI.needsFrameIndexResolution(Fn)) return;
843 
844   // Store SPAdj at exit of a basic block.
845   SmallVector<int, 8> SPState;
846   SPState.resize(Fn.getNumBlockIDs());
847   SmallPtrSet<MachineBasicBlock*, 8> Reachable;
848 
849   // Iterate over the reachable blocks in DFS order.
850   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
851        DFI != DFE; ++DFI) {
852     int SPAdj = 0;
853     // Check the exit state of the DFS stack predecessor.
854     if (DFI.getPathLength() >= 2) {
855       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
856       assert(Reachable.count(StackPred) &&
857              "DFS stack predecessor is already visited.\n");
858       SPAdj = SPState[StackPred->getNumber()];
859     }
860     MachineBasicBlock *BB = *DFI;
861     replaceFrameIndices(BB, Fn, SPAdj);
862     SPState[BB->getNumber()] = SPAdj;
863   }
864 
865   // Handle the unreachable blocks.
866   for (auto &BB : Fn) {
867     if (Reachable.count(&BB))
868       // Already handled in DFS traversal.
869       continue;
870     int SPAdj = 0;
871     replaceFrameIndices(&BB, Fn, SPAdj);
872   }
873 }
874 
875 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
876                               int &SPAdj) {
877   assert(Fn.getSubtarget().getRegisterInfo() &&
878          "getRegisterInfo() must be implemented!");
879   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
880   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
881   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
882   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
883   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
884 
885   if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(*BB);
886 
887   bool InsideCallSequence = false;
888 
889   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
890 
891     if (I->getOpcode() == FrameSetupOpcode ||
892         I->getOpcode() == FrameDestroyOpcode) {
893       InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
894       SPAdj += TII.getSPAdjust(I);
895 
896       I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
897       continue;
898     }
899 
900     MachineInstr *MI = I;
901     bool DoIncr = true;
902     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
903       if (!MI->getOperand(i).isFI())
904         continue;
905 
906       // Frame indices in debug values are encoded in a target independent
907       // way with simply the frame index and offset rather than any
908       // target-specific addressing mode.
909       if (MI->isDebugValue()) {
910         assert(i == 0 && "Frame indices can only appear as the first "
911                          "operand of a DBG_VALUE machine instruction");
912         unsigned Reg;
913         MachineOperand &Offset = MI->getOperand(1);
914         Offset.setImm(Offset.getImm() +
915                       TFI->getFrameIndexReference(
916                           Fn, MI->getOperand(0).getIndex(), Reg));
917         MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
918         continue;
919       }
920 
921       // TODO: This code should be commoned with the code for
922       // PATCHPOINT. There's no good reason for the difference in
923       // implementation other than historical accident.  The only
924       // remaining difference is the unconditional use of the stack
925       // pointer as the base register.
926       if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
927         assert((!MI->isDebugValue() || i == 0) &&
928                "Frame indicies can only appear as the first operand of a "
929                "DBG_VALUE machine instruction");
930         unsigned Reg;
931         MachineOperand &Offset = MI->getOperand(i + 1);
932         const unsigned refOffset =
933           TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
934                                             Reg);
935 
936         Offset.setImm(Offset.getImm() + refOffset);
937         MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
938         continue;
939       }
940 
941       // Some instructions (e.g. inline asm instructions) can have
942       // multiple frame indices and/or cause eliminateFrameIndex
943       // to insert more than one instruction. We need the register
944       // scavenger to go through all of these instructions so that
945       // it can update its register information. We keep the
946       // iterator at the point before insertion so that we can
947       // revisit them in full.
948       bool AtBeginning = (I == BB->begin());
949       if (!AtBeginning) --I;
950 
951       // If this instruction has a FrameIndex operand, we need to
952       // use that target machine register info object to eliminate
953       // it.
954       TRI.eliminateFrameIndex(MI, SPAdj, i,
955                               FrameIndexVirtualScavenging ?  nullptr : RS);
956 
957       // Reset the iterator if we were at the beginning of the BB.
958       if (AtBeginning) {
959         I = BB->begin();
960         DoIncr = false;
961       }
962 
963       MI = nullptr;
964       break;
965     }
966 
967     // If we are looking at a call sequence, we need to keep track of
968     // the SP adjustment made by each instruction in the sequence.
969     // This includes both the frame setup/destroy pseudos (handled above),
970     // as well as other instructions that have side effects w.r.t the SP.
971     // Note that this must come after eliminateFrameIndex, because
972     // if I itself referred to a frame index, we shouldn't count its own
973     // adjustment.
974     if (MI && InsideCallSequence)
975       SPAdj += TII.getSPAdjust(MI);
976 
977     if (DoIncr && I != BB->end()) ++I;
978 
979     // Update register states.
980     if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
981   }
982 }
983 
984 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
985 /// with physical registers. Use the register scavenger to find an
986 /// appropriate register to use.
987 ///
988 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
989 /// iterate over the vreg use list, which at this point only contains machine
990 /// operands for which eliminateFrameIndex need a new scratch reg.
991 void
992 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
993   // Run through the instructions and find any virtual registers.
994   for (MachineFunction::iterator BB = Fn.begin(),
995        E = Fn.end(); BB != E; ++BB) {
996     RS->enterBasicBlock(*BB);
997 
998     int SPAdj = 0;
999 
1000     // The instruction stream may change in the loop, so check BB->end()
1001     // directly.
1002     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1003       // We might end up here again with a NULL iterator if we scavenged a
1004       // register for which we inserted spill code for definition by what was
1005       // originally the first instruction in BB.
1006       if (I == MachineBasicBlock::iterator(nullptr))
1007         I = BB->begin();
1008 
1009       MachineInstr *MI = I;
1010       MachineBasicBlock::iterator J = std::next(I);
1011       MachineBasicBlock::iterator P =
1012                          I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1013                                           : std::prev(I);
1014 
1015       // RS should process this instruction before we might scavenge at this
1016       // location. This is because we might be replacing a virtual register
1017       // defined by this instruction, and if so, registers killed by this
1018       // instruction are available, and defined registers are not.
1019       RS->forward(I);
1020 
1021       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1022         if (MI->getOperand(i).isReg()) {
1023           MachineOperand &MO = MI->getOperand(i);
1024           unsigned Reg = MO.getReg();
1025           if (Reg == 0)
1026             continue;
1027           if (!TargetRegisterInfo::isVirtualRegister(Reg))
1028             continue;
1029 
1030           // When we first encounter a new virtual register, it
1031           // must be a definition.
1032           assert(MI->getOperand(i).isDef() &&
1033                  "frame index virtual missing def!");
1034           // Scavenge a new scratch register
1035           const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1036           unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1037 
1038           ++NumScavengedRegs;
1039 
1040           // Replace this reference to the virtual register with the
1041           // scratch register.
1042           assert (ScratchReg && "Missing scratch register!");
1043           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1044 
1045           // Because this instruction was processed by the RS before this
1046           // register was allocated, make sure that the RS now records the
1047           // register as being used.
1048           RS->setRegUsed(ScratchReg);
1049         }
1050       }
1051 
1052       // If the scavenger needed to use one of its spill slots, the
1053       // spill code will have been inserted in between I and J. This is a
1054       // problem because we need the spill code before I: Move I to just
1055       // prior to J.
1056       if (I != std::prev(J)) {
1057         BB->splice(J, &*BB, I);
1058 
1059         // Before we move I, we need to prepare the RS to visit I again.
1060         // Specifically, RS will assert if it sees uses of registers that
1061         // it believes are undefined. Because we have already processed
1062         // register kills in I, when it visits I again, it will believe that
1063         // those registers are undefined. To avoid this situation, unprocess
1064         // the instruction I.
1065         assert(RS->getCurrentPosition() == I &&
1066           "The register scavenger has an unexpected position");
1067         I = P;
1068         RS->unprocess(P);
1069       } else
1070         ++I;
1071     }
1072   }
1073 }
1074