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