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   /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
63   /// frame indexes with appropriate references.
64   ///
65   bool runOnMachineFunction(MachineFunction &Fn) override;
66 
67 private:
68   RegScavenger *RS;
69 
70   // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
71   // stack frame indexes.
72   unsigned MinCSFrameIndex, MaxCSFrameIndex;
73 
74   // Save and Restore blocks of the current function.
75   MachineBasicBlock *SaveBlock;
76   SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
77 
78   // Flag to control whether to use the register scavenger to resolve
79   // frame index materialization registers. Set according to
80   // TRI->requiresFrameIndexScavenging() for the current function.
81   bool FrameIndexVirtualScavenging;
82 
83   void calculateSets(MachineFunction &Fn);
84   void calculateCallsInformation(MachineFunction &Fn);
85   void calculateCalleeSavedRegisters(MachineFunction &Fn);
86   void insertCSRSpillsAndRestores(MachineFunction &Fn);
87   void calculateFrameObjectOffsets(MachineFunction &Fn);
88   void replaceFrameIndices(MachineFunction &Fn);
89   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
90                            int &SPAdj);
91   void scavengeFrameVirtualRegs(MachineFunction &Fn);
92   void insertPrologEpilogCode(MachineFunction &Fn);
93 
94   // Convenience for recognizing return blocks.
95   bool isReturnBlock(const MachineBasicBlock *MBB) const;
96 };
97 } // namespace
98 
99 char PEI::ID = 0;
100 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
101 
102 static cl::opt<unsigned>
103 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
104               cl::desc("Warn for stack size bigger than the given"
105                        " number"));
106 
107 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
108                 "Prologue/Epilogue Insertion", false, false)
109 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
110 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
111 INITIALIZE_PASS_DEPENDENCY(StackProtector)
112 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
113 INITIALIZE_PASS_END(PEI, "prologepilog",
114                     "Prologue/Epilogue Insertion & Frame Finalization",
115                     false, false)
116 
117 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
118 STATISTIC(NumBytesStackSpace,
119           "Number of bytes used for stack in all functions");
120 
121 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
122   AU.setPreservesCFG();
123   AU.addPreserved<MachineLoopInfo>();
124   AU.addPreserved<MachineDominatorTree>();
125   AU.addRequired<StackProtector>();
126   AU.addRequired<TargetPassConfig>();
127   MachineFunctionPass::getAnalysisUsage(AU);
128 }
129 
130 bool PEI::isReturnBlock(const MachineBasicBlock* MBB) const {
131   return (MBB && !MBB->empty() && MBB->back().isReturn());
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     SaveBlock = 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() || isReturnBlock(RestoreBlock))
151       RestoreBlocks.push_back(RestoreBlock);
152     return;
153   }
154 
155   // Save refs to entry and return blocks.
156   SaveBlock = Fn.begin();
157   for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
158        MBB != E; ++MBB)
159     if (isReturnBlock(MBB))
160       RestoreBlocks.push_back(MBB);
161 
162   return;
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   // Allow the target machine to make some adjustments to the function
187   // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
188   TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
189 
190   // Scan the function for modified callee saved registers and insert spill code
191   // for any callee saved registers that are modified.
192   calculateCalleeSavedRegisters(Fn);
193 
194   // Determine placement of CSR spill/restore code:
195   // place all spills in the entry block, all restores in return blocks.
196   calculateSets(Fn);
197 
198   // Add the code to save and restore the callee saved registers
199   if (!F->hasFnAttribute(Attribute::Naked))
200     insertCSRSpillsAndRestores(Fn);
201 
202   // Allow the target machine to make final modifications to the function
203   // before the frame layout is finalized.
204   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
205 
206   // Calculate actual frame offsets for all abstract stack objects...
207   calculateFrameObjectOffsets(Fn);
208 
209   // Add prolog and epilog code to the function.  This function is required
210   // to align the stack frame as necessary for any stack variables or
211   // called functions.  Because of this, calculateCalleeSavedRegisters()
212   // must be called before this function in order to set the AdjustsStack
213   // and MaxCallFrameSize variables.
214   if (!F->hasFnAttribute(Attribute::Naked))
215     insertPrologEpilogCode(Fn);
216 
217   // Replace all MO_FrameIndex operands with physical register references
218   // and actual offsets.
219   //
220   replaceFrameIndices(Fn);
221 
222   // If register scavenging is needed, as we've enabled doing it as a
223   // post-pass, scavenge the virtual registers that frame index elimination
224   // inserted.
225   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
226     scavengeFrameVirtualRegs(Fn);
227 
228   // Clear any vregs created by virtual scavenging.
229   Fn.getRegInfo().clearVirtRegs();
230 
231   // Warn on stack size when we exceeds the given limit.
232   MachineFrameInfo *MFI = Fn.getFrameInfo();
233   uint64_t StackSize = MFI->getStackSize();
234   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
235     DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
236     F->getContext().diagnose(DiagStackSize);
237   }
238 
239   delete RS;
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 
299 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
300 /// registers.
301 void PEI::calculateCalleeSavedRegisters(MachineFunction &F) {
302   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
303   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
304   MachineFrameInfo *MFI = F.getFrameInfo();
305 
306   // Get the callee saved register list...
307   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
308 
309   // These are used to keep track the callee-save area. Initialize them.
310   MinCSFrameIndex = INT_MAX;
311   MaxCSFrameIndex = 0;
312 
313   // Early exit for targets which have no callee saved registers.
314   if (!CSRegs || CSRegs[0] == 0)
315     return;
316 
317   // In Naked functions we aren't going to save any registers.
318   if (F.getFunction()->hasFnAttribute(Attribute::Naked))
319     return;
320 
321   std::vector<CalleeSavedInfo> CSI;
322   for (unsigned i = 0; CSRegs[i]; ++i) {
323     unsigned Reg = CSRegs[i];
324     // Functions which call __builtin_unwind_init get all their registers saved.
325     if (F.getRegInfo().isPhysRegUsed(Reg) || F.getMMI().callsUnwindInit()) {
326       // If the reg is modified, save it!
327       CSI.push_back(CalleeSavedInfo(Reg));
328     }
329   }
330 
331   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
332     // If target doesn't implement this, use generic code.
333 
334     if (CSI.empty())
335       return; // Early exit if no callee saved registers are modified!
336 
337     unsigned NumFixedSpillSlots;
338     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
339         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
340 
341     // Now that we know which registers need to be saved and restored, allocate
342     // stack slots for them.
343     for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
344          I != E; ++I) {
345       unsigned Reg = I->getReg();
346       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
347 
348       int FrameIdx;
349       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
350         I->setFrameIdx(FrameIdx);
351         continue;
352       }
353 
354       // Check to see if this physreg must be spilled to a particular stack slot
355       // on this target.
356       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
357       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
358              FixedSlot->Reg != Reg)
359         ++FixedSlot;
360 
361       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
362         // Nope, just spill it anywhere convenient.
363         unsigned Align = RC->getAlignment();
364         unsigned StackAlign = TFI->getStackAlignment();
365 
366         // We may not be able to satisfy the desired alignment specification of
367         // the TargetRegisterClass if the stack alignment is smaller. Use the
368         // min.
369         Align = std::min(Align, StackAlign);
370         FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
371         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
372         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
373       } else {
374         // Spill it to the stack where we must.
375         FrameIdx =
376             MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
377       }
378 
379       I->setFrameIdx(FrameIdx);
380     }
381   }
382 
383   MFI->setCalleeSavedInfo(CSI);
384 }
385 
386 /// Helper function to update the liveness information for the callee-saved
387 /// registers.
388 static void updateLiveness(MachineFunction &MF) {
389   MachineFrameInfo *MFI = MF.getFrameInfo();
390   // Visited will contain all the basic blocks that are in the region
391   // where the callee saved registers are alive:
392   // - Anything that is not Save or Restore -> LiveThrough.
393   // - Save -> LiveIn.
394   // - Restore -> LiveOut.
395   // The live-out is not attached to the block, so no need to keep
396   // Restore in this set.
397   SmallPtrSet<MachineBasicBlock *, 8> Visited;
398   SmallVector<MachineBasicBlock *, 8> WorkList;
399   MachineBasicBlock *Entry = &MF.front();
400   MachineBasicBlock *Save = MFI->getSavePoint();
401 
402   if (!Save)
403     Save = Entry;
404 
405   if (Entry != Save) {
406     WorkList.push_back(Entry);
407     Visited.insert(Entry);
408   }
409   Visited.insert(Save);
410 
411   MachineBasicBlock *Restore = MFI->getRestorePoint();
412   if (Restore)
413     // By construction Restore cannot be visited, otherwise it
414     // means there exists a path to Restore that does not go
415     // through Save.
416     WorkList.push_back(Restore);
417 
418   while (!WorkList.empty()) {
419     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
420     // By construction, the region that is after the save point is
421     // dominated by the Save and post-dominated by the Restore.
422     if (CurBB == Save)
423       continue;
424     // Enqueue all the successors not already visited.
425     // Those are by construction either before Save or after Restore.
426     for (MachineBasicBlock *SuccBB : CurBB->successors())
427       if (Visited.insert(SuccBB).second)
428         WorkList.push_back(SuccBB);
429   }
430 
431   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
432 
433   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
434     for (MachineBasicBlock *MBB : Visited)
435       // Add the callee-saved register as live-in.
436       // It's killed at the spill.
437       MBB->addLiveIn(CSI[i].getReg());
438   }
439 }
440 
441 /// insertCSRSpillsAndRestores - Insert spill and restore code for
442 /// callee saved registers used in the function.
443 ///
444 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
445   // Get callee saved register information.
446   MachineFrameInfo *MFI = Fn.getFrameInfo();
447   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
448 
449   MFI->setCalleeSavedInfoValid(true);
450 
451   // Early exit if no callee saved registers are modified!
452   if (CSI.empty())
453     return;
454 
455   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
456   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
457   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
458   MachineBasicBlock::iterator I;
459 
460   // Spill using target interface.
461   I = SaveBlock->begin();
462   if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
463     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
464       // Insert the spill to the stack frame.
465       unsigned Reg = CSI[i].getReg();
466       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
467       TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
468                               RC, TRI);
469     }
470   }
471   // Update the live-in information of all the blocks up to the save point.
472   updateLiveness(Fn);
473 
474   // Restore using target interface.
475   for (MachineBasicBlock *MBB : RestoreBlocks) {
476     I = MBB->end();
477 
478     // Skip over all terminator instructions, which are part of the return
479     // sequence.
480     MachineBasicBlock::iterator I2 = I;
481     while (I2 != MBB->begin() && (--I2)->isTerminator())
482       I = I2;
483 
484     bool AtStart = I == MBB->begin();
485     MachineBasicBlock::iterator BeforeI = I;
486     if (!AtStart)
487       --BeforeI;
488 
489     // Restore all registers immediately before the return and any
490     // terminators that precede it.
491     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
492       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
493         unsigned Reg = CSI[i].getReg();
494         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
495         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
496         assert(I != MBB->begin() &&
497                "loadRegFromStackSlot didn't insert any code!");
498         // Insert in reverse order.  loadRegFromStackSlot can insert
499         // multiple instructions.
500         if (AtStart)
501           I = MBB->begin();
502         else {
503           I = BeforeI;
504           ++I;
505         }
506       }
507     }
508   }
509 }
510 
511 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
512 static inline void
513 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
514                   bool StackGrowsDown, int64_t &Offset,
515                   unsigned &MaxAlign) {
516   // If the stack grows down, add the object size to find the lowest address.
517   if (StackGrowsDown)
518     Offset += MFI->getObjectSize(FrameIdx);
519 
520   unsigned Align = MFI->getObjectAlignment(FrameIdx);
521 
522   // If the alignment of this object is greater than that of the stack, then
523   // increase the stack alignment to match.
524   MaxAlign = std::max(MaxAlign, Align);
525 
526   // Adjust to alignment boundary.
527   Offset = (Offset + Align - 1) / Align * Align;
528 
529   if (StackGrowsDown) {
530     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
531     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
532   } else {
533     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
534     MFI->setObjectOffset(FrameIdx, Offset);
535     Offset += MFI->getObjectSize(FrameIdx);
536   }
537 }
538 
539 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
540 /// those required to be close to the Stack Protector) to stack offsets.
541 static void
542 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
543                       SmallSet<int, 16> &ProtectedObjs,
544                       MachineFrameInfo *MFI, bool StackGrowsDown,
545                       int64_t &Offset, unsigned &MaxAlign) {
546 
547   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
548         E = UnassignedObjs.end(); I != E; ++I) {
549     int i = *I;
550     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
551     ProtectedObjs.insert(i);
552   }
553 }
554 
555 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
556 /// abstract stack objects.
557 ///
558 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
559   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
560   StackProtector *SP = &getAnalysis<StackProtector>();
561 
562   bool StackGrowsDown =
563     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
564 
565   // Loop over all of the stack objects, assigning sequential addresses...
566   MachineFrameInfo *MFI = Fn.getFrameInfo();
567 
568   // Start at the beginning of the local area.
569   // The Offset is the distance from the stack top in the direction
570   // of stack growth -- so it's always nonnegative.
571   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
572   if (StackGrowsDown)
573     LocalAreaOffset = -LocalAreaOffset;
574   assert(LocalAreaOffset >= 0
575          && "Local area offset should be in direction of stack growth");
576   int64_t Offset = LocalAreaOffset;
577 
578   // If there are fixed sized objects that are preallocated in the local area,
579   // non-fixed objects can't be allocated right at the start of local area.
580   // We currently don't support filling in holes in between fixed sized
581   // objects, so we adjust 'Offset' to point to the end of last fixed sized
582   // preallocated object.
583   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
584     int64_t FixedOff;
585     if (StackGrowsDown) {
586       // The maximum distance from the stack pointer is at lower address of
587       // the object -- which is given by offset. For down growing stack
588       // the offset is negative, so we negate the offset to get the distance.
589       FixedOff = -MFI->getObjectOffset(i);
590     } else {
591       // The maximum distance from the start pointer is at the upper
592       // address of the object.
593       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
594     }
595     if (FixedOff > Offset) Offset = FixedOff;
596   }
597 
598   // First assign frame offsets to stack objects that are used to spill
599   // callee saved registers.
600   if (StackGrowsDown) {
601     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
602       // If the stack grows down, we need to add the size to find the lowest
603       // address of the object.
604       Offset += MFI->getObjectSize(i);
605 
606       unsigned Align = MFI->getObjectAlignment(i);
607       // Adjust to alignment boundary
608       Offset = RoundUpToAlignment(Offset, Align);
609 
610       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
611     }
612   } else {
613     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
614     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
615       unsigned Align = MFI->getObjectAlignment(i);
616       // Adjust to alignment boundary
617       Offset = RoundUpToAlignment(Offset, Align);
618 
619       MFI->setObjectOffset(i, Offset);
620       Offset += MFI->getObjectSize(i);
621     }
622   }
623 
624   unsigned MaxAlign = MFI->getMaxAlignment();
625 
626   // Make sure the special register scavenging spill slot is closest to the
627   // incoming stack pointer if a frame pointer is required and is closer
628   // to the incoming rather than the final stack pointer.
629   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
630   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
631                                TFI.isFPCloseToIncomingSP() &&
632                                RegInfo->useFPForScavengingIndex(Fn) &&
633                                !RegInfo->needsStackRealignment(Fn));
634   if (RS && EarlyScavengingSlots) {
635     SmallVector<int, 2> SFIs;
636     RS->getScavengingFrameIndices(SFIs);
637     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
638            IE = SFIs.end(); I != IE; ++I)
639       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
640   }
641 
642   // FIXME: Once this is working, then enable flag will change to a target
643   // check for whether the frame is large enough to want to use virtual
644   // frame index registers. Functions which don't want/need this optimization
645   // will continue to use the existing code path.
646   if (MFI->getUseLocalStackAllocationBlock()) {
647     unsigned Align = MFI->getLocalFrameMaxAlign();
648 
649     // Adjust to alignment boundary.
650     Offset = RoundUpToAlignment(Offset, Align);
651 
652     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
653 
654     // Resolve offsets for objects in the local block.
655     for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
656       std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
657       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
658       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
659             FIOffset << "]\n");
660       MFI->setObjectOffset(Entry.first, FIOffset);
661     }
662     // Allocate the local block
663     Offset += MFI->getLocalFrameSize();
664 
665     MaxAlign = std::max(Align, MaxAlign);
666   }
667 
668   // Make sure that the stack protector comes before the local variables on the
669   // stack.
670   SmallSet<int, 16> ProtectedObjs;
671   if (MFI->getStackProtectorIndex() >= 0) {
672     StackObjSet LargeArrayObjs;
673     StackObjSet SmallArrayObjs;
674     StackObjSet AddrOfObjs;
675 
676     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
677                       Offset, MaxAlign);
678 
679     // Assign large stack objects first.
680     for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
681       if (MFI->isObjectPreAllocated(i) &&
682           MFI->getUseLocalStackAllocationBlock())
683         continue;
684       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
685         continue;
686       if (RS && RS->isScavengingFrameIndex((int)i))
687         continue;
688       if (MFI->isDeadObjectIndex(i))
689         continue;
690       if (MFI->getStackProtectorIndex() == (int)i)
691         continue;
692 
693       switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
694       case StackProtector::SSPLK_None:
695         continue;
696       case StackProtector::SSPLK_SmallArray:
697         SmallArrayObjs.insert(i);
698         continue;
699       case StackProtector::SSPLK_AddrOf:
700         AddrOfObjs.insert(i);
701         continue;
702       case StackProtector::SSPLK_LargeArray:
703         LargeArrayObjs.insert(i);
704         continue;
705       }
706       llvm_unreachable("Unexpected SSPLayoutKind.");
707     }
708 
709     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
710                           Offset, MaxAlign);
711     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
712                           Offset, MaxAlign);
713     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
714                           Offset, MaxAlign);
715   }
716 
717   // Then assign frame offsets to stack objects that are not used to spill
718   // callee saved registers.
719   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
720     if (MFI->isObjectPreAllocated(i) &&
721         MFI->getUseLocalStackAllocationBlock())
722       continue;
723     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
724       continue;
725     if (RS && RS->isScavengingFrameIndex((int)i))
726       continue;
727     if (MFI->isDeadObjectIndex(i))
728       continue;
729     if (MFI->getStackProtectorIndex() == (int)i)
730       continue;
731     if (ProtectedObjs.count(i))
732       continue;
733 
734     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
735   }
736 
737   // Make sure the special register scavenging spill slot is closest to the
738   // stack pointer.
739   if (RS && !EarlyScavengingSlots) {
740     SmallVector<int, 2> SFIs;
741     RS->getScavengingFrameIndices(SFIs);
742     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
743            IE = SFIs.end(); I != IE; ++I)
744       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
745   }
746 
747   if (!TFI.targetHandlesStackFrameRounding()) {
748     // If we have reserved argument space for call sites in the function
749     // immediately on entry to the current function, count it as part of the
750     // overall stack size.
751     if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
752       Offset += MFI->getMaxCallFrameSize();
753 
754     // Round up the size to a multiple of the alignment.  If the function has
755     // any calls or alloca's, align to the target's StackAlignment value to
756     // ensure that the callee's frame or the alloca data is suitably aligned;
757     // otherwise, for leaf functions, align to the TransientStackAlignment
758     // value.
759     unsigned StackAlign;
760     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
761         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
762       StackAlign = TFI.getStackAlignment();
763     else
764       StackAlign = TFI.getTransientStackAlignment();
765 
766     // If the frame pointer is eliminated, all frame offsets will be relative to
767     // SP not FP. Align to MaxAlign so this works.
768     StackAlign = std::max(StackAlign, MaxAlign);
769     Offset = RoundUpToAlignment(Offset, StackAlign);
770   }
771 
772   // Update frame info to pretend that this is part of the stack...
773   int64_t StackSize = Offset - LocalAreaOffset;
774   MFI->setStackSize(StackSize);
775   NumBytesStackSpace += StackSize;
776 }
777 
778 /// insertPrologEpilogCode - Scan the function for modified callee saved
779 /// registers, insert spill code for these callee saved registers, then add
780 /// prolog and epilog code to the function.
781 ///
782 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
783   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
784 
785   // Add prologue to the function...
786   TFI.emitPrologue(Fn, *SaveBlock);
787 
788   // Add epilogue to restore the callee-save registers in each exiting block.
789   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
790     TFI.emitEpilogue(Fn, *RestoreBlock);
791 
792   // Emit additional code that is required to support segmented stacks, if
793   // we've been asked for it.  This, when linked with a runtime with support
794   // for segmented stacks (libgcc is one), will result in allocating stack
795   // space in small chunks instead of one large contiguous block.
796   if (Fn.shouldSplitStack())
797     TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
798 
799   // Emit additional code that is required to explicitly handle the stack in
800   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
801   // approach is rather similar to that of Segmented Stacks, but it uses a
802   // different conditional check and another BIF for allocating more stack
803   // space.
804   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
805     TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
806 }
807 
808 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
809 /// register references and actual offsets.
810 ///
811 void PEI::replaceFrameIndices(MachineFunction &Fn) {
812   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
813   if (!TFI.needsFrameIndexResolution(Fn)) return;
814 
815   MachineModuleInfo &MMI = Fn.getMMI();
816   const Function *F = Fn.getFunction();
817   const Function *ParentF = MMI.getWinEHParent(F);
818   unsigned FrameReg;
819   if (F == ParentF) {
820     WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
821     // FIXME: This should be unconditional but we have bugs in the preparation
822     // pass.
823     if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
824       FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
825           Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
826   } else if (MMI.hasWinEHFuncInfo(F)) {
827     WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
828     auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F);
829     if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end())
830       FuncInfo.CatchHandlerParentFrameObjOffset[F] =
831           TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg);
832   }
833 
834   // Store SPAdj at exit of a basic block.
835   SmallVector<int, 8> SPState;
836   SPState.resize(Fn.getNumBlockIDs());
837   SmallPtrSet<MachineBasicBlock*, 8> Reachable;
838 
839   // Iterate over the reachable blocks in DFS order.
840   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
841        DFI != DFE; ++DFI) {
842     int SPAdj = 0;
843     // Check the exit state of the DFS stack predecessor.
844     if (DFI.getPathLength() >= 2) {
845       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
846       assert(Reachable.count(StackPred) &&
847              "DFS stack predecessor is already visited.\n");
848       SPAdj = SPState[StackPred->getNumber()];
849     }
850     MachineBasicBlock *BB = *DFI;
851     replaceFrameIndices(BB, Fn, SPAdj);
852     SPState[BB->getNumber()] = SPAdj;
853   }
854 
855   // Handle the unreachable blocks.
856   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
857     if (Reachable.count(BB))
858       // Already handled in DFS traversal.
859       continue;
860     int SPAdj = 0;
861     replaceFrameIndices(BB, Fn, SPAdj);
862   }
863 }
864 
865 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
866                               int &SPAdj) {
867   assert(Fn.getSubtarget().getRegisterInfo() &&
868          "getRegisterInfo() must be implemented!");
869   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
870   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
871   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
872   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
873   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
874 
875   if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
876 
877   bool InsideCallSequence = false;
878 
879   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
880 
881     if (I->getOpcode() == FrameSetupOpcode ||
882         I->getOpcode() == FrameDestroyOpcode) {
883       InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
884       SPAdj += TII.getSPAdjust(I);
885 
886       MachineBasicBlock::iterator PrevI = BB->end();
887       if (I != BB->begin()) PrevI = std::prev(I);
888       TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
889 
890       // Visit the instructions created by eliminateCallFramePseudoInstr().
891       if (PrevI == BB->end())
892         I = BB->begin();     // The replaced instr was the first in the block.
893       else
894         I = std::next(PrevI);
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 indicies 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 indicies 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           MachineRegisterInfo &MRI = Fn.getRegInfo();
1042           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1043 
1044           // Make sure MRI now accounts this register as used.
1045           MRI.setPhysRegUsed(ScratchReg);
1046 
1047           // Because this instruction was processed by the RS before this
1048           // register was allocated, make sure that the RS now records the
1049           // register as being used.
1050           RS->setRegUsed(ScratchReg);
1051         }
1052       }
1053 
1054       // If the scavenger needed to use one of its spill slots, the
1055       // spill code will have been inserted in between I and J. This is a
1056       // problem because we need the spill code before I: Move I to just
1057       // prior to J.
1058       if (I != std::prev(J)) {
1059         BB->splice(J, BB, I);
1060 
1061         // Before we move I, we need to prepare the RS to visit I again.
1062         // Specifically, RS will assert if it sees uses of registers that
1063         // it believes are undefined. Because we have already processed
1064         // register kills in I, when it visits I again, it will believe that
1065         // those registers are undefined. To avoid this situation, unprocess
1066         // the instruction I.
1067         assert(RS->getCurrentPosition() == I &&
1068           "The register scavenger has an unexpected position");
1069         I = P;
1070         RS->unprocess(P);
1071       } else
1072         ++I;
1073     }
1074   }
1075 }
1076