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