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