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