[WinEH] Pull Adjectives and CatchObj out of the catchpad arg list
[oota-llvm.git] / lib / CodeGen / PrologEpilogInserter.cpp
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. Typically there is a
75   // single save block, unless Windows EH funclets are involved.
76   SmallVector<MachineBasicBlock *, 1> SaveBlocks;
77   SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
78
79   // Flag to control whether to use the register scavenger to resolve
80   // frame index materialization registers. Set according to
81   // TRI->requiresFrameIndexScavenging() for the current function.
82   bool FrameIndexVirtualScavenging;
83
84   void calculateSets(MachineFunction &Fn);
85   void calculateCallsInformation(MachineFunction &Fn);
86   void assignCalleeSavedSpillSlots(MachineFunction &Fn,
87                                    const BitVector &SavedRegs);
88   void insertCSRSpillsAndRestores(MachineFunction &Fn);
89   void calculateFrameObjectOffsets(MachineFunction &Fn);
90   void replaceFrameIndices(MachineFunction &Fn);
91   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
92                            int &SPAdj);
93   void scavengeFrameVirtualRegs(MachineFunction &Fn);
94   void insertPrologEpilogCode(MachineFunction &Fn);
95
96   // Convenience for recognizing return blocks.
97   bool isReturnBlock(const MachineBasicBlock *MBB) const;
98 };
99 } // namespace
100
101 char PEI::ID = 0;
102 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
103
104 static cl::opt<unsigned>
105 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
106               cl::desc("Warn for stack size bigger than the given"
107                        " number"));
108
109 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
110                 "Prologue/Epilogue Insertion", false, false)
111 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
112 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
113 INITIALIZE_PASS_DEPENDENCY(StackProtector)
114 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
115 INITIALIZE_PASS_END(PEI, "prologepilog",
116                     "Prologue/Epilogue Insertion & Frame Finalization",
117                     false, false)
118
119 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
120 STATISTIC(NumBytesStackSpace,
121           "Number of bytes used for stack in all functions");
122
123 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
124   AU.setPreservesCFG();
125   AU.addPreserved<MachineLoopInfo>();
126   AU.addPreserved<MachineDominatorTree>();
127   AU.addRequired<StackProtector>();
128   AU.addRequired<TargetPassConfig>();
129   MachineFunctionPass::getAnalysisUsage(AU);
130 }
131
132 bool PEI::isReturnBlock(const MachineBasicBlock* MBB) const {
133   return (MBB && !MBB->empty() && MBB->back().isReturn());
134 }
135
136 /// Compute the set of return blocks
137 void PEI::calculateSets(MachineFunction &Fn) {
138   const MachineFrameInfo *MFI = Fn.getFrameInfo();
139
140   // Even when we do not change any CSR, we still want to insert the
141   // prologue and epilogue of the function.
142   // So set the save points for those.
143
144   // Use the points found by shrink-wrapping, if any.
145   if (MFI->getSavePoint()) {
146     SaveBlocks.push_back(MFI->getSavePoint());
147     assert(MFI->getRestorePoint() && "Both restore and save must be set");
148     MachineBasicBlock *RestoreBlock = MFI->getRestorePoint();
149     // If RestoreBlock does not have any successor and is not a return block
150     // then the end point is unreachable and we do not need to insert any
151     // epilogue.
152     if (!RestoreBlock->succ_empty() || isReturnBlock(RestoreBlock))
153       RestoreBlocks.push_back(RestoreBlock);
154     return;
155   }
156
157   // Save refs to entry and return blocks.
158   SaveBlocks.push_back(Fn.begin());
159   for (MachineBasicBlock &MBB : Fn) {
160     if (MBB.isEHFuncletEntry())
161       SaveBlocks.push_back(&MBB);
162     if (isReturnBlock(&MBB))
163       RestoreBlocks.push_back(&MBB);
164   }
165 }
166
167 /// StackObjSet - A set of stack object indexes
168 typedef SmallSetVector<int, 8> StackObjSet;
169
170 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
171 /// frame indexes with appropriate references.
172 ///
173 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
174   const Function* F = Fn.getFunction();
175   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
176   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
177
178   assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
179
180   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
181   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
182
183   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
184   // function's frame information. Also eliminates call frame pseudo
185   // instructions.
186   calculateCallsInformation(Fn);
187
188   // Determine which of the registers in the callee save list should be saved.
189   BitVector SavedRegs;
190   TFI->determineCalleeSaves(Fn, SavedRegs, RS);
191
192   // Insert spill code for any callee saved registers that are modified.
193   assignCalleeSavedSpillSlots(Fn, SavedRegs);
194
195   // Determine placement of CSR spill/restore code:
196   // place all spills in the entry block, all restores in return blocks.
197   calculateSets(Fn);
198
199   // Add the code to save and restore the callee saved registers
200   if (!F->hasFnAttribute(Attribute::Naked))
201     insertCSRSpillsAndRestores(Fn);
202
203   // Allow the target machine to make final modifications to the function
204   // before the frame layout is finalized.
205   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
206
207   // Calculate actual frame offsets for all abstract stack objects...
208   calculateFrameObjectOffsets(Fn);
209
210   // Add prolog and epilog code to the function.  This function is required
211   // to align the stack frame as necessary for any stack variables or
212   // called functions.  Because of this, calculateCalleeSavedRegisters()
213   // must be called before this function in order to set the AdjustsStack
214   // and MaxCallFrameSize variables.
215   if (!F->hasFnAttribute(Attribute::Naked))
216     insertPrologEpilogCode(Fn);
217
218   // Replace all MO_FrameIndex operands with physical register references
219   // and actual offsets.
220   //
221   replaceFrameIndices(Fn);
222
223   // If register scavenging is needed, as we've enabled doing it as a
224   // post-pass, scavenge the virtual registers that frame index elimination
225   // inserted.
226   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
227     scavengeFrameVirtualRegs(Fn);
228
229   // Clear any vregs created by virtual scavenging.
230   Fn.getRegInfo().clearVirtRegs();
231
232   // Warn on stack size when we exceeds the given limit.
233   MachineFrameInfo *MFI = Fn.getFrameInfo();
234   uint64_t StackSize = MFI->getStackSize();
235   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
236     DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
237     F->getContext().diagnose(DiagStackSize);
238   }
239
240   delete RS;
241   SaveBlocks.clear();
242   RestoreBlocks.clear();
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 (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
334          I != E; ++I) {
335       unsigned Reg = I->getReg();
336       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
337
338       int FrameIdx;
339       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
340         I->setFrameIdx(FrameIdx);
341         continue;
342       }
343
344       // Check to see if this physreg must be spilled to a particular stack slot
345       // on this target.
346       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
347       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
348              FixedSlot->Reg != Reg)
349         ++FixedSlot;
350
351       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
352         // Nope, just spill it anywhere convenient.
353         unsigned Align = RC->getAlignment();
354         unsigned StackAlign = TFI->getStackAlignment();
355
356         // We may not be able to satisfy the desired alignment specification of
357         // the TargetRegisterClass if the stack alignment is smaller. Use the
358         // min.
359         Align = std::min(Align, StackAlign);
360         FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
361         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
362         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
363       } else {
364         // Spill it to the stack where we must.
365         FrameIdx =
366             MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
367       }
368
369       I->setFrameIdx(FrameIdx);
370     }
371   }
372
373   MFI->setCalleeSavedInfo(CSI);
374 }
375
376 /// Helper function to update the liveness information for the callee-saved
377 /// registers.
378 static void updateLiveness(MachineFunction &MF) {
379   MachineFrameInfo *MFI = MF.getFrameInfo();
380   // Visited will contain all the basic blocks that are in the region
381   // where the callee saved registers are alive:
382   // - Anything that is not Save or Restore -> LiveThrough.
383   // - Save -> LiveIn.
384   // - Restore -> LiveOut.
385   // The live-out is not attached to the block, so no need to keep
386   // Restore in this set.
387   SmallPtrSet<MachineBasicBlock *, 8> Visited;
388   SmallVector<MachineBasicBlock *, 8> WorkList;
389   MachineBasicBlock *Entry = &MF.front();
390   MachineBasicBlock *Save = MFI->getSavePoint();
391
392   if (!Save)
393     Save = Entry;
394
395   if (Entry != Save) {
396     WorkList.push_back(Entry);
397     Visited.insert(Entry);
398   }
399   Visited.insert(Save);
400
401   MachineBasicBlock *Restore = MFI->getRestorePoint();
402   if (Restore)
403     // By construction Restore cannot be visited, otherwise it
404     // means there exists a path to Restore that does not go
405     // through Save.
406     WorkList.push_back(Restore);
407
408   while (!WorkList.empty()) {
409     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
410     // By construction, the region that is after the save point is
411     // dominated by the Save and post-dominated by the Restore.
412     if (CurBB == Save)
413       continue;
414     // Enqueue all the successors not already visited.
415     // Those are by construction either before Save or after Restore.
416     for (MachineBasicBlock *SuccBB : CurBB->successors())
417       if (Visited.insert(SuccBB).second)
418         WorkList.push_back(SuccBB);
419   }
420
421   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
422
423   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
424     for (MachineBasicBlock *MBB : Visited)
425       // Add the callee-saved register as live-in.
426       // It's killed at the spill.
427       MBB->addLiveIn(CSI[i].getReg());
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) {
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 = (Offset + Align - 1) / Align * Align;
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) {
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);
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   // If there are fixed sized objects that are preallocated in the local area,
571   // non-fixed objects can't be allocated right at the start of local area.
572   // We currently don't support filling in holes in between fixed sized
573   // objects, so we adjust 'Offset' to point to the end of last fixed sized
574   // preallocated object.
575   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
576     int64_t FixedOff;
577     if (StackGrowsDown) {
578       // The maximum distance from the stack pointer is at lower address of
579       // the object -- which is given by offset. For down growing stack
580       // the offset is negative, so we negate the offset to get the distance.
581       FixedOff = -MFI->getObjectOffset(i);
582     } else {
583       // The maximum distance from the start pointer is at the upper
584       // address of the object.
585       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
586     }
587     if (FixedOff > Offset) Offset = FixedOff;
588   }
589
590   // First assign frame offsets to stack objects that are used to spill
591   // callee saved registers.
592   if (StackGrowsDown) {
593     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
594       // If the stack grows down, we need to add the size to find the lowest
595       // address of the object.
596       Offset += MFI->getObjectSize(i);
597
598       unsigned Align = MFI->getObjectAlignment(i);
599       // Adjust to alignment boundary
600       Offset = RoundUpToAlignment(Offset, Align);
601
602       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
603     }
604   } else {
605     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
606     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
607       unsigned Align = MFI->getObjectAlignment(i);
608       // Adjust to alignment boundary
609       Offset = RoundUpToAlignment(Offset, Align);
610
611       MFI->setObjectOffset(i, Offset);
612       Offset += MFI->getObjectSize(i);
613     }
614   }
615
616   unsigned MaxAlign = MFI->getMaxAlignment();
617
618   // Make sure the special register scavenging spill slot is closest to the
619   // incoming stack pointer if a frame pointer is required and is closer
620   // to the incoming rather than the final stack pointer.
621   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
622   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
623                                TFI.isFPCloseToIncomingSP() &&
624                                RegInfo->useFPForScavengingIndex(Fn) &&
625                                !RegInfo->needsStackRealignment(Fn));
626   if (RS && EarlyScavengingSlots) {
627     SmallVector<int, 2> SFIs;
628     RS->getScavengingFrameIndices(SFIs);
629     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
630            IE = SFIs.end(); I != IE; ++I)
631       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
632   }
633
634   // FIXME: Once this is working, then enable flag will change to a target
635   // check for whether the frame is large enough to want to use virtual
636   // frame index registers. Functions which don't want/need this optimization
637   // will continue to use the existing code path.
638   if (MFI->getUseLocalStackAllocationBlock()) {
639     unsigned Align = MFI->getLocalFrameMaxAlign();
640
641     // Adjust to alignment boundary.
642     Offset = RoundUpToAlignment(Offset, Align);
643
644     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
645
646     // Resolve offsets for objects in the local block.
647     for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
648       std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
649       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
650       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
651             FIOffset << "]\n");
652       MFI->setObjectOffset(Entry.first, FIOffset);
653     }
654     // Allocate the local block
655     Offset += MFI->getLocalFrameSize();
656
657     MaxAlign = std::max(Align, MaxAlign);
658   }
659
660   // Make sure that the stack protector comes before the local variables on the
661   // stack.
662   SmallSet<int, 16> ProtectedObjs;
663   if (MFI->getStackProtectorIndex() >= 0) {
664     StackObjSet LargeArrayObjs;
665     StackObjSet SmallArrayObjs;
666     StackObjSet AddrOfObjs;
667
668     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
669                       Offset, MaxAlign);
670
671     // Assign large stack objects first.
672     for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
673       if (MFI->isObjectPreAllocated(i) &&
674           MFI->getUseLocalStackAllocationBlock())
675         continue;
676       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
677         continue;
678       if (RS && RS->isScavengingFrameIndex((int)i))
679         continue;
680       if (MFI->isDeadObjectIndex(i))
681         continue;
682       if (MFI->getStackProtectorIndex() == (int)i)
683         continue;
684
685       switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
686       case StackProtector::SSPLK_None:
687         continue;
688       case StackProtector::SSPLK_SmallArray:
689         SmallArrayObjs.insert(i);
690         continue;
691       case StackProtector::SSPLK_AddrOf:
692         AddrOfObjs.insert(i);
693         continue;
694       case StackProtector::SSPLK_LargeArray:
695         LargeArrayObjs.insert(i);
696         continue;
697       }
698       llvm_unreachable("Unexpected SSPLayoutKind.");
699     }
700
701     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
702                           Offset, MaxAlign);
703     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
704                           Offset, MaxAlign);
705     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
706                           Offset, MaxAlign);
707   }
708
709   // Then assign frame offsets to stack objects that are not used to spill
710   // callee saved registers.
711   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
712     if (MFI->isObjectPreAllocated(i) &&
713         MFI->getUseLocalStackAllocationBlock())
714       continue;
715     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
716       continue;
717     if (RS && RS->isScavengingFrameIndex((int)i))
718       continue;
719     if (MFI->isDeadObjectIndex(i))
720       continue;
721     if (MFI->getStackProtectorIndex() == (int)i)
722       continue;
723     if (ProtectedObjs.count(i))
724       continue;
725
726     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
727   }
728
729   // Make sure the special register scavenging spill slot is closest to the
730   // stack pointer.
731   if (RS && !EarlyScavengingSlots) {
732     SmallVector<int, 2> SFIs;
733     RS->getScavengingFrameIndices(SFIs);
734     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
735            IE = SFIs.end(); I != IE; ++I)
736       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
737   }
738
739   if (!TFI.targetHandlesStackFrameRounding()) {
740     // If we have reserved argument space for call sites in the function
741     // immediately on entry to the current function, count it as part of the
742     // overall stack size.
743     if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
744       Offset += MFI->getMaxCallFrameSize();
745
746     // Round up the size to a multiple of the alignment.  If the function has
747     // any calls or alloca's, align to the target's StackAlignment value to
748     // ensure that the callee's frame or the alloca data is suitably aligned;
749     // otherwise, for leaf functions, align to the TransientStackAlignment
750     // value.
751     unsigned StackAlign;
752     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
753         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
754       StackAlign = TFI.getStackAlignment();
755     else
756       StackAlign = TFI.getTransientStackAlignment();
757
758     // If the frame pointer is eliminated, all frame offsets will be relative to
759     // SP not FP. Align to MaxAlign so this works.
760     StackAlign = std::max(StackAlign, MaxAlign);
761     Offset = RoundUpToAlignment(Offset, StackAlign);
762   }
763
764   // Update frame info to pretend that this is part of the stack...
765   int64_t StackSize = Offset - LocalAreaOffset;
766   MFI->setStackSize(StackSize);
767   NumBytesStackSpace += StackSize;
768 }
769
770 /// insertPrologEpilogCode - Scan the function for modified callee saved
771 /// registers, insert spill code for these callee saved registers, then add
772 /// prolog and epilog code to the function.
773 ///
774 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
775   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
776
777   // Add prologue to the function...
778   for (MachineBasicBlock *SaveBlock : SaveBlocks)
779     TFI.emitPrologue(Fn, *SaveBlock);
780
781   // Add epilogue to restore the callee-save registers in each exiting block.
782   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
783     TFI.emitEpilogue(Fn, *RestoreBlock);
784
785   // Emit additional code that is required to support segmented stacks, if
786   // we've been asked for it.  This, when linked with a runtime with support
787   // for segmented stacks (libgcc is one), will result in allocating stack
788   // space in small chunks instead of one large contiguous block.
789   if (Fn.shouldSplitStack()) {
790     for (MachineBasicBlock *SaveBlock : SaveBlocks)
791       TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
792   }
793
794   // Emit additional code that is required to explicitly handle the stack in
795   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
796   // approach is rather similar to that of Segmented Stacks, but it uses a
797   // different conditional check and another BIF for allocating more stack
798   // space.
799   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
800     for (MachineBasicBlock *SaveBlock : SaveBlocks)
801       TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
802 }
803
804 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
805 /// register references and actual offsets.
806 ///
807 void PEI::replaceFrameIndices(MachineFunction &Fn) {
808   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
809   if (!TFI.needsFrameIndexResolution(Fn)) return;
810
811   MachineModuleInfo &MMI = Fn.getMMI();
812   const Function *F = Fn.getFunction();
813   const Function *ParentF = MMI.getWinEHParent(F);
814   unsigned FrameReg;
815   if (F == ParentF) {
816     WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
817     // FIXME: This should be unconditional but we have bugs in the preparation
818     // pass.
819     if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
820       FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
821           Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
822     for (WinEHTryBlockMapEntry &TBME : FuncInfo.TryBlockMap) {
823       for (WinEHHandlerType &H : TBME.HandlerArray) {
824         unsigned UnusedReg;
825         if (H.CatchObj.FrameIndex == INT_MAX)
826           H.CatchObj.FrameOffset = INT_MAX;
827         else
828           H.CatchObj.FrameOffset =
829               TFI.getFrameIndexReference(Fn, H.CatchObj.FrameIndex, UnusedReg);
830       }
831     }
832   } else if (MMI.hasWinEHFuncInfo(F)) {
833     WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
834     auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F);
835     if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end())
836       FuncInfo.CatchHandlerParentFrameObjOffset[F] =
837           TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg);
838   }
839
840   // Store SPAdj at exit of a basic block.
841   SmallVector<int, 8> SPState;
842   SPState.resize(Fn.getNumBlockIDs());
843   SmallPtrSet<MachineBasicBlock*, 8> Reachable;
844
845   // Iterate over the reachable blocks in DFS order.
846   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
847        DFI != DFE; ++DFI) {
848     int SPAdj = 0;
849     // Check the exit state of the DFS stack predecessor.
850     if (DFI.getPathLength() >= 2) {
851       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
852       assert(Reachable.count(StackPred) &&
853              "DFS stack predecessor is already visited.\n");
854       SPAdj = SPState[StackPred->getNumber()];
855     }
856     MachineBasicBlock *BB = *DFI;
857     replaceFrameIndices(BB, Fn, SPAdj);
858     SPState[BB->getNumber()] = SPAdj;
859   }
860
861   // Handle the unreachable blocks.
862   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
863     if (Reachable.count(BB))
864       // Already handled in DFS traversal.
865       continue;
866     int SPAdj = 0;
867     replaceFrameIndices(BB, Fn, SPAdj);
868   }
869 }
870
871 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
872                               int &SPAdj) {
873   assert(Fn.getSubtarget().getRegisterInfo() &&
874          "getRegisterInfo() must be implemented!");
875   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
876   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
877   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
878   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
879   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
880
881   if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
882
883   bool InsideCallSequence = false;
884
885   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
886
887     if (I->getOpcode() == FrameSetupOpcode ||
888         I->getOpcode() == FrameDestroyOpcode) {
889       InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
890       SPAdj += TII.getSPAdjust(I);
891
892       MachineBasicBlock::iterator PrevI = BB->end();
893       if (I != BB->begin()) PrevI = std::prev(I);
894       TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
895
896       // Visit the instructions created by eliminateCallFramePseudoInstr().
897       if (PrevI == BB->end())
898         I = BB->begin();     // The replaced instr was the first in the block.
899       else
900         I = std::next(PrevI);
901       continue;
902     }
903
904     MachineInstr *MI = I;
905     bool DoIncr = true;
906     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
907       if (!MI->getOperand(i).isFI())
908         continue;
909
910       // Frame indices in debug values are encoded in a target independent
911       // way with simply the frame index and offset rather than any
912       // target-specific addressing mode.
913       if (MI->isDebugValue()) {
914         assert(i == 0 && "Frame indices can only appear as the first "
915                          "operand of a DBG_VALUE machine instruction");
916         unsigned Reg;
917         MachineOperand &Offset = MI->getOperand(1);
918         Offset.setImm(Offset.getImm() +
919                       TFI->getFrameIndexReference(
920                           Fn, MI->getOperand(0).getIndex(), Reg));
921         MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
922         continue;
923       }
924
925       // TODO: This code should be commoned with the code for
926       // PATCHPOINT. There's no good reason for the difference in
927       // implementation other than historical accident.  The only
928       // remaining difference is the unconditional use of the stack
929       // pointer as the base register.
930       if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
931         assert((!MI->isDebugValue() || i == 0) &&
932                "Frame indicies can only appear as the first operand of a "
933                "DBG_VALUE machine instruction");
934         unsigned Reg;
935         MachineOperand &Offset = MI->getOperand(i + 1);
936         const unsigned refOffset =
937           TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
938                                             Reg);
939
940         Offset.setImm(Offset.getImm() + refOffset);
941         MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
942         continue;
943       }
944
945       // Some instructions (e.g. inline asm instructions) can have
946       // multiple frame indices and/or cause eliminateFrameIndex
947       // to insert more than one instruction. We need the register
948       // scavenger to go through all of these instructions so that
949       // it can update its register information. We keep the
950       // iterator at the point before insertion so that we can
951       // revisit them in full.
952       bool AtBeginning = (I == BB->begin());
953       if (!AtBeginning) --I;
954
955       // If this instruction has a FrameIndex operand, we need to
956       // use that target machine register info object to eliminate
957       // it.
958       TRI.eliminateFrameIndex(MI, SPAdj, i,
959                               FrameIndexVirtualScavenging ?  nullptr : RS);
960
961       // Reset the iterator if we were at the beginning of the BB.
962       if (AtBeginning) {
963         I = BB->begin();
964         DoIncr = false;
965       }
966
967       MI = nullptr;
968       break;
969     }
970
971     // If we are looking at a call sequence, we need to keep track of
972     // the SP adjustment made by each instruction in the sequence.
973     // This includes both the frame setup/destroy pseudos (handled above),
974     // as well as other instructions that have side effects w.r.t the SP.
975     // Note that this must come after eliminateFrameIndex, because 
976     // if I itself referred to a frame index, we shouldn't count its own
977     // adjustment.
978     if (MI && InsideCallSequence)
979       SPAdj += TII.getSPAdjust(MI);
980
981     if (DoIncr && I != BB->end()) ++I;
982
983     // Update register states.
984     if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
985   }
986 }
987
988 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
989 /// with physical registers. Use the register scavenger to find an
990 /// appropriate register to use.
991 ///
992 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
993 /// iterate over the vreg use list, which at this point only contains machine
994 /// operands for which eliminateFrameIndex need a new scratch reg.
995 void
996 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
997   // Run through the instructions and find any virtual registers.
998   for (MachineFunction::iterator BB = Fn.begin(),
999        E = Fn.end(); BB != E; ++BB) {
1000     RS->enterBasicBlock(BB);
1001
1002     int SPAdj = 0;
1003
1004     // The instruction stream may change in the loop, so check BB->end()
1005     // directly.
1006     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1007       // We might end up here again with a NULL iterator if we scavenged a
1008       // register for which we inserted spill code for definition by what was
1009       // originally the first instruction in BB.
1010       if (I == MachineBasicBlock::iterator(nullptr))
1011         I = BB->begin();
1012
1013       MachineInstr *MI = I;
1014       MachineBasicBlock::iterator J = std::next(I);
1015       MachineBasicBlock::iterator P =
1016                          I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1017                                           : std::prev(I);
1018
1019       // RS should process this instruction before we might scavenge at this
1020       // location. This is because we might be replacing a virtual register
1021       // defined by this instruction, and if so, registers killed by this
1022       // instruction are available, and defined registers are not.
1023       RS->forward(I);
1024
1025       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1026         if (MI->getOperand(i).isReg()) {
1027           MachineOperand &MO = MI->getOperand(i);
1028           unsigned Reg = MO.getReg();
1029           if (Reg == 0)
1030             continue;
1031           if (!TargetRegisterInfo::isVirtualRegister(Reg))
1032             continue;
1033
1034           // When we first encounter a new virtual register, it
1035           // must be a definition.
1036           assert(MI->getOperand(i).isDef() &&
1037                  "frame index virtual missing def!");
1038           // Scavenge a new scratch register
1039           const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1040           unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1041
1042           ++NumScavengedRegs;
1043
1044           // Replace this reference to the virtual register with the
1045           // scratch register.
1046           assert (ScratchReg && "Missing scratch register!");
1047           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1048           
1049           // Because this instruction was processed by the RS before this
1050           // register was allocated, make sure that the RS now records the
1051           // register as being used.
1052           RS->setRegUsed(ScratchReg);
1053         }
1054       }
1055
1056       // If the scavenger needed to use one of its spill slots, the
1057       // spill code will have been inserted in between I and J. This is a
1058       // problem because we need the spill code before I: Move I to just
1059       // prior to J.
1060       if (I != std::prev(J)) {
1061         BB->splice(J, BB, I);
1062
1063         // Before we move I, we need to prepare the RS to visit I again.
1064         // Specifically, RS will assert if it sees uses of registers that
1065         // it believes are undefined. Because we have already processed
1066         // register kills in I, when it visits I again, it will believe that
1067         // those registers are undefined. To avoid this situation, unprocess
1068         // the instruction I.
1069         assert(RS->getCurrentPosition() == I &&
1070           "The register scavenger has an unexpected position");
1071         I = P;
1072         RS->unprocess(P);
1073       } else
1074         ++I;
1075     }
1076   }
1077 }