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