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