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