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