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