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