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