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