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