xref: /openbsd-src/gnu/llvm/llvm/lib/Target/X86/X86FrameLowering.cpp (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the X86 implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86FrameLowering.h"
14 #include "X86InstrBuilder.h"
15 #include "X86InstrInfo.h"
16 #include "X86MachineFunctionInfo.h"
17 #include "X86ReturnProtectorLowering.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Analysis/EHPersonalities.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include <cstdlib>
35 
36 using namespace llvm;
37 
38 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
39                                    MaybeAlign StackAlignOverride)
40     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
41                           STI.is64Bit() ? -8 : -4),
42       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()), RPL() {
43   // Cache a bunch of frame-related predicates for this subtarget.
44   SlotSize = TRI->getSlotSize();
45   Is64Bit = STI.is64Bit();
46   IsLP64 = STI.isTarget64BitLP64();
47   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
48   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
49   StackPtr = TRI->getStackRegister();
50   SaveArgs = Is64Bit ? STI.getSaveArgs() : 0;
51 }
52 
53 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
54   return !MF.getFrameInfo().hasVarSizedObjects() &&
55          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
56 }
57 
58 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
59 /// call frame pseudos can be simplified.  Having a FP, as in the default
60 /// implementation, is not sufficient here since we can't always use it.
61 /// Use a more nuanced condition.
62 bool
63 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
64   return hasReservedCallFrame(MF) ||
65          (hasFP(MF) && !TRI->needsStackRealignment(MF)) ||
66          TRI->hasBasePointer(MF);
67 }
68 
69 // needsFrameIndexResolution - Do we need to perform FI resolution for
70 // this function. Normally, this is required only when the function
71 // has any stack objects. However, FI resolution actually has another job,
72 // not apparent from the title - it resolves callframesetup/destroy
73 // that were not simplified earlier.
74 // So, this is required for x86 functions that have push sequences even
75 // when there are no stack objects.
76 bool
77 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
78   return MF.getFrameInfo().hasStackObjects() ||
79          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
80 }
81 
82 /// hasFP - Return true if the specified function should have a dedicated frame
83 /// pointer register.  This is true if the function has variable sized allocas
84 /// or if frame pointer elimination is disabled.
85 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
86   const MachineFrameInfo &MFI = MF.getFrameInfo();
87   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
88           TRI->needsStackRealignment(MF) ||
89           MFI.hasVarSizedObjects() ||
90           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
91           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
92           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
93           MFI.hasStackMap() || MFI.hasPatchPoint() ||
94           MFI.hasCopyImplyingStackAdjustment() ||
95           SaveArgs);
96 }
97 
98 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
99   if (IsLP64) {
100     if (isInt<8>(Imm))
101       return X86::SUB64ri8;
102     return X86::SUB64ri32;
103   } else {
104     if (isInt<8>(Imm))
105       return X86::SUB32ri8;
106     return X86::SUB32ri;
107   }
108 }
109 
110 static unsigned getADDriOpcode(bool IsLP64, int64_t Imm) {
111   if (IsLP64) {
112     if (isInt<8>(Imm))
113       return X86::ADD64ri8;
114     return X86::ADD64ri32;
115   } else {
116     if (isInt<8>(Imm))
117       return X86::ADD32ri8;
118     return X86::ADD32ri;
119   }
120 }
121 
122 static unsigned getSUBrrOpcode(bool IsLP64) {
123   return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
124 }
125 
126 static unsigned getADDrrOpcode(bool IsLP64) {
127   return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
128 }
129 
130 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
131   if (IsLP64) {
132     if (isInt<8>(Imm))
133       return X86::AND64ri8;
134     return X86::AND64ri32;
135   }
136   if (isInt<8>(Imm))
137     return X86::AND32ri8;
138   return X86::AND32ri;
139 }
140 
141 static unsigned getLEArOpcode(bool IsLP64) {
142   return IsLP64 ? X86::LEA64r : X86::LEA32r;
143 }
144 
145 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
146 /// when it reaches the "return" instruction. We can then pop a stack object
147 /// to this register without worry about clobbering it.
148 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
149                                        MachineBasicBlock::iterator &MBBI,
150                                        const X86RegisterInfo *TRI,
151                                        bool Is64Bit) {
152   const MachineFunction *MF = MBB.getParent();
153   if (MF->callsEHReturn())
154     return 0;
155 
156   const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF);
157 
158   if (MBBI == MBB.end())
159     return 0;
160 
161   switch (MBBI->getOpcode()) {
162   default: return 0;
163   case TargetOpcode::PATCHABLE_RET:
164   case X86::RET:
165   case X86::RETL:
166   case X86::RETQ:
167   case X86::RETIL:
168   case X86::RETIQ:
169   case X86::TCRETURNdi:
170   case X86::TCRETURNri:
171   case X86::TCRETURNmi:
172   case X86::TCRETURNdi64:
173   case X86::TCRETURNri64:
174   case X86::TCRETURNmi64:
175   case X86::EH_RETURN:
176   case X86::EH_RETURN64: {
177     SmallSet<uint16_t, 8> Uses;
178     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
179       MachineOperand &MO = MBBI->getOperand(i);
180       if (!MO.isReg() || MO.isDef())
181         continue;
182       Register Reg = MO.getReg();
183       if (!Reg)
184         continue;
185       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
186         Uses.insert(*AI);
187     }
188 
189     for (auto CS : AvailableRegs)
190       if (!Uses.count(CS) && CS != X86::RIP && CS != X86::RSP &&
191           CS != X86::ESP)
192         return CS;
193   }
194   }
195 
196   return 0;
197 }
198 
199 static bool isEAXLiveIn(MachineBasicBlock &MBB) {
200   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
201     unsigned Reg = RegMask.PhysReg;
202 
203     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
204         Reg == X86::AH || Reg == X86::AL)
205       return true;
206   }
207 
208   return false;
209 }
210 
211 /// Check if the flags need to be preserved before the terminators.
212 /// This would be the case, if the eflags is live-in of the region
213 /// composed by the terminators or live-out of that region, without
214 /// being defined by a terminator.
215 static bool
216 flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
217   for (const MachineInstr &MI : MBB.terminators()) {
218     bool BreakNext = false;
219     for (const MachineOperand &MO : MI.operands()) {
220       if (!MO.isReg())
221         continue;
222       Register Reg = MO.getReg();
223       if (Reg != X86::EFLAGS)
224         continue;
225 
226       // This terminator needs an eflags that is not defined
227       // by a previous another terminator:
228       // EFLAGS is live-in of the region composed by the terminators.
229       if (!MO.isDef())
230         return true;
231       // This terminator defines the eflags, i.e., we don't need to preserve it.
232       // However, we still need to check this specific terminator does not
233       // read a live-in value.
234       BreakNext = true;
235     }
236     // We found a definition of the eflags, no need to preserve them.
237     if (BreakNext)
238       return false;
239   }
240 
241   // None of the terminators use or define the eflags.
242   // Check if they are live-out, that would imply we need to preserve them.
243   for (const MachineBasicBlock *Succ : MBB.successors())
244     if (Succ->isLiveIn(X86::EFLAGS))
245       return true;
246 
247   return false;
248 }
249 
250 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
251 /// stack pointer by a constant value.
252 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
253                                     MachineBasicBlock::iterator &MBBI,
254                                     const DebugLoc &DL,
255                                     int64_t NumBytes, bool InEpilogue) const {
256   bool isSub = NumBytes < 0;
257   uint64_t Offset = isSub ? -NumBytes : NumBytes;
258   MachineInstr::MIFlag Flag =
259       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
260 
261   uint64_t Chunk = (1LL << 31) - 1;
262 
263   if (Offset > Chunk) {
264     // Rather than emit a long series of instructions for large offsets,
265     // load the offset into a register and do one sub/add
266     unsigned Reg = 0;
267     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
268 
269     if (isSub && !isEAXLiveIn(MBB))
270       Reg = Rax;
271     else
272       Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
273 
274     unsigned MovRIOpc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
275     unsigned AddSubRROpc =
276         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
277     if (Reg) {
278       BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Reg)
279           .addImm(Offset)
280           .setMIFlag(Flag);
281       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
282                              .addReg(StackPtr)
283                              .addReg(Reg);
284       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
285       return;
286     } else if (Offset > 8 * Chunk) {
287       // If we would need more than 8 add or sub instructions (a >16GB stack
288       // frame), it's worth spilling RAX to materialize this immediate.
289       //   pushq %rax
290       //   movabsq +-$Offset+-SlotSize, %rax
291       //   addq %rsp, %rax
292       //   xchg %rax, (%rsp)
293       //   movq (%rsp), %rsp
294       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
295       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
296           .addReg(Rax, RegState::Kill)
297           .setMIFlag(Flag);
298       // Subtract is not commutative, so negate the offset and always use add.
299       // Subtract 8 less and add 8 more to account for the PUSH we just did.
300       if (isSub)
301         Offset = -(Offset - SlotSize);
302       else
303         Offset = Offset + SlotSize;
304       BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Rax)
305           .addImm(Offset)
306           .setMIFlag(Flag);
307       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
308                              .addReg(Rax)
309                              .addReg(StackPtr);
310       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
311       // Exchange the new SP in RAX with the top of the stack.
312       addRegOffset(
313           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
314           StackPtr, false, 0);
315       // Load new SP from the top of the stack into RSP.
316       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
317                    StackPtr, false, 0);
318       return;
319     }
320   }
321 
322   while (Offset) {
323     uint64_t ThisVal = std::min(Offset, Chunk);
324     if (ThisVal == SlotSize) {
325       // Use push / pop for slot sized adjustments as a size optimization. We
326       // need to find a dead register when using pop.
327       unsigned Reg = isSub
328         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
329         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
330       if (Reg) {
331         unsigned Opc = isSub
332           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
333           : (Is64Bit ? X86::POP64r  : X86::POP32r);
334         BuildMI(MBB, MBBI, DL, TII.get(Opc))
335             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
336             .setMIFlag(Flag);
337         Offset -= ThisVal;
338         continue;
339       }
340     }
341 
342     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
343         .setMIFlag(Flag);
344 
345     Offset -= ThisVal;
346   }
347 }
348 
349 MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
350     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
351     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
352   assert(Offset != 0 && "zero offset stack adjustment requested");
353 
354   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
355   // is tricky.
356   bool UseLEA;
357   if (!InEpilogue) {
358     // Check if inserting the prologue at the beginning
359     // of MBB would require to use LEA operations.
360     // We need to use LEA operations if EFLAGS is live in, because
361     // it means an instruction will read it before it gets defined.
362     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
363   } else {
364     // If we can use LEA for SP but we shouldn't, check that none
365     // of the terminators uses the eflags. Otherwise we will insert
366     // a ADD that will redefine the eflags and break the condition.
367     // Alternatively, we could move the ADD, but this may not be possible
368     // and is an optimization anyway.
369     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
370     if (UseLEA && !STI.useLeaForSP())
371       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
372     // If that assert breaks, that means we do not do the right thing
373     // in canUseAsEpilogue.
374     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
375            "We shouldn't have allowed this insertion point");
376   }
377 
378   MachineInstrBuilder MI;
379   if (UseLEA) {
380     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
381                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
382                               StackPtr),
383                       StackPtr, false, Offset);
384   } else {
385     bool IsSub = Offset < 0;
386     uint64_t AbsOffset = IsSub ? -Offset : Offset;
387     unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
388                          : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
389     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
390              .addReg(StackPtr)
391              .addImm(AbsOffset);
392     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
393   }
394   return MI;
395 }
396 
397 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
398                                      MachineBasicBlock::iterator &MBBI,
399                                      bool doMergeWithPrevious) const {
400   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
401       (!doMergeWithPrevious && MBBI == MBB.end()))
402     return 0;
403 
404   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
405 
406   PI = skipDebugInstructionsBackward(PI, MBB.begin());
407   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
408   // instruction, and that there are no DBG_VALUE or other instructions between
409   // ADD/SUB/LEA and its corresponding CFI instruction.
410   /* TODO: Add support for the case where there are multiple CFI instructions
411     below the ADD/SUB/LEA, e.g.:
412     ...
413     add
414     cfi_def_cfa_offset
415     cfi_offset
416     ...
417   */
418   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
419     PI = std::prev(PI);
420 
421   unsigned Opc = PI->getOpcode();
422   int Offset = 0;
423 
424   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
425        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
426       PI->getOperand(0).getReg() == StackPtr){
427     assert(PI->getOperand(1).getReg() == StackPtr);
428     Offset = PI->getOperand(2).getImm();
429   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
430              PI->getOperand(0).getReg() == StackPtr &&
431              PI->getOperand(1).getReg() == StackPtr &&
432              PI->getOperand(2).getImm() == 1 &&
433              PI->getOperand(3).getReg() == X86::NoRegister &&
434              PI->getOperand(5).getReg() == X86::NoRegister) {
435     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
436     Offset = PI->getOperand(4).getImm();
437   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
438               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
439              PI->getOperand(0).getReg() == StackPtr) {
440     assert(PI->getOperand(1).getReg() == StackPtr);
441     Offset = -PI->getOperand(2).getImm();
442   } else
443     return 0;
444 
445   PI = MBB.erase(PI);
446   if (PI != MBB.end() && PI->isCFIInstruction()) PI = MBB.erase(PI);
447   if (!doMergeWithPrevious)
448     MBBI = skipDebugInstructionsForward(PI, MBB.end());
449 
450   return Offset;
451 }
452 
453 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
454                                 MachineBasicBlock::iterator MBBI,
455                                 const DebugLoc &DL,
456                                 const MCCFIInstruction &CFIInst) const {
457   MachineFunction &MF = *MBB.getParent();
458   unsigned CFIIndex = MF.addFrameInst(CFIInst);
459   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
460       .addCFIIndex(CFIIndex);
461 }
462 
463 void X86FrameLowering::emitCalleeSavedFrameMoves(
464     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
465     const DebugLoc &DL) const {
466   MachineFunction &MF = *MBB.getParent();
467   MachineFrameInfo &MFI = MF.getFrameInfo();
468   MachineModuleInfo &MMI = MF.getMMI();
469   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
470 
471   // Add callee saved registers to move list.
472   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
473   if (CSI.empty()) return;
474 
475   // Calculate offsets.
476   for (std::vector<CalleeSavedInfo>::const_iterator
477          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
478     int64_t Offset = MFI.getObjectOffset(I->getFrameIdx());
479     unsigned Reg = I->getReg();
480 
481     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
482     BuildCFI(MBB, MBBI, DL,
483              MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
484   }
485 }
486 
487 void X86FrameLowering::emitStackProbe(MachineFunction &MF,
488                                       MachineBasicBlock &MBB,
489                                       MachineBasicBlock::iterator MBBI,
490                                       const DebugLoc &DL, bool InProlog) const {
491   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
492   if (STI.isTargetWindowsCoreCLR()) {
493     if (InProlog) {
494       emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
495     } else {
496       emitStackProbeInline(MF, MBB, MBBI, DL, false);
497     }
498   } else {
499     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog);
500   }
501 }
502 
503 void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
504                                         MachineBasicBlock &PrologMBB) const {
505   const StringRef ChkStkStubSymbol = "__chkstk_stub";
506   MachineInstr *ChkStkStub = nullptr;
507 
508   for (MachineInstr &MI : PrologMBB) {
509     if (MI.isCall() && MI.getOperand(0).isSymbol() &&
510         ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) {
511       ChkStkStub = &MI;
512       break;
513     }
514   }
515 
516   if (ChkStkStub != nullptr) {
517     assert(!ChkStkStub->isBundled() &&
518            "Not expecting bundled instructions here");
519     MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator());
520     assert(std::prev(MBBI) == ChkStkStub &&
521            "MBBI expected after __chkstk_stub.");
522     DebugLoc DL = PrologMBB.findDebugLoc(MBBI);
523     emitStackProbeInline(MF, PrologMBB, MBBI, DL, true);
524     ChkStkStub->eraseFromParent();
525   }
526 }
527 
528 void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
529                                             MachineBasicBlock &MBB,
530                                             MachineBasicBlock::iterator MBBI,
531                                             const DebugLoc &DL,
532                                             bool InProlog) const {
533   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
534   assert(STI.is64Bit() && "different expansion needed for 32 bit");
535   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
536   const TargetInstrInfo &TII = *STI.getInstrInfo();
537   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
538 
539   // RAX contains the number of bytes of desired stack adjustment.
540   // The handling here assumes this value has already been updated so as to
541   // maintain stack alignment.
542   //
543   // We need to exit with RSP modified by this amount and execute suitable
544   // page touches to notify the OS that we're growing the stack responsibly.
545   // All stack probing must be done without modifying RSP.
546   //
547   // MBB:
548   //    SizeReg = RAX;
549   //    ZeroReg = 0
550   //    CopyReg = RSP
551   //    Flags, TestReg = CopyReg - SizeReg
552   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
553   //    LimitReg = gs magic thread env access
554   //    if FinalReg >= LimitReg goto ContinueMBB
555   // RoundBB:
556   //    RoundReg = page address of FinalReg
557   // LoopMBB:
558   //    LoopReg = PHI(LimitReg,ProbeReg)
559   //    ProbeReg = LoopReg - PageSize
560   //    [ProbeReg] = 0
561   //    if (ProbeReg > RoundReg) goto LoopMBB
562   // ContinueMBB:
563   //    RSP = RSP - RAX
564   //    [rest of original MBB]
565 
566   // Set up the new basic blocks
567   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
568   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
569   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
570 
571   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
572   MF.insert(MBBIter, RoundMBB);
573   MF.insert(MBBIter, LoopMBB);
574   MF.insert(MBBIter, ContinueMBB);
575 
576   // Split MBB and move the tail portion down to ContinueMBB.
577   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
578   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
579   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
580 
581   // Some useful constants
582   const int64_t ThreadEnvironmentStackLimit = 0x10;
583   const int64_t PageSize = 0x1000;
584   const int64_t PageMask = ~(PageSize - 1);
585 
586   // Registers we need. For the normal case we use virtual
587   // registers. For the prolog expansion we use RAX, RCX and RDX.
588   MachineRegisterInfo &MRI = MF.getRegInfo();
589   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
590   const Register SizeReg = InProlog ? X86::RAX
591                                     : MRI.createVirtualRegister(RegClass),
592                  ZeroReg = InProlog ? X86::RCX
593                                     : MRI.createVirtualRegister(RegClass),
594                  CopyReg = InProlog ? X86::RDX
595                                     : MRI.createVirtualRegister(RegClass),
596                  TestReg = InProlog ? X86::RDX
597                                     : MRI.createVirtualRegister(RegClass),
598                  FinalReg = InProlog ? X86::RDX
599                                      : MRI.createVirtualRegister(RegClass),
600                  RoundedReg = InProlog ? X86::RDX
601                                        : MRI.createVirtualRegister(RegClass),
602                  LimitReg = InProlog ? X86::RCX
603                                      : MRI.createVirtualRegister(RegClass),
604                  JoinReg = InProlog ? X86::RCX
605                                     : MRI.createVirtualRegister(RegClass),
606                  ProbeReg = InProlog ? X86::RCX
607                                      : MRI.createVirtualRegister(RegClass);
608 
609   // SP-relative offsets where we can save RCX and RDX.
610   int64_t RCXShadowSlot = 0;
611   int64_t RDXShadowSlot = 0;
612 
613   // If inlining in the prolog, save RCX and RDX.
614   if (InProlog) {
615     // Compute the offsets. We need to account for things already
616     // pushed onto the stack at this point: return address, frame
617     // pointer (if used), and callee saves.
618     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
619     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
620     const bool HasFP = hasFP(MF);
621 
622     // Check if we need to spill RCX and/or RDX.
623     // Here we assume that no earlier prologue instruction changes RCX and/or
624     // RDX, so checking the block live-ins is enough.
625     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
626     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
627     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
628     // Assign the initial slot to both registers, then change RDX's slot if both
629     // need to be spilled.
630     if (IsRCXLiveIn)
631       RCXShadowSlot = InitSlot;
632     if (IsRDXLiveIn)
633       RDXShadowSlot = InitSlot;
634     if (IsRDXLiveIn && IsRCXLiveIn)
635       RDXShadowSlot += 8;
636     // Emit the saves if needed.
637     if (IsRCXLiveIn)
638       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
639                    RCXShadowSlot)
640           .addReg(X86::RCX);
641     if (IsRDXLiveIn)
642       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
643                    RDXShadowSlot)
644           .addReg(X86::RDX);
645   } else {
646     // Not in the prolog. Copy RAX to a virtual reg.
647     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
648   }
649 
650   // Add code to MBB to check for overflow and set the new target stack pointer
651   // to zero if so.
652   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
653       .addReg(ZeroReg, RegState::Undef)
654       .addReg(ZeroReg, RegState::Undef);
655   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
656   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
657       .addReg(CopyReg)
658       .addReg(SizeReg);
659   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
660       .addReg(TestReg)
661       .addReg(ZeroReg)
662       .addImm(X86::COND_B);
663 
664   // FinalReg now holds final stack pointer value, or zero if
665   // allocation would overflow. Compare against the current stack
666   // limit from the thread environment block. Note this limit is the
667   // lowest touched page on the stack, not the point at which the OS
668   // will cause an overflow exception, so this is just an optimization
669   // to avoid unnecessarily touching pages that are below the current
670   // SP but already committed to the stack by the OS.
671   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
672       .addReg(0)
673       .addImm(1)
674       .addReg(0)
675       .addImm(ThreadEnvironmentStackLimit)
676       .addReg(X86::GS);
677   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
678   // Jump if the desired stack pointer is at or above the stack limit.
679   BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE);
680 
681   // Add code to roundMBB to round the final stack pointer to a page boundary.
682   RoundMBB->addLiveIn(FinalReg);
683   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
684       .addReg(FinalReg)
685       .addImm(PageMask);
686   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
687 
688   // LimitReg now holds the current stack limit, RoundedReg page-rounded
689   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
690   // and probe until we reach RoundedReg.
691   if (!InProlog) {
692     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
693         .addReg(LimitReg)
694         .addMBB(RoundMBB)
695         .addReg(ProbeReg)
696         .addMBB(LoopMBB);
697   }
698 
699   LoopMBB->addLiveIn(JoinReg);
700   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
701                false, -PageSize);
702 
703   // Probe by storing a byte onto the stack.
704   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
705       .addReg(ProbeReg)
706       .addImm(1)
707       .addReg(0)
708       .addImm(0)
709       .addReg(0)
710       .addImm(0);
711 
712   LoopMBB->addLiveIn(RoundedReg);
713   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
714       .addReg(RoundedReg)
715       .addReg(ProbeReg);
716   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE);
717 
718   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
719 
720   // If in prolog, restore RDX and RCX.
721   if (InProlog) {
722     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
723       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
724                            TII.get(X86::MOV64rm), X86::RCX),
725                    X86::RSP, false, RCXShadowSlot);
726     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
727       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
728                            TII.get(X86::MOV64rm), X86::RDX),
729                    X86::RSP, false, RDXShadowSlot);
730   }
731 
732   // Now that the probing is done, add code to continueMBB to update
733   // the stack pointer for real.
734   ContinueMBB->addLiveIn(SizeReg);
735   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
736       .addReg(X86::RSP)
737       .addReg(SizeReg);
738 
739   // Add the control flow edges we need.
740   MBB.addSuccessor(ContinueMBB);
741   MBB.addSuccessor(RoundMBB);
742   RoundMBB->addSuccessor(LoopMBB);
743   LoopMBB->addSuccessor(ContinueMBB);
744   LoopMBB->addSuccessor(LoopMBB);
745 
746   // Mark all the instructions added to the prolog as frame setup.
747   if (InProlog) {
748     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
749       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
750     }
751     for (MachineInstr &MI : *RoundMBB) {
752       MI.setFlag(MachineInstr::FrameSetup);
753     }
754     for (MachineInstr &MI : *LoopMBB) {
755       MI.setFlag(MachineInstr::FrameSetup);
756     }
757     for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin();
758          CMBBI != ContinueMBBI; ++CMBBI) {
759       CMBBI->setFlag(MachineInstr::FrameSetup);
760     }
761   }
762 }
763 
764 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
765                                           MachineBasicBlock &MBB,
766                                           MachineBasicBlock::iterator MBBI,
767                                           const DebugLoc &DL,
768                                           bool InProlog) const {
769   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
770 
771   // FIXME: Add indirect thunk support and remove this.
772   if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
773     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
774                        "code model and indirect thunks not yet implemented.");
775 
776   unsigned CallOp;
777   if (Is64Bit)
778     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
779   else
780     CallOp = X86::CALLpcrel32;
781 
782   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
783 
784   MachineInstrBuilder CI;
785   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
786 
787   // All current stack probes take AX and SP as input, clobber flags, and
788   // preserve all registers. x86_64 probes leave RSP unmodified.
789   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
790     // For the large code model, we have to call through a register. Use R11,
791     // as it is scratch in all supported calling conventions.
792     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
793         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
794     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
795   } else {
796     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
797         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
798   }
799 
800   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
801   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
802   CI.addReg(AX, RegState::Implicit)
803       .addReg(SP, RegState::Implicit)
804       .addReg(AX, RegState::Define | RegState::Implicit)
805       .addReg(SP, RegState::Define | RegState::Implicit)
806       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
807 
808   if (STI.isTargetWin64() || !STI.isOSWindows()) {
809     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
810     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
811     // themselves. They also does not clobber %rax so we can reuse it when
812     // adjusting %rsp.
813     // All other platforms do not specify a particular ABI for the stack probe
814     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
815     BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
816         .addReg(SP)
817         .addReg(AX);
818   }
819 
820   if (InProlog) {
821     // Apply the frame setup flag to all inserted instrs.
822     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
823       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
824   }
825 }
826 
827 void X86FrameLowering::emitStackProbeInlineStub(
828     MachineFunction &MF, MachineBasicBlock &MBB,
829     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
830 
831   assert(InProlog && "ChkStkStub called outside prolog!");
832 
833   BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32))
834       .addExternalSymbol("__chkstk_stub");
835 }
836 
837 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
838   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
839   // and might require smaller successive adjustments.
840   const uint64_t Win64MaxSEHOffset = 128;
841   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
842   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
843   return SEHFrameOffset & -16;
844 }
845 
846 // If we're forcing a stack realignment we can't rely on just the frame
847 // info, we need to know the ABI stack alignment as well in case we
848 // have a call out.  Otherwise just make sure we have some alignment - we'll
849 // go with the minimum SlotSize.
850 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
851   const MachineFrameInfo &MFI = MF.getFrameInfo();
852   uint64_t MaxAlign = MFI.getMaxAlignment(); // Desired stack alignment.
853   unsigned StackAlign = getStackAlignment();
854   if (MF.getFunction().hasFnAttribute("stackrealign")) {
855     if (MFI.hasCalls())
856       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
857     else if (MaxAlign < SlotSize)
858       MaxAlign = SlotSize;
859   }
860   return MaxAlign;
861 }
862 
863 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
864                                           MachineBasicBlock::iterator MBBI,
865                                           const DebugLoc &DL, unsigned Reg,
866                                           uint64_t MaxAlign) const {
867   uint64_t Val = -MaxAlign;
868   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
869   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
870                          .addReg(Reg)
871                          .addImm(Val)
872                          .setMIFlag(MachineInstr::FrameSetup);
873 
874   // The EFLAGS implicit def is dead.
875   MI->getOperand(3).setIsDead();
876 }
877 
878 // FIXME: Get this from tablegen.
879 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
880                                                 const X86Subtarget &Subtarget) {
881   assert(Subtarget.is64Bit());
882 
883   if (Subtarget.isCallingConvWin64(CallConv)) {
884     static const MCPhysReg GPR64ArgRegsWin64[] = {
885       X86::RCX, X86::RDX, X86::R8,  X86::R9
886     };
887     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
888   }
889 
890   static const MCPhysReg GPR64ArgRegs64Bit[] = {
891     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
892   };
893   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
894 }
895 
896 bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const {
897   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
898   // clobbered by any interrupt handler.
899   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
900          "MF used frame lowering for wrong subtarget");
901   const Function &Fn = MF.getFunction();
902   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
903   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
904 }
905 
906 
907 /// emitPrologue - Push callee-saved registers onto the stack, which
908 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
909 /// space for local variables. Also emit labels used by the exception handler to
910 /// generate the exception handling frames.
911 
912 /*
913   Here's a gist of what gets emitted:
914 
915   ; Establish frame pointer, if needed
916   [if needs FP]
917       push  %rbp
918       .cfi_def_cfa_offset 16
919       .cfi_offset %rbp, -16
920       .seh_pushreg %rpb
921       mov  %rsp, %rbp
922       .cfi_def_cfa_register %rbp
923 
924   ; Spill general-purpose registers
925   [for all callee-saved GPRs]
926       pushq %<reg>
927       [if not needs FP]
928          .cfi_def_cfa_offset (offset from RETADDR)
929       .seh_pushreg %<reg>
930 
931   ; If the required stack alignment > default stack alignment
932   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
933   ; of unknown size in the stack frame.
934   [if stack needs re-alignment]
935       and  $MASK, %rsp
936 
937   ; Allocate space for locals
938   [if target is Windows and allocated space > 4096 bytes]
939       ; Windows needs special care for allocations larger
940       ; than one page.
941       mov $NNN, %rax
942       call ___chkstk_ms/___chkstk
943       sub  %rax, %rsp
944   [else]
945       sub  $NNN, %rsp
946 
947   [if needs FP]
948       .seh_stackalloc (size of XMM spill slots)
949       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
950   [else]
951       .seh_stackalloc NNN
952 
953   ; Spill XMMs
954   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
955   ; they may get spilled on any platform, if the current function
956   ; calls @llvm.eh.unwind.init
957   [if needs FP]
958       [for all callee-saved XMM registers]
959           movaps  %<xmm reg>, -MMM(%rbp)
960       [for all callee-saved XMM registers]
961           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
962               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
963   [else]
964       [for all callee-saved XMM registers]
965           movaps  %<xmm reg>, KKK(%rsp)
966       [for all callee-saved XMM registers]
967           .seh_savexmm %<xmm reg>, KKK
968 
969   .seh_endprologue
970 
971   [if needs base pointer]
972       mov  %rsp, %rbx
973       [if needs to restore base pointer]
974           mov %rsp, -MMM(%rbp)
975 
976   ; Emit CFI info
977   [if needs FP]
978       [for all callee-saved registers]
979           .cfi_offset %<reg>, (offset from %rbp)
980   [else]
981        .cfi_def_cfa_offset (offset from RETADDR)
982       [for all callee-saved registers]
983           .cfi_offset %<reg>, (offset from %rsp)
984 
985   Notes:
986   - .seh directives are emitted only for Windows 64 ABI
987   - .cv_fpo directives are emitted on win32 when emitting CodeView
988   - .cfi directives are emitted for all other ABIs
989   - for 32-bit code, substitute %e?? registers for %r??
990 */
991 
992 void X86FrameLowering::emitPrologue(MachineFunction &MF,
993                                     MachineBasicBlock &MBB) const {
994   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
995          "MF used frame lowering for wrong subtarget");
996   MachineBasicBlock::iterator MBBI = MBB.begin();
997   MachineFrameInfo &MFI = MF.getFrameInfo();
998   const Function &Fn = MF.getFunction();
999   MachineModuleInfo &MMI = MF.getMMI();
1000   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1001   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
1002   uint64_t StackSize = MFI.getStackSize();    // Number of bytes to allocate.
1003   bool IsFunclet = MBB.isEHFuncletEntry();
1004   EHPersonality Personality = EHPersonality::Unknown;
1005   if (Fn.hasPersonalityFn())
1006     Personality = classifyEHPersonality(Fn.getPersonalityFn());
1007   bool FnHasClrFunclet =
1008       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
1009   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
1010   bool HasFP = hasFP(MF);
1011   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1012   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
1013   // FIXME: Emit FPO data for EH funclets.
1014   bool NeedsWinFPO =
1015       !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag();
1016   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1017   bool NeedsDwarfCFI = !IsWin64Prologue && MF.needsFrameMoves();
1018   Register FramePtr = TRI->getFrameRegister(MF);
1019   const Register MachineFramePtr =
1020       STI.isTarget64BitILP32()
1021           ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
1022   Register BasePtr = TRI->getBaseRegister();
1023   bool HasWinCFI = false;
1024 
1025   // Debug location must be unknown since the first debug location is used
1026   // to determine the end of the prologue.
1027   DebugLoc DL;
1028 
1029   // Add RETADDR move area to callee saved frame size.
1030   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1031   if (TailCallReturnAddrDelta && IsWin64Prologue)
1032     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
1033 
1034   if (TailCallReturnAddrDelta < 0)
1035     X86FI->setCalleeSavedFrameSize(
1036       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
1037 
1038   bool UseStackProbe = !STI.getTargetLowering()->getStackProbeSymbolName(MF).empty();
1039   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
1040 
1041   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
1042   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
1043   // stack alignment.
1044   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
1045       Fn.arg_size() == 2) {
1046     StackSize += 8;
1047     MFI.setStackSize(StackSize);
1048     emitSPUpdate(MBB, MBBI, DL, -8, /*InEpilogue=*/false);
1049   }
1050 
1051   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
1052   // function, and use up to 128 bytes of stack space, don't have a frame
1053   // pointer, calls, or dynamic alloca then we do not need to adjust the
1054   // stack pointer (we fit in the Red Zone). We also check that we don't
1055   // push and pop from the stack.
1056   if (has128ByteRedZone(MF) &&
1057       !TRI->needsStackRealignment(MF) &&
1058       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
1059       !MFI.adjustsStack() &&                   // No calls.
1060       !UseStackProbe &&                        // No stack probes.
1061       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
1062       !MF.shouldSplitStack()) {                // Regular stack
1063     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
1064     if (HasFP) MinSize += SlotSize;
1065     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
1066     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
1067     MFI.setStackSize(StackSize);
1068   }
1069 
1070   // Insert stack pointer adjustment for later moving of return addr.  Only
1071   // applies to tail call optimized functions where the callee argument stack
1072   // size is bigger than the callers.
1073   if (TailCallReturnAddrDelta < 0) {
1074     BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta,
1075                          /*InEpilogue=*/false)
1076         .setMIFlag(MachineInstr::FrameSetup);
1077   }
1078 
1079   // Mapping for machine moves:
1080   //
1081   //   DST: VirtualFP AND
1082   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
1083   //        ELSE                        => DW_CFA_def_cfa
1084   //
1085   //   SRC: VirtualFP AND
1086   //        DST: Register               => DW_CFA_def_cfa_register
1087   //
1088   //   ELSE
1089   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
1090   //        REG < 64                    => DW_CFA_offset + Reg
1091   //        ELSE                        => DW_CFA_offset_extended
1092 
1093   uint64_t NumBytes = 0;
1094   int stackGrowth = -SlotSize;
1095 
1096   // Find the funclet establisher parameter
1097   Register Establisher = X86::NoRegister;
1098   if (IsClrFunclet)
1099     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1100   else if (IsFunclet)
1101     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1102 
1103   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
1104     // Immediately spill establisher into the home slot.
1105     // The runtime cares about this.
1106     // MOV64mr %rdx, 16(%rsp)
1107     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1108     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
1109         .addReg(Establisher)
1110         .setMIFlag(MachineInstr::FrameSetup);
1111     MBB.addLiveIn(Establisher);
1112   }
1113 
1114   if (HasFP) {
1115     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
1116 
1117     // Calculate required stack adjustment.
1118     uint64_t FrameSize = StackSize - SlotSize;
1119     // If required, include space for extra hidden slot for stashing base pointer.
1120     if (X86FI->getRestoreBasePointer())
1121       FrameSize += SlotSize;
1122 
1123     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
1124 
1125     // Callee-saved registers are pushed on stack before the stack is realigned.
1126     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1127       NumBytes = alignTo(NumBytes, MaxAlign);
1128 
1129     // Save EBP/RBP into the appropriate stack slot.
1130     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
1131       .addReg(MachineFramePtr, RegState::Kill)
1132       .setMIFlag(MachineInstr::FrameSetup);
1133 
1134     if (NeedsDwarfCFI) {
1135       // Mark the place where EBP/RBP was saved.
1136       // Define the current CFA rule to use the provided offset.
1137       assert(StackSize);
1138       BuildCFI(MBB, MBBI, DL,
1139                MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
1140 
1141       // Change the rule for the FramePtr to be an "offset" rule.
1142       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1143       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
1144                                   nullptr, DwarfFramePtr, 2 * stackGrowth));
1145     }
1146 
1147     if (NeedsWinCFI) {
1148       HasWinCFI = true;
1149       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1150           .addImm(FramePtr)
1151           .setMIFlag(MachineInstr::FrameSetup);
1152     }
1153 
1154     if (!IsWin64Prologue && !IsFunclet) {
1155       // Update EBP with the new base value.
1156       BuildMI(MBB, MBBI, DL,
1157               TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1158               FramePtr)
1159           .addReg(StackPtr)
1160           .setMIFlag(MachineInstr::FrameSetup);
1161 
1162       if (NeedsDwarfCFI) {
1163         // Mark effective beginning of when frame pointer becomes valid.
1164         // Define the current CFA to use the EBP/RBP register.
1165         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1166         BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister(
1167                                     nullptr, DwarfFramePtr));
1168       }
1169 
1170       if (SaveArgs && !Fn.arg_empty()) {
1171         ArrayRef<MCPhysReg> GPRs =
1172           get64BitArgumentGPRs(Fn.getCallingConv(), STI);
1173         unsigned arg_size = Fn.arg_size();
1174         unsigned RI = 0;
1175         int64_t SaveSize = 0;
1176 
1177         if (Fn.hasStructRetAttr()) {
1178           GPRs = GPRs.drop_front(1);
1179           arg_size--;
1180         }
1181 
1182         for (MCPhysReg Reg : GPRs) {
1183           if (++RI > arg_size)
1184             break;
1185 
1186           SaveSize += SlotSize;
1187 
1188           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1189             .addReg(Reg)
1190             .setMIFlag(MachineInstr::FrameSetup);
1191         }
1192 
1193         // Realign the stack. PUSHes are the most space efficient.
1194         while (SaveSize % getStackAlignment()) {
1195           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1196             .addReg(GPRs.front())
1197             .setMIFlag(MachineInstr::FrameSetup);
1198 
1199           SaveSize += SlotSize;
1200         }
1201 
1202 	//dlg StackSize -= SaveSize;
1203         //dlg MFI.setStackSize(StackSize);
1204         X86FI->setSaveArgSize(SaveSize);
1205       }
1206 
1207       if (NeedsWinFPO) {
1208         // .cv_fpo_setframe $FramePtr
1209         HasWinCFI = true;
1210         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
1211             .addImm(FramePtr)
1212             .addImm(0)
1213             .setMIFlag(MachineInstr::FrameSetup);
1214       }
1215     }
1216   } else {
1217     assert(!IsFunclet && "funclets without FPs not yet implemented");
1218     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
1219   }
1220 
1221   // Update the offset adjustment, which is mainly used by codeview to translate
1222   // from ESP to VFRAME relative local variable offsets.
1223   if (!IsFunclet) {
1224     if (HasFP && TRI->needsStackRealignment(MF))
1225       MFI.setOffsetAdjustment(-NumBytes);
1226     else
1227       MFI.setOffsetAdjustment(-StackSize);
1228   }
1229 
1230   // For EH funclets, only allocate enough space for outgoing calls. Save the
1231   // NumBytes value that we would've used for the parent frame.
1232   unsigned ParentFrameNumBytes = NumBytes;
1233   if (IsFunclet)
1234     NumBytes = getWinEHFuncletFrameSize(MF);
1235 
1236   // Skip the callee-saved push instructions.
1237   bool PushedRegs = false;
1238   int StackOffset = 2 * stackGrowth;
1239 
1240   while (MBBI != MBB.end() &&
1241          MBBI->getFlag(MachineInstr::FrameSetup) &&
1242          (MBBI->getOpcode() == X86::PUSH32r ||
1243           MBBI->getOpcode() == X86::PUSH64r)) {
1244     PushedRegs = true;
1245     Register Reg = MBBI->getOperand(0).getReg();
1246     ++MBBI;
1247 
1248     if (!HasFP && NeedsDwarfCFI) {
1249       // Mark callee-saved push instruction.
1250       // Define the current CFA rule to use the provided offset.
1251       assert(StackSize);
1252       BuildCFI(MBB, MBBI, DL,
1253                MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
1254       StackOffset += stackGrowth;
1255     }
1256 
1257     if (NeedsWinCFI) {
1258       HasWinCFI = true;
1259       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1260           .addImm(Reg)
1261           .setMIFlag(MachineInstr::FrameSetup);
1262     }
1263   }
1264 
1265   // Realign stack after we pushed callee-saved registers (so that we'll be
1266   // able to calculate their offsets from the frame pointer).
1267   // Don't do this for Win64, it needs to realign the stack after the prologue.
1268   if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) {
1269     assert(HasFP && "There should be a frame pointer if stack is realigned.");
1270     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1271 
1272     if (NeedsWinCFI) {
1273       HasWinCFI = true;
1274       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
1275           .addImm(MaxAlign)
1276           .setMIFlag(MachineInstr::FrameSetup);
1277     }
1278   }
1279 
1280   // If there is an SUB32ri of ESP immediately before this instruction, merge
1281   // the two. This can be the case when tail call elimination is enabled and
1282   // the callee has more arguments then the caller.
1283   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
1284 
1285   // Adjust stack pointer: ESP -= numbytes.
1286 
1287   // Windows and cygwin/mingw require a prologue helper routine when allocating
1288   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
1289   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
1290   // stack and adjust the stack pointer in one go.  The 64-bit version of
1291   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
1292   // responsible for adjusting the stack pointer.  Touching the stack at 4K
1293   // increments is necessary to ensure that the guard pages used by the OS
1294   // virtual memory manager are allocated in correct sequence.
1295   uint64_t AlignedNumBytes = NumBytes;
1296   if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF))
1297     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
1298   if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
1299     assert(!X86FI->getUsesRedZone() &&
1300            "The Red Zone is not accounted for in stack probes");
1301 
1302     // Check whether EAX is livein for this block.
1303     bool isEAXAlive = isEAXLiveIn(MBB);
1304 
1305     if (isEAXAlive) {
1306       if (Is64Bit) {
1307         // Save RAX
1308         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1309           .addReg(X86::RAX, RegState::Kill)
1310           .setMIFlag(MachineInstr::FrameSetup);
1311       } else {
1312         // Save EAX
1313         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
1314           .addReg(X86::EAX, RegState::Kill)
1315           .setMIFlag(MachineInstr::FrameSetup);
1316       }
1317     }
1318 
1319     if (Is64Bit) {
1320       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
1321       // Function prologue is responsible for adjusting the stack pointer.
1322       int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
1323       if (isUInt<32>(Alloc)) {
1324         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1325             .addImm(Alloc)
1326             .setMIFlag(MachineInstr::FrameSetup);
1327       } else if (isInt<32>(Alloc)) {
1328         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
1329             .addImm(Alloc)
1330             .setMIFlag(MachineInstr::FrameSetup);
1331       } else {
1332         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
1333             .addImm(Alloc)
1334             .setMIFlag(MachineInstr::FrameSetup);
1335       }
1336     } else {
1337       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
1338       // We'll also use 4 already allocated bytes for EAX.
1339       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1340           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
1341           .setMIFlag(MachineInstr::FrameSetup);
1342     }
1343 
1344     // Call __chkstk, __chkstk_ms, or __alloca.
1345     emitStackProbe(MF, MBB, MBBI, DL, true);
1346 
1347     if (isEAXAlive) {
1348       // Restore RAX/EAX
1349       MachineInstr *MI;
1350       if (Is64Bit)
1351         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
1352                           StackPtr, false, NumBytes - 8);
1353       else
1354         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
1355                           StackPtr, false, NumBytes - 4);
1356       MI->setFlag(MachineInstr::FrameSetup);
1357       MBB.insert(MBBI, MI);
1358     }
1359   } else if (NumBytes) {
1360     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
1361   }
1362 
1363   if (NeedsWinCFI && NumBytes) {
1364     HasWinCFI = true;
1365     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
1366         .addImm(NumBytes)
1367         .setMIFlag(MachineInstr::FrameSetup);
1368   }
1369 
1370   int SEHFrameOffset = 0;
1371   unsigned SPOrEstablisher;
1372   if (IsFunclet) {
1373     if (IsClrFunclet) {
1374       // The establisher parameter passed to a CLR funclet is actually a pointer
1375       // to the (mostly empty) frame of its nearest enclosing funclet; we have
1376       // to find the root function establisher frame by loading the PSPSym from
1377       // the intermediate frame.
1378       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1379       MachinePointerInfo NoInfo;
1380       MBB.addLiveIn(Establisher);
1381       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
1382                    Establisher, false, PSPSlotOffset)
1383           .addMemOperand(MF.getMachineMemOperand(
1384               NoInfo, MachineMemOperand::MOLoad, SlotSize, SlotSize));
1385       ;
1386       // Save the root establisher back into the current funclet's (mostly
1387       // empty) frame, in case a sub-funclet or the GC needs it.
1388       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
1389                    false, PSPSlotOffset)
1390           .addReg(Establisher)
1391           .addMemOperand(
1392               MF.getMachineMemOperand(NoInfo, MachineMemOperand::MOStore |
1393                                                   MachineMemOperand::MOVolatile,
1394                                       SlotSize, SlotSize));
1395     }
1396     SPOrEstablisher = Establisher;
1397   } else {
1398     SPOrEstablisher = StackPtr;
1399   }
1400 
1401   if (IsWin64Prologue && HasFP) {
1402     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
1403     // this calculation on the incoming establisher, which holds the value of
1404     // RSP from the parent frame at the end of the prologue.
1405     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
1406     if (SEHFrameOffset)
1407       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
1408                    SPOrEstablisher, false, SEHFrameOffset);
1409     else
1410       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
1411           .addReg(SPOrEstablisher);
1412 
1413     // If this is not a funclet, emit the CFI describing our frame pointer.
1414     if (NeedsWinCFI && !IsFunclet) {
1415       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
1416       HasWinCFI = true;
1417       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
1418           .addImm(FramePtr)
1419           .addImm(SEHFrameOffset)
1420           .setMIFlag(MachineInstr::FrameSetup);
1421       if (isAsynchronousEHPersonality(Personality))
1422         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
1423     }
1424   } else if (IsFunclet && STI.is32Bit()) {
1425     // Reset EBP / ESI to something good for funclets.
1426     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
1427     // If we're a catch funclet, we can be returned to via catchret. Save ESP
1428     // into the registration node so that the runtime will restore it for us.
1429     if (!MBB.isCleanupFuncletEntry()) {
1430       assert(Personality == EHPersonality::MSVC_CXX);
1431       unsigned FrameReg;
1432       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
1433       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg);
1434       // ESP is the first field, so no extra displacement is needed.
1435       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
1436                    false, EHRegOffset)
1437           .addReg(X86::ESP);
1438     }
1439   }
1440 
1441   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
1442     const MachineInstr &FrameInstr = *MBBI;
1443     ++MBBI;
1444 
1445     if (NeedsWinCFI) {
1446       int FI;
1447       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
1448         if (X86::FR64RegClass.contains(Reg)) {
1449           int Offset;
1450           unsigned IgnoredFrameReg;
1451           if (IsWin64Prologue && IsFunclet)
1452             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
1453           else
1454             Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg) +
1455                      SEHFrameOffset;
1456 
1457           HasWinCFI = true;
1458           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
1459           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
1460               .addImm(Reg)
1461               .addImm(Offset)
1462               .setMIFlag(MachineInstr::FrameSetup);
1463         }
1464       }
1465     }
1466   }
1467 
1468   if (NeedsWinCFI && HasWinCFI)
1469     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
1470         .setMIFlag(MachineInstr::FrameSetup);
1471 
1472   if (FnHasClrFunclet && !IsFunclet) {
1473     // Save the so-called Initial-SP (i.e. the value of the stack pointer
1474     // immediately after the prolog)  into the PSPSlot so that funclets
1475     // and the GC can recover it.
1476     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1477     auto PSPInfo = MachinePointerInfo::getFixedStack(
1478         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
1479     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
1480                  PSPSlotOffset)
1481         .addReg(StackPtr)
1482         .addMemOperand(MF.getMachineMemOperand(
1483             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
1484             SlotSize, SlotSize));
1485   }
1486 
1487   // Realign stack after we spilled callee-saved registers (so that we'll be
1488   // able to calculate their offsets from the frame pointer).
1489   // Win64 requires aligning the stack after the prologue.
1490   if (IsWin64Prologue && TRI->needsStackRealignment(MF)) {
1491     assert(HasFP && "There should be a frame pointer if stack is realigned.");
1492     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
1493   }
1494 
1495   // We already dealt with stack realignment and funclets above.
1496   if (IsFunclet && STI.is32Bit())
1497     return;
1498 
1499   // If we need a base pointer, set it up here. It's whatever the value
1500   // of the stack pointer is at this point. Any variable size objects
1501   // will be allocated after this, so we can still use the base pointer
1502   // to reference locals.
1503   if (TRI->hasBasePointer(MF)) {
1504     // Update the base pointer with the current stack pointer.
1505     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
1506     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
1507       .addReg(SPOrEstablisher)
1508       .setMIFlag(MachineInstr::FrameSetup);
1509     if (X86FI->getRestoreBasePointer()) {
1510       // Stash value of base pointer.  Saving RSP instead of EBP shortens
1511       // dependence chain. Used by SjLj EH.
1512       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1513       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
1514                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
1515         .addReg(SPOrEstablisher)
1516         .setMIFlag(MachineInstr::FrameSetup);
1517     }
1518 
1519     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
1520       // Stash the value of the frame pointer relative to the base pointer for
1521       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
1522       // it recovers the frame pointer from the base pointer rather than the
1523       // other way around.
1524       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1525       unsigned UsedReg;
1526       int Offset =
1527           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
1528       assert(UsedReg == BasePtr);
1529       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
1530           .addReg(FramePtr)
1531           .setMIFlag(MachineInstr::FrameSetup);
1532     }
1533   }
1534 
1535   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
1536     // Mark end of stack pointer adjustment.
1537     if (!HasFP && NumBytes) {
1538       // Define the current CFA rule to use the provided offset.
1539       assert(StackSize);
1540       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
1541                                   nullptr, -StackSize + stackGrowth));
1542     }
1543 
1544     // Emit DWARF info specifying the offsets of the callee-saved registers.
1545     emitCalleeSavedFrameMoves(MBB, MBBI, DL);
1546   }
1547 
1548   // X86 Interrupt handling function cannot assume anything about the direction
1549   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
1550   // in each prologue of interrupt handler function.
1551   //
1552   // FIXME: Create "cld" instruction only in these cases:
1553   // 1. The interrupt handling function uses any of the "rep" instructions.
1554   // 2. Interrupt handling function calls another function.
1555   //
1556   if (Fn.getCallingConv() == CallingConv::X86_INTR)
1557     BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
1558         .setMIFlag(MachineInstr::FrameSetup);
1559 
1560   // At this point we know if the function has WinCFI or not.
1561   MF.setHasWinCFI(HasWinCFI);
1562 }
1563 
1564 bool X86FrameLowering::canUseLEAForSPInEpilogue(
1565     const MachineFunction &MF) const {
1566   // We can't use LEA instructions for adjusting the stack pointer if we don't
1567   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
1568   // to deallocate the stack.
1569   // This means that we can use LEA for SP in two situations:
1570   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
1571   // 2. We *have* a frame pointer which means we are permitted to use LEA.
1572   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
1573 }
1574 
1575 static bool isFuncletReturnInstr(MachineInstr &MI) {
1576   switch (MI.getOpcode()) {
1577   case X86::CATCHRET:
1578   case X86::CLEANUPRET:
1579     return true;
1580   default:
1581     return false;
1582   }
1583   llvm_unreachable("impossible");
1584 }
1585 
1586 // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
1587 // stack. It holds a pointer to the bottom of the root function frame.  The
1588 // establisher frame pointer passed to a nested funclet may point to the
1589 // (mostly empty) frame of its parent funclet, but it will need to find
1590 // the frame of the root function to access locals.  To facilitate this,
1591 // every funclet copies the pointer to the bottom of the root function
1592 // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
1593 // same offset for the PSPSym in the root function frame that's used in the
1594 // funclets' frames allows each funclet to dynamically accept any ancestor
1595 // frame as its establisher argument (the runtime doesn't guarantee the
1596 // immediate parent for some reason lost to history), and also allows the GC,
1597 // which uses the PSPSym for some bookkeeping, to find it in any funclet's
1598 // frame with only a single offset reported for the entire method.
1599 unsigned
1600 X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
1601   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
1602   unsigned SPReg;
1603   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
1604                                               /*IgnoreSPUpdates*/ true);
1605   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
1606   return static_cast<unsigned>(Offset);
1607 }
1608 
1609 unsigned
1610 X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
1611   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1612   // This is the size of the pushed CSRs.
1613   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1614   // This is the size of callee saved XMMs.
1615   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
1616   unsigned XMMSize = WinEHXMMSlotInfo.size() *
1617                      TRI->getSpillSize(X86::VR128RegClass);
1618   // This is the amount of stack a funclet needs to allocate.
1619   unsigned UsedSize;
1620   EHPersonality Personality =
1621       classifyEHPersonality(MF.getFunction().getPersonalityFn());
1622   if (Personality == EHPersonality::CoreCLR) {
1623     // CLR funclets need to hold enough space to include the PSPSym, at the
1624     // same offset from the stack pointer (immediately after the prolog) as it
1625     // resides at in the main function.
1626     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
1627   } else {
1628     // Other funclets just need enough stack for outgoing call arguments.
1629     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
1630   }
1631   // RBP is not included in the callee saved register block. After pushing RBP,
1632   // everything is 16 byte aligned. Everything we allocate before an outgoing
1633   // call must also be 16 byte aligned.
1634   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlignment());
1635   // Subtract out the size of the callee saved registers. This is how much stack
1636   // each funclet will allocate.
1637   return FrameSizeMinusRBP + XMMSize - CSSize;
1638 }
1639 
1640 static bool isTailCallOpcode(unsigned Opc) {
1641     return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
1642         Opc == X86::TCRETURNmi ||
1643         Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 ||
1644         Opc == X86::TCRETURNmi64;
1645 }
1646 
1647 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
1648                                     MachineBasicBlock &MBB) const {
1649   const MachineFrameInfo &MFI = MF.getFrameInfo();
1650   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1651   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
1652   MachineBasicBlock::iterator MBBI = Terminator;
1653   DebugLoc DL;
1654   if (MBBI != MBB.end())
1655     DL = MBBI->getDebugLoc();
1656   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1657   const bool Is64BitILP32 = STI.isTarget64BitILP32();
1658   Register FramePtr = TRI->getFrameRegister(MF);
1659   unsigned MachineFramePtr =
1660       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
1661 
1662   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1663   bool NeedsWin64CFI =
1664       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
1665   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
1666 
1667   // Get the number of bytes to allocate from the FrameInfo.
1668   uint64_t StackSize = MFI.getStackSize();
1669   uint64_t MaxAlign = calculateMaxStackAlign(MF);
1670   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1671   bool HasFP = hasFP(MF);
1672   uint64_t NumBytes = 0;
1673 
1674   bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
1675                         !MF.getTarget().getTargetTriple().isOSWindows()) &&
1676                        MF.needsFrameMoves();
1677 
1678   if (IsFunclet) {
1679     assert(HasFP && "EH funclets without FP not yet implemented");
1680     NumBytes = getWinEHFuncletFrameSize(MF);
1681   } else if (HasFP) {
1682     // Calculate required stack adjustment.
1683     uint64_t FrameSize = StackSize - SlotSize;
1684     NumBytes = FrameSize - CSSize;
1685 
1686     // Callee-saved registers were pushed on stack before the stack was
1687     // realigned.
1688     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1689       NumBytes = alignTo(FrameSize, MaxAlign);
1690   } else {
1691     NumBytes = StackSize - CSSize;
1692   }
1693   uint64_t SEHStackAllocAmt = NumBytes;
1694 
1695   MachineBasicBlock::iterator FirstCSPop = MBBI;
1696   // Skip the callee-saved pop instructions.
1697   while (MBBI != MBB.begin()) {
1698     MachineBasicBlock::iterator PI = std::prev(MBBI);
1699     unsigned Opc = PI->getOpcode();
1700 
1701     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
1702       if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
1703           (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)))
1704         break;
1705       FirstCSPop = PI;
1706     }
1707 
1708     --MBBI;
1709   }
1710   MBBI = FirstCSPop;
1711 
1712   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
1713     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
1714 
1715   if (MBBI != MBB.end())
1716     DL = MBBI->getDebugLoc();
1717 
1718   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1719   // instruction, merge the two instructions.
1720   if (NumBytes || MFI.hasVarSizedObjects())
1721     NumBytes += mergeSPUpdates(MBB, MBBI, true);
1722 
1723   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1724   // slot before popping them off! Same applies for the case, when stack was
1725   // realigned. Don't do this if this was a funclet epilogue, since the funclets
1726   // will not do realignment or dynamic stack allocation.
1727   if ((TRI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) &&
1728       !IsFunclet) {
1729     if (TRI->needsStackRealignment(MF))
1730       MBBI = FirstCSPop;
1731     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1732     uint64_t LEAAmount =
1733         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1734 
1735     // There are only two legal forms of epilogue:
1736     // - add SEHAllocationSize, %rsp
1737     // - lea SEHAllocationSize(%FramePtr), %rsp
1738     //
1739     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1740     // However, we may use this sequence if we have a frame pointer because the
1741     // effects of the prologue can safely be undone.
1742     if (LEAAmount != 0) {
1743       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1744       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1745                    FramePtr, false, LEAAmount);
1746       --MBBI;
1747     } else {
1748       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1749       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1750         .addReg(FramePtr);
1751       --MBBI;
1752     }
1753   } else if (NumBytes) {
1754     // Adjust stack pointer back: ESP += numbytes.
1755     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
1756     if (!hasFP(MF) && NeedsDwarfCFI) {
1757       // Define the current CFA rule to use the provided offset.
1758       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
1759                                   nullptr, -CSSize - SlotSize));
1760     }
1761     --MBBI;
1762   }
1763 
1764   if (HasFP) {
1765     MBBI = Terminator;
1766 
1767     if (X86FI->getSaveArgSize()) {
1768       // LEAVE is effectively mov rbp,rsp; pop rbp
1769       BuildMI(MBB, MBBI, DL, TII.get(X86::LEAVE64))
1770         .setMIFlag(MachineInstr::FrameDestroy);
1771     } else {
1772       // Pop EBP.
1773       BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
1774               MachineFramePtr)
1775           .setMIFlag(MachineInstr::FrameDestroy);
1776     }
1777     if (NeedsDwarfCFI) {
1778       unsigned DwarfStackPtr =
1779           TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
1780       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfa(
1781                                   nullptr, DwarfStackPtr, -SlotSize));
1782       --MBBI;
1783     }
1784   }
1785 
1786   // Windows unwinder will not invoke function's exception handler if IP is
1787   // either in prologue or in epilogue.  This behavior causes a problem when a
1788   // call immediately precedes an epilogue, because the return address points
1789   // into the epilogue.  To cope with that, we insert an epilogue marker here,
1790   // then replace it with a 'nop' if it ends up immediately after a CALL in the
1791   // final emitted code.
1792   if (NeedsWin64CFI && MF.hasWinCFI())
1793     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1794 
1795   if (!hasFP(MF) && NeedsDwarfCFI) {
1796     MBBI = FirstCSPop;
1797     int64_t Offset = -CSSize - SlotSize;
1798     // Mark callee-saved pop instruction.
1799     // Define the current CFA rule to use the provided offset.
1800     while (MBBI != MBB.end()) {
1801       MachineBasicBlock::iterator PI = MBBI;
1802       unsigned Opc = PI->getOpcode();
1803       ++MBBI;
1804       if (Opc == X86::POP32r || Opc == X86::POP64r) {
1805         Offset += SlotSize;
1806         BuildCFI(MBB, MBBI, DL,
1807                  MCCFIInstruction::createDefCfaOffset(nullptr, Offset));
1808       }
1809     }
1810   }
1811 
1812   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
1813     // Add the return addr area delta back since we are not tail calling.
1814     int Offset = -1 * X86FI->getTCReturnAddrDelta();
1815     assert(Offset >= 0 && "TCDelta should never be positive");
1816     if (Offset) {
1817       // Check for possible merge with preceding ADD instruction.
1818       Offset += mergeSPUpdates(MBB, Terminator, true);
1819       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
1820     }
1821   }
1822 }
1823 
1824 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1825                                              unsigned &FrameReg) const {
1826   const MachineFrameInfo &MFI = MF.getFrameInfo();
1827 
1828   bool IsFixed = MFI.isFixedObjectIndex(FI);
1829   // We can't calculate offset from frame pointer if the stack is realigned,
1830   // so enforce usage of stack/base pointer.  The base pointer is used when we
1831   // have dynamic allocas in addition to dynamic realignment.
1832   if (TRI->hasBasePointer(MF))
1833     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
1834   else if (TRI->needsStackRealignment(MF))
1835     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
1836   else
1837     FrameReg = TRI->getFrameRegister(MF);
1838 
1839   // Offset will hold the offset from the stack pointer at function entry to the
1840   // object.
1841   // We need to factor in additional offsets applied during the prologue to the
1842   // frame, base, and stack pointer depending on which is used.
1843   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
1844   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1845   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1846   uint64_t StackSize = MFI.getStackSize();
1847   bool HasFP = hasFP(MF);
1848   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1849   int64_t FPDelta = 0;
1850 
1851   // In an x86 interrupt, remove the offset we added to account for the return
1852   // address from any stack object allocated in the caller's frame. Interrupts
1853   // do not have a standard return address. Fixed objects in the current frame,
1854   // such as SSE register spills, should not get this treatment.
1855   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
1856       Offset >= 0) {
1857     Offset += getOffsetOfLocalArea();
1858   }
1859 
1860   if (IsWin64Prologue) {
1861     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
1862 
1863     // Calculate required stack adjustment.
1864     uint64_t FrameSize = StackSize - SlotSize;
1865     // If required, include space for extra hidden slot for stashing base pointer.
1866     if (X86FI->getRestoreBasePointer())
1867       FrameSize += SlotSize;
1868     uint64_t NumBytes = FrameSize - CSSize;
1869 
1870     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1871     if (FI && FI == X86FI->getFAIndex())
1872       return -SEHFrameOffset;
1873 
1874     // FPDelta is the offset from the "traditional" FP location of the old base
1875     // pointer followed by return address and the location required by the
1876     // restricted Win64 prologue.
1877     // Add FPDelta to all offsets below that go through the frame pointer.
1878     FPDelta = FrameSize - SEHFrameOffset;
1879     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
1880            "FPDelta isn't aligned per the Win64 ABI!");
1881   }
1882 
1883   if (FI >= 0)
1884     Offset -= X86FI->getSaveArgSize();
1885 
1886   if (TRI->hasBasePointer(MF)) {
1887     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1888     if (FI < 0) {
1889       // Skip the saved EBP.
1890       return Offset + SlotSize + FPDelta;
1891     } else {
1892       assert((-(Offset + StackSize)) % MFI.getObjectAlignment(FI) == 0);
1893       return Offset + StackSize;
1894     }
1895   } else if (TRI->needsStackRealignment(MF)) {
1896     if (FI < 0) {
1897       // Skip the saved EBP.
1898       return Offset + SlotSize + FPDelta;
1899     } else {
1900       assert((-(Offset + StackSize)) % MFI.getObjectAlignment(FI) == 0);
1901       return Offset + StackSize;
1902     }
1903     // FIXME: Support tail calls
1904   } else {
1905     if (!HasFP)
1906       return Offset + StackSize;
1907 
1908     // Skip the saved EBP.
1909     Offset += SlotSize;
1910 
1911     // Skip the RETADDR move area
1912     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1913     if (TailCallReturnAddrDelta < 0)
1914       Offset -= TailCallReturnAddrDelta;
1915   }
1916 
1917   return Offset + FPDelta;
1918 }
1919 
1920 int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF,
1921                                               int FI, unsigned &FrameReg) const {
1922   const MachineFrameInfo &MFI = MF.getFrameInfo();
1923   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1924   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
1925   const auto it = WinEHXMMSlotInfo.find(FI);
1926 
1927   if (it == WinEHXMMSlotInfo.end())
1928     return getFrameIndexReference(MF, FI, FrameReg);
1929 
1930   FrameReg = TRI->getStackRegister();
1931   return alignDown(MFI.getMaxCallFrameSize(), getStackAlignment()) + it->second;
1932 }
1933 
1934 int X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF,
1935                                                int FI, unsigned &FrameReg,
1936                                                int Adjustment) const {
1937   const MachineFrameInfo &MFI = MF.getFrameInfo();
1938   FrameReg = TRI->getStackRegister();
1939   return MFI.getObjectOffset(FI) - getOffsetOfLocalArea() + Adjustment;
1940 }
1941 
1942 int
1943 X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
1944                                                  int FI, unsigned &FrameReg,
1945                                                  bool IgnoreSPUpdates) const {
1946 
1947   const MachineFrameInfo &MFI = MF.getFrameInfo();
1948   // Does not include any dynamic realign.
1949   const uint64_t StackSize = MFI.getStackSize();
1950   // LLVM arranges the stack as follows:
1951   //   ...
1952   //   ARG2
1953   //   ARG1
1954   //   RETADDR
1955   //   PUSH RBP   <-- RBP points here
1956   //   PUSH CSRs
1957   //   ~~~~~~~    <-- possible stack realignment (non-win64)
1958   //   ...
1959   //   STACK OBJECTS
1960   //   ...        <-- RSP after prologue points here
1961   //   ~~~~~~~    <-- possible stack realignment (win64)
1962   //
1963   // if (hasVarSizedObjects()):
1964   //   ...        <-- "base pointer" (ESI/RBX) points here
1965   //   DYNAMIC ALLOCAS
1966   //   ...        <-- RSP points here
1967   //
1968   // Case 1: In the simple case of no stack realignment and no dynamic
1969   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
1970   // with fixed offsets from RSP.
1971   //
1972   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
1973   // stack objects are addressed with RBP and regular stack objects with RSP.
1974   //
1975   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
1976   // to address stack arguments for outgoing calls and nothing else. The "base
1977   // pointer" points to local variables, and RBP points to fixed objects.
1978   //
1979   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
1980   // answer we give is relative to the SP after the prologue, and not the
1981   // SP in the middle of the function.
1982 
1983   if (MFI.isFixedObjectIndex(FI) && TRI->needsStackRealignment(MF) &&
1984       !STI.isTargetWin64())
1985     return getFrameIndexReference(MF, FI, FrameReg);
1986 
1987   // If !hasReservedCallFrame the function might have SP adjustement in the
1988   // body.  So, even though the offset is statically known, it depends on where
1989   // we are in the function.
1990   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
1991     return getFrameIndexReference(MF, FI, FrameReg);
1992 
1993   // We don't handle tail calls, and shouldn't be seeing them either.
1994   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
1995          "we don't handle this case!");
1996 
1997   // This is how the math works out:
1998   //
1999   //  %rsp grows (i.e. gets lower) left to right. Each box below is
2000   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
2001   //  get to.
2002   //
2003   //    ----------------------------------
2004   //    | BP | Obj0 | Obj1 | ... | ObjN |
2005   //    ----------------------------------
2006   //    ^    ^      ^                   ^
2007   //    A    B      C                   E
2008   //
2009   // A is the incoming stack pointer.
2010   // (B - A) is the local area offset (-8 for x86-64) [1]
2011   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
2012   //
2013   // |(E - B)| is the StackSize (absolute value, positive).  For a
2014   // stack that grown down, this works out to be (B - E). [3]
2015   //
2016   // E is also the value of %rsp after stack has been set up, and we
2017   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
2018   // (C - E) == (C - A) - (B - A) + (B - E)
2019   //            { Using [1], [2] and [3] above }
2020   //         == getObjectOffset - LocalAreaOffset + StackSize
2021 
2022   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
2023 }
2024 
2025 bool X86FrameLowering::assignCalleeSavedSpillSlots(
2026     MachineFunction &MF, const TargetRegisterInfo *TRI,
2027     std::vector<CalleeSavedInfo> &CSI) const {
2028   MachineFrameInfo &MFI = MF.getFrameInfo();
2029   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2030 
2031   unsigned CalleeSavedFrameSize = 0;
2032   unsigned XMMCalleeSavedFrameSize = 0;
2033   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2034   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
2035 
2036   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
2037 
2038   if (TailCallReturnAddrDelta < 0) {
2039     // create RETURNADDR area
2040     //   arg
2041     //   arg
2042     //   RETADDR
2043     //   { ...
2044     //     RETADDR area
2045     //     ...
2046     //   }
2047     //   [EBP]
2048     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
2049                            TailCallReturnAddrDelta - SlotSize, true);
2050   }
2051 
2052   // Spill the BasePtr if it's used.
2053   if (this->TRI->hasBasePointer(MF)) {
2054     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
2055     if (MF.hasEHFunclets()) {
2056       int FI = MFI.CreateSpillStackObject(SlotSize, SlotSize);
2057       X86FI->setHasSEHFramePtrSave(true);
2058       X86FI->setSEHFramePtrSaveIndex(FI);
2059     }
2060   }
2061 
2062   if (hasFP(MF)) {
2063     // emitPrologue always spills frame register the first thing.
2064     SpillSlotOffset -= SlotSize;
2065     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2066 
2067     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
2068     // the frame register, we can delete it from CSI list and not have to worry
2069     // about avoiding it later.
2070     Register FPReg = TRI->getFrameRegister(MF);
2071     for (unsigned i = 0; i < CSI.size(); ++i) {
2072       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
2073         CSI.erase(CSI.begin() + i);
2074         break;
2075       }
2076     }
2077   }
2078 
2079   // Assign slots for GPRs. It increases frame size.
2080   for (unsigned i = CSI.size(); i != 0; --i) {
2081     unsigned Reg = CSI[i - 1].getReg();
2082 
2083     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
2084       continue;
2085 
2086     SpillSlotOffset -= SlotSize;
2087     CalleeSavedFrameSize += SlotSize;
2088 
2089     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2090     CSI[i - 1].setFrameIdx(SlotIndex);
2091   }
2092 
2093   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
2094   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
2095 
2096   // Assign slots for XMMs.
2097   for (unsigned i = CSI.size(); i != 0; --i) {
2098     unsigned Reg = CSI[i - 1].getReg();
2099     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
2100       continue;
2101 
2102     // If this is k-register make sure we lookup via the largest legal type.
2103     MVT VT = MVT::Other;
2104     if (X86::VK16RegClass.contains(Reg))
2105       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
2106 
2107     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2108     unsigned Size = TRI->getSpillSize(*RC);
2109     unsigned Align = TRI->getSpillAlignment(*RC);
2110     // ensure alignment
2111     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
2112     SpillSlotOffset = -alignTo(-SpillSlotOffset, Align);
2113 
2114     // spill into slot
2115     SpillSlotOffset -= Size;
2116     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
2117     CSI[i - 1].setFrameIdx(SlotIndex);
2118     MFI.ensureMaxAlignment(Align);
2119 
2120     // Save the start offset and size of XMM in stack frame for funclets.
2121     if (X86::VR128RegClass.contains(Reg)) {
2122       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
2123       XMMCalleeSavedFrameSize += Size;
2124     }
2125   }
2126 
2127   return true;
2128 }
2129 
2130 bool X86FrameLowering::spillCalleeSavedRegisters(
2131     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2132     const std::vector<CalleeSavedInfo> &CSI,
2133     const TargetRegisterInfo *TRI) const {
2134   DebugLoc DL = MBB.findDebugLoc(MI);
2135 
2136   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
2137   // for us, and there are no XMM CSRs on Win32.
2138   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
2139     return true;
2140 
2141   // Push GPRs. It increases frame size.
2142   const MachineFunction &MF = *MBB.getParent();
2143   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
2144   for (unsigned i = CSI.size(); i != 0; --i) {
2145     unsigned Reg = CSI[i - 1].getReg();
2146 
2147     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
2148       continue;
2149 
2150     const MachineRegisterInfo &MRI = MF.getRegInfo();
2151     bool isLiveIn = MRI.isLiveIn(Reg);
2152     if (!isLiveIn)
2153       MBB.addLiveIn(Reg);
2154 
2155     // Decide whether we can add a kill flag to the use.
2156     bool CanKill = !isLiveIn;
2157     // Check if any subregister is live-in
2158     if (CanKill) {
2159       for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) {
2160         if (MRI.isLiveIn(*AReg)) {
2161           CanKill = false;
2162           break;
2163         }
2164       }
2165     }
2166 
2167     // Do not set a kill flag on values that are also marked as live-in. This
2168     // happens with the @llvm-returnaddress intrinsic and with arguments
2169     // passed in callee saved registers.
2170     // Omitting the kill flags is conservatively correct even if the live-in
2171     // is not used after all.
2172     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill))
2173       .setMIFlag(MachineInstr::FrameSetup);
2174   }
2175 
2176   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
2177   // It can be done by spilling XMMs to stack frame.
2178   for (unsigned i = CSI.size(); i != 0; --i) {
2179     unsigned Reg = CSI[i-1].getReg();
2180     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
2181       continue;
2182 
2183     // If this is k-register make sure we lookup via the largest legal type.
2184     MVT VT = MVT::Other;
2185     if (X86::VK16RegClass.contains(Reg))
2186       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
2187 
2188     // Add the callee-saved register as live-in. It's killed at the spill.
2189     MBB.addLiveIn(Reg);
2190     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2191 
2192     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
2193                             TRI);
2194     --MI;
2195     MI->setFlag(MachineInstr::FrameSetup);
2196     ++MI;
2197   }
2198 
2199   return true;
2200 }
2201 
2202 void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
2203                                                MachineBasicBlock::iterator MBBI,
2204                                                MachineInstr *CatchRet) const {
2205   // SEH shouldn't use catchret.
2206   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2207              MBB.getParent()->getFunction().getPersonalityFn())) &&
2208          "SEH should not use CATCHRET");
2209   DebugLoc DL = CatchRet->getDebugLoc();
2210   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
2211 
2212   // Fill EAX/RAX with the address of the target block.
2213   if (STI.is64Bit()) {
2214     // LEA64r CatchRetTarget(%rip), %rax
2215     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
2216         .addReg(X86::RIP)
2217         .addImm(0)
2218         .addReg(0)
2219         .addMBB(CatchRetTarget)
2220         .addReg(0);
2221   } else {
2222     // MOV32ri $CatchRetTarget, %eax
2223     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
2224         .addMBB(CatchRetTarget);
2225   }
2226 
2227   // Record that we've taken the address of CatchRetTarget and no longer just
2228   // reference it in a terminator.
2229   CatchRetTarget->setHasAddressTaken();
2230 }
2231 
2232 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
2233                                                MachineBasicBlock::iterator MI,
2234                                           std::vector<CalleeSavedInfo> &CSI,
2235                                           const TargetRegisterInfo *TRI) const {
2236   if (CSI.empty())
2237     return false;
2238 
2239   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
2240     // Don't restore CSRs in 32-bit EH funclets. Matches
2241     // spillCalleeSavedRegisters.
2242     if (STI.is32Bit())
2243       return true;
2244     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
2245     // funclets. emitEpilogue transforms these to normal jumps.
2246     if (MI->getOpcode() == X86::CATCHRET) {
2247       const Function &F = MBB.getParent()->getFunction();
2248       bool IsSEH = isAsynchronousEHPersonality(
2249           classifyEHPersonality(F.getPersonalityFn()));
2250       if (IsSEH)
2251         return true;
2252     }
2253   }
2254 
2255   DebugLoc DL = MBB.findDebugLoc(MI);
2256 
2257   // Reload XMMs from stack frame.
2258   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2259     unsigned Reg = CSI[i].getReg();
2260     if (X86::GR64RegClass.contains(Reg) ||
2261         X86::GR32RegClass.contains(Reg))
2262       continue;
2263 
2264     // If this is k-register make sure we lookup via the largest legal type.
2265     MVT VT = MVT::Other;
2266     if (X86::VK16RegClass.contains(Reg))
2267       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
2268 
2269     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2270     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
2271   }
2272 
2273   // POP GPRs.
2274   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
2275   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2276     unsigned Reg = CSI[i].getReg();
2277     if (!X86::GR64RegClass.contains(Reg) &&
2278         !X86::GR32RegClass.contains(Reg))
2279       continue;
2280 
2281     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
2282         .setMIFlag(MachineInstr::FrameDestroy);
2283   }
2284   return true;
2285 }
2286 
2287 void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
2288                                             BitVector &SavedRegs,
2289                                             RegScavenger *RS) const {
2290   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2291 
2292   // Spill the BasePtr if it's used.
2293   if (TRI->hasBasePointer(MF)){
2294     Register BasePtr = TRI->getBaseRegister();
2295     if (STI.isTarget64BitILP32())
2296       BasePtr = getX86SubSuperRegister(BasePtr, 64);
2297     SavedRegs.set(BasePtr);
2298   }
2299 }
2300 
2301 static bool
2302 HasNestArgument(const MachineFunction *MF) {
2303   const Function &F = MF->getFunction();
2304   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
2305        I != E; I++) {
2306     if (I->hasNestAttr() && !I->use_empty())
2307       return true;
2308   }
2309   return false;
2310 }
2311 
2312 /// GetScratchRegister - Get a temp register for performing work in the
2313 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
2314 /// and the properties of the function either one or two registers will be
2315 /// needed. Set primary to true for the first register, false for the second.
2316 static unsigned
2317 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
2318   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
2319 
2320   // Erlang stuff.
2321   if (CallingConvention == CallingConv::HiPE) {
2322     if (Is64Bit)
2323       return Primary ? X86::R14 : X86::R13;
2324     else
2325       return Primary ? X86::EBX : X86::EDI;
2326   }
2327 
2328   if (Is64Bit) {
2329     if (IsLP64)
2330       return Primary ? X86::R11 : X86::R12;
2331     else
2332       return Primary ? X86::R11D : X86::R12D;
2333   }
2334 
2335   bool IsNested = HasNestArgument(&MF);
2336 
2337   if (CallingConvention == CallingConv::X86_FastCall ||
2338       CallingConvention == CallingConv::Fast ||
2339       CallingConvention == CallingConv::Tail) {
2340     if (IsNested)
2341       report_fatal_error("Segmented stacks does not support fastcall with "
2342                          "nested function.");
2343     return Primary ? X86::EAX : X86::ECX;
2344   }
2345   if (IsNested)
2346     return Primary ? X86::EDX : X86::EAX;
2347   return Primary ? X86::ECX : X86::EAX;
2348 }
2349 
2350 // The stack limit in the TCB is set to this many bytes above the actual stack
2351 // limit.
2352 static const uint64_t kSplitStackAvailable = 256;
2353 
2354 void X86FrameLowering::adjustForSegmentedStacks(
2355     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2356   MachineFrameInfo &MFI = MF.getFrameInfo();
2357   uint64_t StackSize;
2358   unsigned TlsReg, TlsOffset;
2359   DebugLoc DL;
2360 
2361   // To support shrink-wrapping we would need to insert the new blocks
2362   // at the right place and update the branches to PrologueMBB.
2363   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
2364 
2365   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2366   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2367          "Scratch register is live-in");
2368 
2369   if (MF.getFunction().isVarArg())
2370     report_fatal_error("Segmented stacks do not support vararg functions.");
2371   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
2372       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
2373       !STI.isTargetDragonFly())
2374     report_fatal_error("Segmented stacks not supported on this platform.");
2375 
2376   // Eventually StackSize will be calculated by a link-time pass; which will
2377   // also decide whether checking code needs to be injected into this particular
2378   // prologue.
2379   StackSize = MFI.getStackSize();
2380 
2381   // Do not generate a prologue for leaf functions with a stack of size zero.
2382   // For non-leaf functions we have to allow for the possibility that the
2383   // callis to a non-split function, as in PR37807. This function could also
2384   // take the address of a non-split function. When the linker tries to adjust
2385   // its non-existent prologue, it would fail with an error. Mark the object
2386   // file so that such failures are not errors. See this Go language bug-report
2387   // https://go-review.googlesource.com/c/go/+/148819/
2388   if (StackSize == 0 && !MFI.hasTailCall()) {
2389     MF.getMMI().setHasNosplitStack(true);
2390     return;
2391   }
2392 
2393   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
2394   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
2395   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2396   bool IsNested = false;
2397 
2398   // We need to know if the function has a nest argument only in 64 bit mode.
2399   if (Is64Bit)
2400     IsNested = HasNestArgument(&MF);
2401 
2402   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
2403   // allocMBB needs to be last (terminating) instruction.
2404 
2405   for (const auto &LI : PrologueMBB.liveins()) {
2406     allocMBB->addLiveIn(LI);
2407     checkMBB->addLiveIn(LI);
2408   }
2409 
2410   if (IsNested)
2411     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
2412 
2413   MF.push_front(allocMBB);
2414   MF.push_front(checkMBB);
2415 
2416   // When the frame size is less than 256 we just compare the stack
2417   // boundary directly to the value of the stack pointer, per gcc.
2418   bool CompareStackPointer = StackSize < kSplitStackAvailable;
2419 
2420   // Read the limit off the current stacklet off the stack_guard location.
2421   if (Is64Bit) {
2422     if (STI.isTargetLinux()) {
2423       TlsReg = X86::FS;
2424       TlsOffset = IsLP64 ? 0x70 : 0x40;
2425     } else if (STI.isTargetDarwin()) {
2426       TlsReg = X86::GS;
2427       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
2428     } else if (STI.isTargetWin64()) {
2429       TlsReg = X86::GS;
2430       TlsOffset = 0x28; // pvArbitrary, reserved for application use
2431     } else if (STI.isTargetFreeBSD()) {
2432       TlsReg = X86::FS;
2433       TlsOffset = 0x18;
2434     } else if (STI.isTargetDragonFly()) {
2435       TlsReg = X86::FS;
2436       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
2437     } else {
2438       report_fatal_error("Segmented stacks not supported on this platform.");
2439     }
2440 
2441     if (CompareStackPointer)
2442       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
2443     else
2444       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
2445         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2446 
2447     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
2448       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2449   } else {
2450     if (STI.isTargetLinux()) {
2451       TlsReg = X86::GS;
2452       TlsOffset = 0x30;
2453     } else if (STI.isTargetDarwin()) {
2454       TlsReg = X86::GS;
2455       TlsOffset = 0x48 + 90*4;
2456     } else if (STI.isTargetWin32()) {
2457       TlsReg = X86::FS;
2458       TlsOffset = 0x14; // pvArbitrary, reserved for application use
2459     } else if (STI.isTargetDragonFly()) {
2460       TlsReg = X86::FS;
2461       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
2462     } else if (STI.isTargetFreeBSD()) {
2463       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
2464     } else {
2465       report_fatal_error("Segmented stacks not supported on this platform.");
2466     }
2467 
2468     if (CompareStackPointer)
2469       ScratchReg = X86::ESP;
2470     else
2471       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
2472         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2473 
2474     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
2475         STI.isTargetDragonFly()) {
2476       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
2477         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2478     } else if (STI.isTargetDarwin()) {
2479 
2480       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
2481       unsigned ScratchReg2;
2482       bool SaveScratch2;
2483       if (CompareStackPointer) {
2484         // The primary scratch register is available for holding the TLS offset.
2485         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2486         SaveScratch2 = false;
2487       } else {
2488         // Need to use a second register to hold the TLS offset
2489         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
2490 
2491         // Unfortunately, with fastcc the second scratch register may hold an
2492         // argument.
2493         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
2494       }
2495 
2496       // If Scratch2 is live-in then it needs to be saved.
2497       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
2498              "Scratch register is live-in and not saved");
2499 
2500       if (SaveScratch2)
2501         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
2502           .addReg(ScratchReg2, RegState::Kill);
2503 
2504       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
2505         .addImm(TlsOffset);
2506       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
2507         .addReg(ScratchReg)
2508         .addReg(ScratchReg2).addImm(1).addReg(0)
2509         .addImm(0)
2510         .addReg(TlsReg);
2511 
2512       if (SaveScratch2)
2513         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
2514     }
2515   }
2516 
2517   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
2518   // It jumps to normal execution of the function body.
2519   BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A);
2520 
2521   // On 32 bit we first push the arguments size and then the frame size. On 64
2522   // bit, we pass the stack frame size in r10 and the argument size in r11.
2523   if (Is64Bit) {
2524     // Functions with nested arguments use R10, so it needs to be saved across
2525     // the call to _morestack
2526 
2527     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
2528     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
2529     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
2530     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
2531     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
2532 
2533     if (IsNested)
2534       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
2535 
2536     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
2537       .addImm(StackSize);
2538     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
2539       .addImm(X86FI->getArgumentStackSize());
2540   } else {
2541     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2542       .addImm(X86FI->getArgumentStackSize());
2543     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2544       .addImm(StackSize);
2545   }
2546 
2547   // __morestack is in libgcc
2548   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
2549     // Under the large code model, we cannot assume that __morestack lives
2550     // within 2^31 bytes of the call site, so we cannot use pc-relative
2551     // addressing. We cannot perform the call via a temporary register,
2552     // as the rax register may be used to store the static chain, and all
2553     // other suitable registers may be either callee-save or used for
2554     // parameter passing. We cannot use the stack at this point either
2555     // because __morestack manipulates the stack directly.
2556     //
2557     // To avoid these issues, perform an indirect call via a read-only memory
2558     // location containing the address.
2559     //
2560     // This solution is not perfect, as it assumes that the .rodata section
2561     // is laid out within 2^31 bytes of each function body, but this seems
2562     // to be sufficient for JIT.
2563     // FIXME: Add retpoline support and remove the error here..
2564     if (STI.useIndirectThunkCalls())
2565       report_fatal_error("Emitting morestack calls on 64-bit with the large "
2566                          "code model and thunks not yet implemented.");
2567     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
2568         .addReg(X86::RIP)
2569         .addImm(0)
2570         .addReg(0)
2571         .addExternalSymbol("__morestack_addr")
2572         .addReg(0);
2573     MF.getMMI().setUsesMorestackAddr(true);
2574   } else {
2575     if (Is64Bit)
2576       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
2577         .addExternalSymbol("__morestack");
2578     else
2579       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
2580         .addExternalSymbol("__morestack");
2581   }
2582 
2583   if (IsNested)
2584     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
2585   else
2586     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
2587 
2588   allocMBB->addSuccessor(&PrologueMBB);
2589 
2590   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
2591   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
2592 
2593 #ifdef EXPENSIVE_CHECKS
2594   MF.verify();
2595 #endif
2596 }
2597 
2598 /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
2599 /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
2600 /// to fields it needs, through a named metadata node "hipe.literals" containing
2601 /// name-value pairs.
2602 static unsigned getHiPELiteral(
2603     NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) {
2604   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
2605     MDNode *Node = HiPELiteralsMD->getOperand(i);
2606     if (Node->getNumOperands() != 2) continue;
2607     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
2608     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
2609     if (!NodeName || !NodeVal) continue;
2610     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
2611     if (ValConst && NodeName->getString() == LiteralName) {
2612       return ValConst->getZExtValue();
2613     }
2614   }
2615 
2616   report_fatal_error("HiPE literal " + LiteralName
2617                      + " required but not provided");
2618 }
2619 
2620 // Return true if there are no non-ehpad successors to MBB and there are no
2621 // non-meta instructions between MBBI and MBB.end().
2622 static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
2623                                   MachineBasicBlock::const_iterator MBBI) {
2624   return std::all_of(
2625              MBB.succ_begin(), MBB.succ_end(),
2626              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
2627          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
2628            return MI.isMetaInstruction();
2629          });
2630 }
2631 
2632 /// Erlang programs may need a special prologue to handle the stack size they
2633 /// might need at runtime. That is because Erlang/OTP does not implement a C
2634 /// stack but uses a custom implementation of hybrid stack/heap architecture.
2635 /// (for more information see Eric Stenman's Ph.D. thesis:
2636 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
2637 ///
2638 /// CheckStack:
2639 ///       temp0 = sp - MaxStack
2640 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2641 /// OldStart:
2642 ///       ...
2643 /// IncStack:
2644 ///       call inc_stack   # doubles the stack space
2645 ///       temp0 = sp - MaxStack
2646 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2647 void X86FrameLowering::adjustForHiPEPrologue(
2648     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2649   MachineFrameInfo &MFI = MF.getFrameInfo();
2650   DebugLoc DL;
2651 
2652   // To support shrink-wrapping we would need to insert the new blocks
2653   // at the right place and update the branches to PrologueMBB.
2654   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
2655 
2656   // HiPE-specific values
2657   NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule()
2658     ->getNamedMetadata("hipe.literals");
2659   if (!HiPELiteralsMD)
2660     report_fatal_error(
2661         "Can't generate HiPE prologue without runtime parameters");
2662   const unsigned HipeLeafWords
2663     = getHiPELiteral(HiPELiteralsMD,
2664                      Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
2665   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
2666   const unsigned Guaranteed = HipeLeafWords * SlotSize;
2667   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ?
2668                             MF.getFunction().arg_size() - CCRegisteredArgs : 0;
2669   unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize;
2670 
2671   assert(STI.isTargetLinux() &&
2672          "HiPE prologue is only supported on Linux operating systems.");
2673 
2674   // Compute the largest caller's frame that is needed to fit the callees'
2675   // frames. This 'MaxStack' is computed from:
2676   //
2677   // a) the fixed frame size, which is the space needed for all spilled temps,
2678   // b) outgoing on-stack parameter areas, and
2679   // c) the minimum stack space this function needs to make available for the
2680   //    functions it calls (a tunable ABI property).
2681   if (MFI.hasCalls()) {
2682     unsigned MoreStackForCalls = 0;
2683 
2684     for (auto &MBB : MF) {
2685       for (auto &MI : MBB) {
2686         if (!MI.isCall())
2687           continue;
2688 
2689         // Get callee operand.
2690         const MachineOperand &MO = MI.getOperand(0);
2691 
2692         // Only take account of global function calls (no closures etc.).
2693         if (!MO.isGlobal())
2694           continue;
2695 
2696         const Function *F = dyn_cast<Function>(MO.getGlobal());
2697         if (!F)
2698           continue;
2699 
2700         // Do not update 'MaxStack' for primitive and built-in functions
2701         // (encoded with names either starting with "erlang."/"bif_" or not
2702         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
2703         // "_", such as the BIF "suspend_0") as they are executed on another
2704         // stack.
2705         if (F->getName().find("erlang.") != StringRef::npos ||
2706             F->getName().find("bif_") != StringRef::npos ||
2707             F->getName().find_first_of("._") == StringRef::npos)
2708           continue;
2709 
2710         unsigned CalleeStkArity =
2711           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
2712         if (HipeLeafWords - 1 > CalleeStkArity)
2713           MoreStackForCalls = std::max(MoreStackForCalls,
2714                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
2715       }
2716     }
2717     MaxStack += MoreStackForCalls;
2718   }
2719 
2720   // If the stack frame needed is larger than the guaranteed then runtime checks
2721   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
2722   if (MaxStack > Guaranteed) {
2723     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
2724     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
2725 
2726     for (const auto &LI : PrologueMBB.liveins()) {
2727       stackCheckMBB->addLiveIn(LI);
2728       incStackMBB->addLiveIn(LI);
2729     }
2730 
2731     MF.push_front(incStackMBB);
2732     MF.push_front(stackCheckMBB);
2733 
2734     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
2735     unsigned LEAop, CMPop, CALLop;
2736     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
2737     if (Is64Bit) {
2738       SPReg = X86::RSP;
2739       PReg  = X86::RBP;
2740       LEAop = X86::LEA64r;
2741       CMPop = X86::CMP64rm;
2742       CALLop = X86::CALL64pcrel32;
2743     } else {
2744       SPReg = X86::ESP;
2745       PReg  = X86::EBP;
2746       LEAop = X86::LEA32r;
2747       CMPop = X86::CMP32rm;
2748       CALLop = X86::CALLpcrel32;
2749     }
2750 
2751     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2752     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2753            "HiPE prologue scratch register is live-in");
2754 
2755     // Create new MBB for StackCheck:
2756     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
2757                  SPReg, false, -MaxStack);
2758     // SPLimitOffset is in a fixed heap location (pointed by BP).
2759     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
2760                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
2761     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE);
2762 
2763     // Create new MBB for IncStack:
2764     BuildMI(incStackMBB, DL, TII.get(CALLop)).
2765       addExternalSymbol("inc_stack_0");
2766     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
2767                  SPReg, false, -MaxStack);
2768     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
2769                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
2770     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE);
2771 
2772     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
2773     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
2774     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
2775     incStackMBB->addSuccessor(incStackMBB, {1, 100});
2776   }
2777 #ifdef EXPENSIVE_CHECKS
2778   MF.verify();
2779 #endif
2780 }
2781 
2782 bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
2783                                            MachineBasicBlock::iterator MBBI,
2784                                            const DebugLoc &DL,
2785                                            int Offset) const {
2786 
2787   if (Offset <= 0)
2788     return false;
2789 
2790   if (Offset % SlotSize)
2791     return false;
2792 
2793   int NumPops = Offset / SlotSize;
2794   // This is only worth it if we have at most 2 pops.
2795   if (NumPops != 1 && NumPops != 2)
2796     return false;
2797 
2798   // Handle only the trivial case where the adjustment directly follows
2799   // a call. This is the most common one, anyway.
2800   if (MBBI == MBB.begin())
2801     return false;
2802   MachineBasicBlock::iterator Prev = std::prev(MBBI);
2803   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
2804     return false;
2805 
2806   unsigned Regs[2];
2807   unsigned FoundRegs = 0;
2808 
2809   auto &MRI = MBB.getParent()->getRegInfo();
2810   auto RegMask = Prev->getOperand(1);
2811 
2812   auto &RegClass =
2813       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
2814   // Try to find up to NumPops free registers.
2815   for (auto Candidate : RegClass) {
2816 
2817     // Poor man's liveness:
2818     // Since we're immediately after a call, any register that is clobbered
2819     // by the call and not defined by it can be considered dead.
2820     if (!RegMask.clobbersPhysReg(Candidate))
2821       continue;
2822 
2823     // Don't clobber reserved registers
2824     if (MRI.isReserved(Candidate))
2825       continue;
2826 
2827     bool IsDef = false;
2828     for (const MachineOperand &MO : Prev->implicit_operands()) {
2829       if (MO.isReg() && MO.isDef() &&
2830           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
2831         IsDef = true;
2832         break;
2833       }
2834     }
2835 
2836     if (IsDef)
2837       continue;
2838 
2839     Regs[FoundRegs++] = Candidate;
2840     if (FoundRegs == (unsigned)NumPops)
2841       break;
2842   }
2843 
2844   if (FoundRegs == 0)
2845     return false;
2846 
2847   // If we found only one free register, but need two, reuse the same one twice.
2848   while (FoundRegs < (unsigned)NumPops)
2849     Regs[FoundRegs++] = Regs[0];
2850 
2851   for (int i = 0; i < NumPops; ++i)
2852     BuildMI(MBB, MBBI, DL,
2853             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
2854 
2855   return true;
2856 }
2857 
2858 MachineBasicBlock::iterator X86FrameLowering::
2859 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
2860                               MachineBasicBlock::iterator I) const {
2861   bool reserveCallFrame = hasReservedCallFrame(MF);
2862   unsigned Opcode = I->getOpcode();
2863   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
2864   DebugLoc DL = I->getDebugLoc();
2865   uint64_t Amount = TII.getFrameSize(*I);
2866   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
2867   I = MBB.erase(I);
2868   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
2869 
2870   if (!reserveCallFrame) {
2871     // If the stack pointer can be changed after prologue, turn the
2872     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
2873     // adjcallstackdown instruction into 'add ESP, <amt>'
2874 
2875     // We need to keep the stack aligned properly.  To do this, we round the
2876     // amount of space needed for the outgoing arguments up to the next
2877     // alignment boundary.
2878     unsigned StackAlign = getStackAlignment();
2879     Amount = alignTo(Amount, StackAlign);
2880 
2881     const Function &F = MF.getFunction();
2882     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
2883     bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
2884 
2885     // If we have any exception handlers in this function, and we adjust
2886     // the SP before calls, we may need to indicate this to the unwinder
2887     // using GNU_ARGS_SIZE. Note that this may be necessary even when
2888     // Amount == 0, because the preceding function may have set a non-0
2889     // GNU_ARGS_SIZE.
2890     // TODO: We don't need to reset this between subsequent functions,
2891     // if it didn't change.
2892     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
2893 
2894     if (HasDwarfEHHandlers && !isDestroy &&
2895         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
2896       BuildCFI(MBB, InsertPos, DL,
2897                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
2898 
2899     if (Amount == 0)
2900       return I;
2901 
2902     // Factor out the amount that gets handled inside the sequence
2903     // (Pushes of argument for frame setup, callee pops for frame destroy)
2904     Amount -= InternalAmt;
2905 
2906     // TODO: This is needed only if we require precise CFA.
2907     // If this is a callee-pop calling convention, emit a CFA adjust for
2908     // the amount the callee popped.
2909     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
2910       BuildCFI(MBB, InsertPos, DL,
2911                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
2912 
2913     // Add Amount to SP to destroy a frame, or subtract to setup.
2914     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
2915 
2916     if (StackAdjustment) {
2917       // Merge with any previous or following adjustment instruction. Note: the
2918       // instructions merged with here do not have CFI, so their stack
2919       // adjustments do not feed into CfaAdjustment.
2920       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
2921       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
2922 
2923       if (StackAdjustment) {
2924         if (!(F.hasMinSize() &&
2925               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
2926           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
2927                                /*InEpilogue=*/false);
2928       }
2929     }
2930 
2931     if (DwarfCFI && !hasFP(MF)) {
2932       // If we don't have FP, but need to generate unwind information,
2933       // we need to set the correct CFA offset after the stack adjustment.
2934       // How much we adjust the CFA offset depends on whether we're emitting
2935       // CFI only for EH purposes or for debugging. EH only requires the CFA
2936       // offset to be correct at each call site, while for debugging we want
2937       // it to be more precise.
2938 
2939       int64_t CfaAdjustment = -StackAdjustment;
2940       // TODO: When not using precise CFA, we also need to adjust for the
2941       // InternalAmt here.
2942       if (CfaAdjustment) {
2943         BuildCFI(MBB, InsertPos, DL,
2944                  MCCFIInstruction::createAdjustCfaOffset(nullptr,
2945                                                          CfaAdjustment));
2946       }
2947     }
2948 
2949     return I;
2950   }
2951 
2952   if (isDestroy && InternalAmt && !blockEndIsUnreachable(MBB, I)) {
2953     // If we are performing frame pointer elimination and if the callee pops
2954     // something off the stack pointer, add it back.  We do this until we have
2955     // more advanced stack pointer tracking ability.
2956     // We are not tracking the stack pointer adjustment by the callee, so make
2957     // sure we restore the stack pointer immediately after the call, there may
2958     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2959     MachineBasicBlock::iterator CI = I;
2960     MachineBasicBlock::iterator B = MBB.begin();
2961     while (CI != B && !std::prev(CI)->isCall())
2962       --CI;
2963     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
2964   }
2965 
2966   return I;
2967 }
2968 
2969 bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
2970   assert(MBB.getParent() && "Block is not attached to a function!");
2971   const MachineFunction &MF = *MBB.getParent();
2972   return !TRI->needsStackRealignment(MF) || !MBB.isLiveIn(X86::EFLAGS);
2973 }
2974 
2975 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
2976   assert(MBB.getParent() && "Block is not attached to a function!");
2977 
2978   // Win64 has strict requirements in terms of epilogue and we are
2979   // not taking a chance at messing with them.
2980   // I.e., unless this block is already an exit block, we can't use
2981   // it as an epilogue.
2982   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
2983     return false;
2984 
2985   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
2986     return true;
2987 
2988   // If we cannot use LEA to adjust SP, we may need to use ADD, which
2989   // clobbers the EFLAGS. Check that we do not need to preserve it,
2990   // otherwise, conservatively assume this is not
2991   // safe to insert the epilogue here.
2992   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
2993 }
2994 
2995 bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
2996   // If we may need to emit frameless compact unwind information, give
2997   // up as this is currently broken: PR25614.
2998   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF)) &&
2999          // The lowering of segmented stack and HiPE only support entry blocks
3000          // as prologue blocks: PR26107.
3001          // This limitation may be lifted if we fix:
3002          // - adjustForSegmentedStacks
3003          // - adjustForHiPEPrologue
3004          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
3005          !MF.shouldSplitStack();
3006 }
3007 
3008 MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
3009     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3010     const DebugLoc &DL, bool RestoreSP) const {
3011   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
3012   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
3013   assert(STI.is32Bit() && !Uses64BitFramePtr &&
3014          "restoring EBP/ESI on non-32-bit target");
3015 
3016   MachineFunction &MF = *MBB.getParent();
3017   Register FramePtr = TRI->getFrameRegister(MF);
3018   Register BasePtr = TRI->getBaseRegister();
3019   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
3020   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3021   MachineFrameInfo &MFI = MF.getFrameInfo();
3022 
3023   // FIXME: Don't set FrameSetup flag in catchret case.
3024 
3025   int FI = FuncInfo.EHRegNodeFrameIndex;
3026   int EHRegSize = MFI.getObjectSize(FI);
3027 
3028   if (RestoreSP) {
3029     // MOV32rm -EHRegSize(%ebp), %esp
3030     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
3031                  X86::EBP, true, -EHRegSize)
3032         .setMIFlag(MachineInstr::FrameSetup);
3033   }
3034 
3035   unsigned UsedReg;
3036   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg);
3037   int EndOffset = -EHRegOffset - EHRegSize;
3038   FuncInfo.EHRegNodeEndOffset = EndOffset;
3039 
3040   if (UsedReg == FramePtr) {
3041     // ADD $offset, %ebp
3042     unsigned ADDri = getADDriOpcode(false, EndOffset);
3043     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
3044         .addReg(FramePtr)
3045         .addImm(EndOffset)
3046         .setMIFlag(MachineInstr::FrameSetup)
3047         ->getOperand(3)
3048         .setIsDead();
3049     assert(EndOffset >= 0 &&
3050            "end of registration object above normal EBP position!");
3051   } else if (UsedReg == BasePtr) {
3052     // LEA offset(%ebp), %esi
3053     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
3054                  FramePtr, false, EndOffset)
3055         .setMIFlag(MachineInstr::FrameSetup);
3056     // MOV32rm SavedEBPOffset(%esi), %ebp
3057     assert(X86FI->getHasSEHFramePtrSave());
3058     int Offset =
3059         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
3060     assert(UsedReg == BasePtr);
3061     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
3062                  UsedReg, true, Offset)
3063         .setMIFlag(MachineInstr::FrameSetup);
3064   } else {
3065     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
3066   }
3067   return MBBI;
3068 }
3069 
3070 int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
3071   return TRI->getSlotSize();
3072 }
3073 
3074 unsigned X86FrameLowering::getInitialCFARegister(const MachineFunction &MF)
3075     const {
3076   return TRI->getDwarfRegNum(StackPtr, true);
3077 }
3078 
3079 namespace {
3080 // Struct used by orderFrameObjects to help sort the stack objects.
3081 struct X86FrameSortingObject {
3082   bool IsValid = false;         // true if we care about this Object.
3083   unsigned ObjectIndex = 0;     // Index of Object into MFI list.
3084   unsigned ObjectSize = 0;      // Size of Object in bytes.
3085   unsigned ObjectAlignment = 1; // Alignment of Object in bytes.
3086   unsigned ObjectNumUses = 0;   // Object static number of uses.
3087 };
3088 
3089 // The comparison function we use for std::sort to order our local
3090 // stack symbols. The current algorithm is to use an estimated
3091 // "density". This takes into consideration the size and number of
3092 // uses each object has in order to roughly minimize code size.
3093 // So, for example, an object of size 16B that is referenced 5 times
3094 // will get higher priority than 4 4B objects referenced 1 time each.
3095 // It's not perfect and we may be able to squeeze a few more bytes out of
3096 // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
3097 // fringe end can have special consideration, given their size is less
3098 // important, etc.), but the algorithmic complexity grows too much to be
3099 // worth the extra gains we get. This gets us pretty close.
3100 // The final order leaves us with objects with highest priority going
3101 // at the end of our list.
3102 struct X86FrameSortingComparator {
3103   inline bool operator()(const X86FrameSortingObject &A,
3104                          const X86FrameSortingObject &B) {
3105     uint64_t DensityAScaled, DensityBScaled;
3106 
3107     // For consistency in our comparison, all invalid objects are placed
3108     // at the end. This also allows us to stop walking when we hit the
3109     // first invalid item after it's all sorted.
3110     if (!A.IsValid)
3111       return false;
3112     if (!B.IsValid)
3113       return true;
3114 
3115     // The density is calculated by doing :
3116     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
3117     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
3118     // Since this approach may cause inconsistencies in
3119     // the floating point <, >, == comparisons, depending on the floating
3120     // point model with which the compiler was built, we're going
3121     // to scale both sides by multiplying with
3122     // A.ObjectSize * B.ObjectSize. This ends up factoring away
3123     // the division and, with it, the need for any floating point
3124     // arithmetic.
3125     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
3126       static_cast<uint64_t>(B.ObjectSize);
3127     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
3128       static_cast<uint64_t>(A.ObjectSize);
3129 
3130     // If the two densities are equal, prioritize highest alignment
3131     // objects. This allows for similar alignment objects
3132     // to be packed together (given the same density).
3133     // There's room for improvement here, also, since we can pack
3134     // similar alignment (different density) objects next to each
3135     // other to save padding. This will also require further
3136     // complexity/iterations, and the overall gain isn't worth it,
3137     // in general. Something to keep in mind, though.
3138     if (DensityAScaled == DensityBScaled)
3139       return A.ObjectAlignment < B.ObjectAlignment;
3140 
3141     return DensityAScaled < DensityBScaled;
3142   }
3143 };
3144 } // namespace
3145 
3146 // Order the symbols in the local stack.
3147 // We want to place the local stack objects in some sort of sensible order.
3148 // The heuristic we use is to try and pack them according to static number
3149 // of uses and size of object in order to minimize code size.
3150 void X86FrameLowering::orderFrameObjects(
3151     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3152   const MachineFrameInfo &MFI = MF.getFrameInfo();
3153 
3154   // Don't waste time if there's nothing to do.
3155   if (ObjectsToAllocate.empty())
3156     return;
3157 
3158   // Create an array of all MFI objects. We won't need all of these
3159   // objects, but we're going to create a full array of them to make
3160   // it easier to index into when we're counting "uses" down below.
3161   // We want to be able to easily/cheaply access an object by simply
3162   // indexing into it, instead of having to search for it every time.
3163   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
3164 
3165   // Walk the objects we care about and mark them as such in our working
3166   // struct.
3167   for (auto &Obj : ObjectsToAllocate) {
3168     SortingObjects[Obj].IsValid = true;
3169     SortingObjects[Obj].ObjectIndex = Obj;
3170     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlignment(Obj);
3171     // Set the size.
3172     int ObjectSize = MFI.getObjectSize(Obj);
3173     if (ObjectSize == 0)
3174       // Variable size. Just use 4.
3175       SortingObjects[Obj].ObjectSize = 4;
3176     else
3177       SortingObjects[Obj].ObjectSize = ObjectSize;
3178   }
3179 
3180   // Count the number of uses for each object.
3181   for (auto &MBB : MF) {
3182     for (auto &MI : MBB) {
3183       if (MI.isDebugInstr())
3184         continue;
3185       for (const MachineOperand &MO : MI.operands()) {
3186         // Check to see if it's a local stack symbol.
3187         if (!MO.isFI())
3188           continue;
3189         int Index = MO.getIndex();
3190         // Check to see if it falls within our range, and is tagged
3191         // to require ordering.
3192         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
3193             SortingObjects[Index].IsValid)
3194           SortingObjects[Index].ObjectNumUses++;
3195       }
3196     }
3197   }
3198 
3199   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
3200   // info).
3201   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
3202 
3203   // Now modify the original list to represent the final order that
3204   // we want. The order will depend on whether we're going to access them
3205   // from the stack pointer or the frame pointer. For SP, the list should
3206   // end up with the END containing objects that we want with smaller offsets.
3207   // For FP, it should be flipped.
3208   int i = 0;
3209   for (auto &Obj : SortingObjects) {
3210     // All invalid items are sorted at the end, so it's safe to stop.
3211     if (!Obj.IsValid)
3212       break;
3213     ObjectsToAllocate[i++] = Obj.ObjectIndex;
3214   }
3215 
3216   // Flip it if we're accessing off of the FP.
3217   if (!TRI->needsStackRealignment(MF) && hasFP(MF))
3218     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
3219 }
3220 
3221 
3222 unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
3223   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
3224   unsigned Offset = 16;
3225   // RBP is immediately pushed.
3226   Offset += SlotSize;
3227   // All callee-saved registers are then pushed.
3228   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
3229   // Every funclet allocates enough stack space for the largest outgoing call.
3230   Offset += getWinEHFuncletFrameSize(MF);
3231   return Offset;
3232 }
3233 
3234 void X86FrameLowering::processFunctionBeforeFrameFinalized(
3235     MachineFunction &MF, RegScavenger *RS) const {
3236   // Mark the function as not having WinCFI. We will set it back to true in
3237   // emitPrologue if it gets called and emits CFI.
3238   MF.setHasWinCFI(false);
3239 
3240   // If this function isn't doing Win64-style C++ EH, we don't need to do
3241   // anything.
3242   const Function &F = MF.getFunction();
3243   if (!STI.is64Bit() || !MF.hasEHFunclets() ||
3244       classifyEHPersonality(F.getPersonalityFn()) != EHPersonality::MSVC_CXX)
3245     return;
3246 
3247   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
3248   // relative to RSP after the prologue.  Find the offset of the last fixed
3249   // object, so that we can allocate a slot immediately following it. If there
3250   // were no fixed objects, use offset -SlotSize, which is immediately after the
3251   // return address. Fixed objects have negative frame indices.
3252   MachineFrameInfo &MFI = MF.getFrameInfo();
3253   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
3254   int64_t MinFixedObjOffset = -SlotSize;
3255   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
3256     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
3257 
3258   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
3259     for (WinEHHandlerType &H : TBME.HandlerArray) {
3260       int FrameIndex = H.CatchObj.FrameIndex;
3261       if (FrameIndex != INT_MAX) {
3262         // Ensure alignment.
3263         unsigned Align = MFI.getObjectAlignment(FrameIndex);
3264         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
3265         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
3266         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
3267       }
3268     }
3269   }
3270 
3271   // Ensure alignment.
3272   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
3273   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
3274   int UnwindHelpFI =
3275       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
3276   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
3277 
3278   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
3279   // other frame setup instructions.
3280   MachineBasicBlock &MBB = MF.front();
3281   auto MBBI = MBB.begin();
3282   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
3283     ++MBBI;
3284 
3285   DebugLoc DL = MBB.findDebugLoc(MBBI);
3286   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
3287                     UnwindHelpFI)
3288       .addImm(-2);
3289 }
3290 
3291 const ReturnProtectorLowering *X86FrameLowering::getReturnProtector() const {
3292   return &RPL;
3293 }
3294