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