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