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