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