Use pushq / popq instead of subq $8, %rsp / addq $8, %rsp to adjust stack in
[oota-llvm.git] / lib / Target / X86 / X86FrameInfo.cpp
1 //=======- X86FrameInfo.cpp - X86 Frame Information ------------*- C++ -*-====//
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 TargetFrameInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86FrameInfo.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/ADT/SmallSet.h"
29
30 using namespace llvm;
31
32 // FIXME: completely move here.
33 extern cl::opt<bool> ForceStackAlign;
34
35 bool X86FrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
36   return !MF.getFrameInfo()->hasVarSizedObjects();
37 }
38
39 /// hasFP - Return true if the specified function should have a dedicated frame
40 /// pointer register.  This is true if the function has variable sized allocas
41 /// or if frame pointer elimination is disabled.
42 bool X86FrameInfo::hasFP(const MachineFunction &MF) const {
43   const MachineFrameInfo *MFI = MF.getFrameInfo();
44   const MachineModuleInfo &MMI = MF.getMMI();
45   const TargetRegisterInfo *RI = TM.getRegisterInfo();
46
47   return (DisableFramePointerElim(MF) ||
48           RI->needsStackRealignment(MF) ||
49           MFI->hasVarSizedObjects() ||
50           MFI->isFrameAddressTaken() ||
51           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
52           MMI.callsUnwindInit());
53 }
54
55 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
56   if (is64Bit) {
57     if (isInt<8>(Imm))
58       return X86::SUB64ri8;
59     return X86::SUB64ri32;
60   } else {
61     if (isInt<8>(Imm))
62       return X86::SUB32ri8;
63     return X86::SUB32ri;
64   }
65 }
66
67 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
68   if (is64Bit) {
69     if (isInt<8>(Imm))
70       return X86::ADD64ri8;
71     return X86::ADD64ri32;
72   } else {
73     if (isInt<8>(Imm))
74       return X86::ADD32ri8;
75     return X86::ADD32ri;
76   }
77 }
78
79 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
80 /// when it reaches the "return" instruction. We can then pop a stack object
81 /// to this register without worry about clobbering it.
82 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
83                                        MachineBasicBlock::iterator &MBBI,
84                                        const TargetRegisterInfo &TRI,
85                                        bool Is64Bit) {
86   const MachineFunction *MF = MBB.getParent();
87   const Function *F = MF->getFunction();
88   if (!F || MF->getMMI().callsEHReturn())
89     return 0;
90
91   static const unsigned CallerSavedRegs32Bit[] = {
92     X86::EAX, X86::EDX, X86::ECX
93   };
94
95   static const unsigned CallerSavedRegs64Bit[] = {
96     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
97     X86::R8,  X86::R9,  X86::R10, X86::R11
98   };
99
100   unsigned Opc = MBBI->getOpcode();
101   switch (Opc) {
102   default: return 0;
103   case X86::RET:
104   case X86::RETI:
105   case X86::TCRETURNdi:
106   case X86::TCRETURNri:
107   case X86::TCRETURNmi:
108   case X86::TCRETURNdi64:
109   case X86::TCRETURNri64:
110   case X86::TCRETURNmi64:
111   case X86::EH_RETURN:
112   case X86::EH_RETURN64: {
113     SmallSet<unsigned, 8> Uses;
114     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
115       MachineOperand &MO = MBBI->getOperand(i);
116       if (!MO.isReg() || MO.isDef())
117         continue;
118       unsigned Reg = MO.getReg();
119       if (!Reg)
120         continue;
121       for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
122         Uses.insert(*AsI);
123     }
124
125     const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
126     for (; *CS; ++CS)
127       if (!Uses.count(*CS))
128         return *CS;
129   }
130   }
131
132   return 0;
133 }
134
135
136 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
137 /// stack pointer by a constant value.
138 static
139 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
140                   unsigned StackPtr, int64_t NumBytes,
141                   bool Is64Bit, const TargetInstrInfo &TII,
142                   const TargetRegisterInfo &TRI) {
143   bool isSub = NumBytes < 0;
144   uint64_t Offset = isSub ? -NumBytes : NumBytes;
145   unsigned Opc = isSub ?
146     getSUBriOpcode(Is64Bit, Offset) :
147     getADDriOpcode(Is64Bit, Offset);
148   uint64_t Chunk = (1LL << 31) - 1;
149   DebugLoc DL = MBB.findDebugLoc(MBBI);
150
151   while (Offset) {
152     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
153     if (ThisVal == (Is64Bit ? 8 : 4)) {
154       // Use push / pop instead.
155       unsigned Reg = isSub
156         ? (Is64Bit ? X86::RAX : X86::EAX)
157         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
158       if (Reg) {
159         Opc = isSub
160           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
161           : (Is64Bit ? X86::POP64r  : X86::POP32r);
162         BuildMI(MBB, MBBI, DL, TII.get(Opc))
163           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
164         Offset -= ThisVal;
165         continue;
166       }
167     }
168
169     MachineInstr *MI =
170       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
171       .addReg(StackPtr)
172       .addImm(ThisVal);
173     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
174     Offset -= ThisVal;
175   }
176 }
177
178 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
179 static
180 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
181                       unsigned StackPtr, uint64_t *NumBytes = NULL) {
182   if (MBBI == MBB.begin()) return;
183
184   MachineBasicBlock::iterator PI = prior(MBBI);
185   unsigned Opc = PI->getOpcode();
186   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
187        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
188       PI->getOperand(0).getReg() == StackPtr) {
189     if (NumBytes)
190       *NumBytes += PI->getOperand(2).getImm();
191     MBB.erase(PI);
192   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
193               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
194              PI->getOperand(0).getReg() == StackPtr) {
195     if (NumBytes)
196       *NumBytes -= PI->getOperand(2).getImm();
197     MBB.erase(PI);
198   }
199 }
200
201 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
202 static
203 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
204                         MachineBasicBlock::iterator &MBBI,
205                         unsigned StackPtr, uint64_t *NumBytes = NULL) {
206   // FIXME: THIS ISN'T RUN!!!
207   return;
208
209   if (MBBI == MBB.end()) return;
210
211   MachineBasicBlock::iterator NI = llvm::next(MBBI);
212   if (NI == MBB.end()) return;
213
214   unsigned Opc = NI->getOpcode();
215   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
216        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
217       NI->getOperand(0).getReg() == StackPtr) {
218     if (NumBytes)
219       *NumBytes -= NI->getOperand(2).getImm();
220     MBB.erase(NI);
221     MBBI = NI;
222   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
223               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
224              NI->getOperand(0).getReg() == StackPtr) {
225     if (NumBytes)
226       *NumBytes += NI->getOperand(2).getImm();
227     MBB.erase(NI);
228     MBBI = NI;
229   }
230 }
231
232 /// mergeSPUpdates - Checks the instruction before/after the passed
233 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
234 /// stack adjustment is returned as a positive value for ADD and a negative for
235 /// SUB.
236 static int mergeSPUpdates(MachineBasicBlock &MBB,
237                            MachineBasicBlock::iterator &MBBI,
238                            unsigned StackPtr,
239                            bool doMergeWithPrevious) {
240   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
241       (!doMergeWithPrevious && MBBI == MBB.end()))
242     return 0;
243
244   MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
245   MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
246   unsigned Opc = PI->getOpcode();
247   int Offset = 0;
248
249   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
250        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
251       PI->getOperand(0).getReg() == StackPtr){
252     Offset += PI->getOperand(2).getImm();
253     MBB.erase(PI);
254     if (!doMergeWithPrevious) MBBI = NI;
255   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
256               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
257              PI->getOperand(0).getReg() == StackPtr) {
258     Offset -= PI->getOperand(2).getImm();
259     MBB.erase(PI);
260     if (!doMergeWithPrevious) MBBI = NI;
261   }
262
263   return Offset;
264 }
265
266 static bool isEAXLiveIn(MachineFunction &MF) {
267   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
268        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
269     unsigned Reg = II->first;
270
271     if (Reg == X86::EAX || Reg == X86::AX ||
272         Reg == X86::AH || Reg == X86::AL)
273       return true;
274   }
275
276   return false;
277 }
278
279 void X86FrameInfo::emitCalleeSavedFrameMoves(MachineFunction &MF,
280                                              MCSymbol *Label,
281                                              unsigned FramePtr) const {
282   MachineFrameInfo *MFI = MF.getFrameInfo();
283   MachineModuleInfo &MMI = MF.getMMI();
284
285   // Add callee saved registers to move list.
286   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
287   if (CSI.empty()) return;
288
289   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
290   const TargetData *TD = TM.getTargetData();
291   bool HasFP = hasFP(MF);
292
293   // Calculate amount of bytes used for return address storing.
294   int stackGrowth =
295     (TM.getFrameInfo()->getStackGrowthDirection() ==
296      TargetFrameInfo::StackGrowsUp ?
297      TD->getPointerSize() : -TD->getPointerSize());
298
299   // FIXME: This is dirty hack. The code itself is pretty mess right now.
300   // It should be rewritten from scratch and generalized sometimes.
301
302   // Determine maximum offset (minumum due to stack growth).
303   int64_t MaxOffset = 0;
304   for (std::vector<CalleeSavedInfo>::const_iterator
305          I = CSI.begin(), E = CSI.end(); I != E; ++I)
306     MaxOffset = std::min(MaxOffset,
307                          MFI->getObjectOffset(I->getFrameIdx()));
308
309   // Calculate offsets.
310   int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
311   for (std::vector<CalleeSavedInfo>::const_iterator
312          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
313     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
314     unsigned Reg = I->getReg();
315     Offset = MaxOffset - Offset + saveAreaOffset;
316
317     // Don't output a new machine move if we're re-saving the frame
318     // pointer. This happens when the PrologEpilogInserter has inserted an extra
319     // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
320     // generates one when frame pointers are used. If we generate a "machine
321     // move" for this extra "PUSH", the linker will lose track of the fact that
322     // the frame pointer should have the value of the first "PUSH" when it's
323     // trying to unwind.
324     // 
325     // FIXME: This looks inelegant. It's possibly correct, but it's covering up
326     //        another bug. I.e., one where we generate a prolog like this:
327     //
328     //          pushl  %ebp
329     //          movl   %esp, %ebp
330     //          pushl  %ebp
331     //          pushl  %esi
332     //           ...
333     //
334     //        The immediate re-push of EBP is unnecessary. At the least, it's an
335     //        optimization bug. EBP can be used as a scratch register in certain
336     //        cases, but probably not when we have a frame pointer.
337     if (HasFP && FramePtr == Reg)
338       continue;
339
340     MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
341     MachineLocation CSSrc(Reg);
342     Moves.push_back(MachineMove(Label, CSDst, CSSrc));
343   }
344 }
345
346 /// emitPrologue - Push callee-saved registers onto the stack, which
347 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
348 /// space for local variables. Also emit labels used by the exception handler to
349 /// generate the exception handling frames.
350 void X86FrameInfo::emitPrologue(MachineFunction &MF) const {
351   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
352   MachineBasicBlock::iterator MBBI = MBB.begin();
353   MachineFrameInfo *MFI = MF.getFrameInfo();
354   const Function *Fn = MF.getFunction();
355   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
356   const X86InstrInfo &TII = *TM.getInstrInfo();
357   MachineModuleInfo &MMI = MF.getMMI();
358   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
359   bool needsFrameMoves = MMI.hasDebugInfo() ||
360                           !Fn->doesNotThrow() || UnwindTablesMandatory;
361   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
362   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
363   bool HasFP = hasFP(MF);
364   bool Is64Bit = STI.is64Bit();
365   bool IsWin64 = STI.isTargetWin64();
366   unsigned StackAlign = getStackAlignment();
367   unsigned SlotSize = RegInfo->getSlotSize();
368   unsigned FramePtr = RegInfo->getFrameRegister(MF);
369   unsigned StackPtr = RegInfo->getStackRegister();
370
371   DebugLoc DL;
372
373   // If we're forcing a stack realignment we can't rely on just the frame
374   // info, we need to know the ABI stack alignment as well in case we
375   // have a call out.  Otherwise just make sure we have some alignment - we'll
376   // go with the minimum SlotSize.
377   if (ForceStackAlign) {
378     if (MFI->hasCalls())
379       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
380     else if (MaxAlign < SlotSize)
381       MaxAlign = SlotSize;
382   }
383
384   // Add RETADDR move area to callee saved frame size.
385   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
386   if (TailCallReturnAddrDelta < 0)
387     X86FI->setCalleeSavedFrameSize(
388       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
389
390   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
391   // function, and use up to 128 bytes of stack space, don't have a frame
392   // pointer, calls, or dynamic alloca then we do not need to adjust the
393   // stack pointer (we fit in the Red Zone).
394   if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
395       !RegInfo->needsStackRealignment(MF) &&
396       !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
397       !MFI->adjustsStack() &&                      // No calls.
398       !IsWin64) {                                  // Win64 has no Red Zone
399     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
400     if (HasFP) MinSize += SlotSize;
401     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
402     MFI->setStackSize(StackSize);
403   } else if (IsWin64) {
404     // We need to always allocate 32 bytes as register spill area.
405     // FIXME: We might reuse these 32 bytes for leaf functions.
406     StackSize += 32;
407     MFI->setStackSize(StackSize);
408   }
409
410   // Insert stack pointer adjustment for later moving of return addr.  Only
411   // applies to tail call optimized functions where the callee argument stack
412   // size is bigger than the callers.
413   if (TailCallReturnAddrDelta < 0) {
414     MachineInstr *MI =
415       BuildMI(MBB, MBBI, DL,
416               TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
417               StackPtr)
418         .addReg(StackPtr)
419         .addImm(-TailCallReturnAddrDelta);
420     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
421   }
422
423   // Mapping for machine moves:
424   //
425   //   DST: VirtualFP AND
426   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
427   //        ELSE                        => DW_CFA_def_cfa
428   //
429   //   SRC: VirtualFP AND
430   //        DST: Register               => DW_CFA_def_cfa_register
431   //
432   //   ELSE
433   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
434   //        REG < 64                    => DW_CFA_offset + Reg
435   //        ELSE                        => DW_CFA_offset_extended
436
437   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
438   const TargetData *TD = MF.getTarget().getTargetData();
439   uint64_t NumBytes = 0;
440   int stackGrowth = -TD->getPointerSize();
441
442   if (HasFP) {
443     // Calculate required stack adjustment.
444     uint64_t FrameSize = StackSize - SlotSize;
445     if (RegInfo->needsStackRealignment(MF))
446       FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
447
448     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
449
450     // Get the offset of the stack slot for the EBP register, which is
451     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
452     // Update the frame offset adjustment.
453     MFI->setOffsetAdjustment(-NumBytes);
454
455     // Save EBP/RBP into the appropriate stack slot.
456     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
457       .addReg(FramePtr, RegState::Kill);
458
459     if (needsFrameMoves) {
460       // Mark the place where EBP/RBP was saved.
461       MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
462       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
463
464       // Define the current CFA rule to use the provided offset.
465       if (StackSize) {
466         MachineLocation SPDst(MachineLocation::VirtualFP);
467         MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
468         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
469       } else {
470         // FIXME: Verify & implement for FP
471         MachineLocation SPDst(StackPtr);
472         MachineLocation SPSrc(StackPtr, stackGrowth);
473         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
474       }
475
476       // Change the rule for the FramePtr to be an "offset" rule.
477       MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
478       MachineLocation FPSrc(FramePtr);
479       Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
480     }
481
482     // Update EBP with the new base value...
483     BuildMI(MBB, MBBI, DL,
484             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
485         .addReg(StackPtr);
486
487     if (needsFrameMoves) {
488       // Mark effective beginning of when frame pointer becomes valid.
489       MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
490       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
491
492       // Define the current CFA to use the EBP/RBP register.
493       MachineLocation FPDst(FramePtr);
494       MachineLocation FPSrc(MachineLocation::VirtualFP);
495       Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
496     }
497
498     // Mark the FramePtr as live-in in every block except the entry.
499     for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
500          I != E; ++I)
501       I->addLiveIn(FramePtr);
502
503     // Realign stack
504     if (RegInfo->needsStackRealignment(MF)) {
505       MachineInstr *MI =
506         BuildMI(MBB, MBBI, DL,
507                 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
508                 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
509
510       // The EFLAGS implicit def is dead.
511       MI->getOperand(3).setIsDead();
512     }
513   } else {
514     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
515   }
516
517   // Skip the callee-saved push instructions.
518   bool PushedRegs = false;
519   int StackOffset = 2 * stackGrowth;
520
521   while (MBBI != MBB.end() &&
522          (MBBI->getOpcode() == X86::PUSH32r ||
523           MBBI->getOpcode() == X86::PUSH64r)) {
524     PushedRegs = true;
525     ++MBBI;
526
527     if (!HasFP && needsFrameMoves) {
528       // Mark callee-saved push instruction.
529       MCSymbol *Label = MMI.getContext().CreateTempSymbol();
530       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
531
532       // Define the current CFA rule to use the provided offset.
533       unsigned Ptr = StackSize ?
534         MachineLocation::VirtualFP : StackPtr;
535       MachineLocation SPDst(Ptr);
536       MachineLocation SPSrc(Ptr, StackOffset);
537       Moves.push_back(MachineMove(Label, SPDst, SPSrc));
538       StackOffset += stackGrowth;
539     }
540   }
541
542   DL = MBB.findDebugLoc(MBBI);
543
544   // If there is an SUB32ri of ESP immediately before this instruction, merge
545   // the two. This can be the case when tail call elimination is enabled and
546   // the callee has more arguments then the caller.
547   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
548
549   // If there is an ADD32ri or SUB32ri of ESP immediately after this
550   // instruction, merge the two instructions.
551   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
552
553   // Adjust stack pointer: ESP -= numbytes.
554
555   // Windows and cygwin/mingw require a prologue helper routine when allocating
556   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
557   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
558   // stack and adjust the stack pointer in one go.  The 64-bit version of
559   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
560   // responsible for adjusting the stack pointer.  Touching the stack at 4K
561   // increments is necessary to ensure that the guard pages used by the OS
562   // virtual memory manager are allocated in correct sequence.
563   if (NumBytes >= 4096 && (STI.isTargetCygMing() || STI.isTargetWin32())) {
564     // Check whether EAX is livein for this function.
565     bool isEAXAlive = isEAXLiveIn(MF);
566
567     const char *StackProbeSymbol =
568       STI.isTargetWindows() ? "_chkstk" : "_alloca";
569     unsigned CallOp = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
570     if (!isEAXAlive) {
571       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
572         .addImm(NumBytes);
573       BuildMI(MBB, MBBI, DL, TII.get(CallOp))
574         .addExternalSymbol(StackProbeSymbol)
575         .addReg(StackPtr,    RegState::Define | RegState::Implicit)
576         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
577     } else {
578       // Save EAX
579       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
580         .addReg(X86::EAX, RegState::Kill);
581
582       // Allocate NumBytes-4 bytes on stack. We'll also use 4 already
583       // allocated bytes for EAX.
584       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
585         .addImm(NumBytes - 4);
586       BuildMI(MBB, MBBI, DL, TII.get(CallOp))
587         .addExternalSymbol(StackProbeSymbol)
588         .addReg(StackPtr,    RegState::Define | RegState::Implicit)
589         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
590
591       // Restore EAX
592       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
593                                               X86::EAX),
594                                       StackPtr, false, NumBytes - 4);
595       MBB.insert(MBBI, MI);
596     }
597   } else if (NumBytes >= 4096 && STI.isTargetWin64()) {
598     // Sanity check that EAX is not livein for this function.  It should
599     // should not be, so throw an assert.
600     assert(!isEAXLiveIn(MF) && "EAX is livein in the Win64 case!");
601
602     // Handle the 64-bit Windows ABI case where we need to call __chkstk.
603     // Function prologue is responsible for adjusting the stack pointer.
604     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
605       .addImm(NumBytes);
606     BuildMI(MBB, MBBI, DL, TII.get(X86::WINCALL64pcrel32))
607       .addExternalSymbol("__chkstk")
608       .addReg(StackPtr, RegState::Define | RegState::Implicit);
609     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
610                  TII, *RegInfo);
611   } else if (NumBytes)
612     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
613                  TII, *RegInfo);
614
615   if ((NumBytes || PushedRegs) && needsFrameMoves) {
616     // Mark end of stack pointer adjustment.
617     MCSymbol *Label = MMI.getContext().CreateTempSymbol();
618     BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
619
620     if (!HasFP && NumBytes) {
621       // Define the current CFA rule to use the provided offset.
622       if (StackSize) {
623         MachineLocation SPDst(MachineLocation::VirtualFP);
624         MachineLocation SPSrc(MachineLocation::VirtualFP,
625                               -StackSize + stackGrowth);
626         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
627       } else {
628         // FIXME: Verify & implement for FP
629         MachineLocation SPDst(StackPtr);
630         MachineLocation SPSrc(StackPtr, stackGrowth);
631         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
632       }
633     }
634
635     // Emit DWARF info specifying the offsets of the callee-saved registers.
636     if (PushedRegs)
637       emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
638   }
639 }
640
641 void X86FrameInfo::emitEpilogue(MachineFunction &MF,
642                                 MachineBasicBlock &MBB) const {
643   const MachineFrameInfo *MFI = MF.getFrameInfo();
644   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
645   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
646   const X86InstrInfo &TII = *TM.getInstrInfo();
647   MachineBasicBlock::iterator MBBI = prior(MBB.end());
648   unsigned RetOpcode = MBBI->getOpcode();
649   DebugLoc DL = MBBI->getDebugLoc();
650   bool Is64Bit = STI.is64Bit();
651   unsigned StackAlign = getStackAlignment();
652   unsigned SlotSize = RegInfo->getSlotSize();
653   unsigned FramePtr = RegInfo->getFrameRegister(MF);
654   unsigned StackPtr = RegInfo->getStackRegister();
655
656   switch (RetOpcode) {
657   default:
658     llvm_unreachable("Can only insert epilog into returning blocks");
659   case X86::RET:
660   case X86::RETI:
661   case X86::TCRETURNdi:
662   case X86::TCRETURNri:
663   case X86::TCRETURNmi:
664   case X86::TCRETURNdi64:
665   case X86::TCRETURNri64:
666   case X86::TCRETURNmi64:
667   case X86::EH_RETURN:
668   case X86::EH_RETURN64:
669     break;  // These are ok
670   }
671
672   // Get the number of bytes to allocate from the FrameInfo.
673   uint64_t StackSize = MFI->getStackSize();
674   uint64_t MaxAlign  = MFI->getMaxAlignment();
675   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
676   uint64_t NumBytes = 0;
677
678   // If we're forcing a stack realignment we can't rely on just the frame
679   // info, we need to know the ABI stack alignment as well in case we
680   // have a call out.  Otherwise just make sure we have some alignment - we'll
681   // go with the minimum.
682   if (ForceStackAlign) {
683     if (MFI->hasCalls())
684       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
685     else
686       MaxAlign = MaxAlign ? MaxAlign : 4;
687   }
688
689   if (hasFP(MF)) {
690     // Calculate required stack adjustment.
691     uint64_t FrameSize = StackSize - SlotSize;
692     if (RegInfo->needsStackRealignment(MF))
693       FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
694
695     NumBytes = FrameSize - CSSize;
696
697     // Pop EBP.
698     BuildMI(MBB, MBBI, DL,
699             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
700   } else {
701     NumBytes = StackSize - CSSize;
702   }
703
704   // Skip the callee-saved pop instructions.
705   MachineBasicBlock::iterator LastCSPop = MBBI;
706   while (MBBI != MBB.begin()) {
707     MachineBasicBlock::iterator PI = prior(MBBI);
708     unsigned Opc = PI->getOpcode();
709
710     if (Opc != X86::POP32r && Opc != X86::POP64r &&
711         !PI->getDesc().isTerminator())
712       break;
713
714     --MBBI;
715   }
716
717   DL = MBBI->getDebugLoc();
718
719   // If there is an ADD32ri or SUB32ri of ESP immediately before this
720   // instruction, merge the two instructions.
721   if (NumBytes || MFI->hasVarSizedObjects())
722     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
723
724   // If dynamic alloca is used, then reset esp to point to the last callee-saved
725   // slot before popping them off! Same applies for the case, when stack was
726   // realigned.
727   if (RegInfo->needsStackRealignment(MF)) {
728     // We cannot use LEA here, because stack pointer was realigned. We need to
729     // deallocate local frame back.
730     if (CSSize) {
731       emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
732       MBBI = prior(LastCSPop);
733     }
734
735     BuildMI(MBB, MBBI, DL,
736             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
737             StackPtr).addReg(FramePtr);
738   } else if (MFI->hasVarSizedObjects()) {
739     if (CSSize) {
740       unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
741       MachineInstr *MI =
742         addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
743                      FramePtr, false, -CSSize);
744       MBB.insert(MBBI, MI);
745     } else {
746       BuildMI(MBB, MBBI, DL,
747               TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
748         .addReg(FramePtr);
749     }
750   } else if (NumBytes) {
751     // Adjust stack pointer back: ESP += numbytes.
752     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
753   }
754
755   // We're returning from function via eh_return.
756   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
757     MBBI = prior(MBB.end());
758     MachineOperand &DestAddr  = MBBI->getOperand(0);
759     assert(DestAddr.isReg() && "Offset should be in register!");
760     BuildMI(MBB, MBBI, DL,
761             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
762             StackPtr).addReg(DestAddr.getReg());
763   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
764              RetOpcode == X86::TCRETURNmi ||
765              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
766              RetOpcode == X86::TCRETURNmi64) {
767     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
768     // Tail call return: adjust the stack pointer and jump to callee.
769     MBBI = prior(MBB.end());
770     MachineOperand &JumpTarget = MBBI->getOperand(0);
771     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
772     assert(StackAdjust.isImm() && "Expecting immediate value.");
773
774     // Adjust stack pointer.
775     int StackAdj = StackAdjust.getImm();
776     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
777     int Offset = 0;
778     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
779
780     // Incoporate the retaddr area.
781     Offset = StackAdj-MaxTCDelta;
782     assert(Offset >= 0 && "Offset should never be negative");
783
784     if (Offset) {
785       // Check for possible merge with preceeding ADD instruction.
786       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
787       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
788     }
789
790     // Jump to label or value in register.
791     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
792       MachineInstrBuilder MIB =
793         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
794                                        ? X86::TAILJMPd : X86::TAILJMPd64));
795       if (JumpTarget.isGlobal())
796         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
797                              JumpTarget.getTargetFlags());
798       else {
799         assert(JumpTarget.isSymbol());
800         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
801                               JumpTarget.getTargetFlags());
802       }
803     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
804       MachineInstrBuilder MIB =
805         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
806                                        ? X86::TAILJMPm : X86::TAILJMPm64));
807       for (unsigned i = 0; i != 5; ++i)
808         MIB.addOperand(MBBI->getOperand(i));
809     } else if (RetOpcode == X86::TCRETURNri64) {
810       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
811         addReg(JumpTarget.getReg(), RegState::Kill);
812     } else {
813       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
814         addReg(JumpTarget.getReg(), RegState::Kill);
815     }
816
817     MachineInstr *NewMI = prior(MBBI);
818     for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
819       NewMI->addOperand(MBBI->getOperand(i));
820
821     // Delete the pseudo instruction TCRETURN.
822     MBB.erase(MBBI);
823   } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
824              (X86FI->getTCReturnAddrDelta() < 0)) {
825     // Add the return addr area delta back since we are not tail calling.
826     int delta = -1*X86FI->getTCReturnAddrDelta();
827     MBBI = prior(MBB.end());
828
829     // Check for possible merge with preceeding ADD instruction.
830     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
831     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
832   }
833 }
834
835 void
836 X86FrameInfo::getInitialFrameState(std::vector<MachineMove> &Moves) const {
837   // Calculate amount of bytes used for return address storing
838   int stackGrowth = (STI.is64Bit() ? -8 : -4);
839   const X86RegisterInfo *RI = TM.getRegisterInfo();
840
841   // Initial state of the frame pointer is esp+stackGrowth.
842   MachineLocation Dst(MachineLocation::VirtualFP);
843   MachineLocation Src(RI->getStackRegister(), stackGrowth);
844   Moves.push_back(MachineMove(0, Dst, Src));
845
846   // Add return address to move list
847   MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
848   MachineLocation CSSrc(RI->getRARegister());
849   Moves.push_back(MachineMove(0, CSDst, CSSrc));
850 }
851
852 int X86FrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
853   const X86RegisterInfo *RI =
854     static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
855   const MachineFrameInfo *MFI = MF.getFrameInfo();
856   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
857   uint64_t StackSize = MFI->getStackSize();
858
859   if (RI->needsStackRealignment(MF)) {
860     if (FI < 0) {
861       // Skip the saved EBP.
862       Offset += RI->getSlotSize();
863     } else {
864       unsigned Align = MFI->getObjectAlignment(FI);
865       assert((-(Offset + StackSize)) % Align == 0);
866       Align = 0;
867       return Offset + StackSize;
868     }
869     // FIXME: Support tail calls
870   } else {
871     if (!hasFP(MF))
872       return Offset + StackSize;
873
874     // Skip the saved EBP.
875     Offset += RI->getSlotSize();
876
877     // Skip the RETADDR move area
878     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
879     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
880     if (TailCallReturnAddrDelta < 0)
881       Offset -= TailCallReturnAddrDelta;
882   }
883
884   return Offset;
885 }
886
887 bool X86FrameInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
888                                              MachineBasicBlock::iterator MI,
889                                         const std::vector<CalleeSavedInfo> &CSI,
890                                           const TargetRegisterInfo *TRI) const {
891   if (CSI.empty())
892     return false;
893
894   DebugLoc DL = MBB.findDebugLoc(MI);
895
896   MachineFunction &MF = *MBB.getParent();
897
898   bool isWin64 = STI.isTargetWin64();
899   unsigned SlotSize = STI.is64Bit() ? 8 : 4;
900   unsigned FPReg = TRI->getFrameRegister(MF);
901   unsigned CalleeFrameSize = 0;
902
903   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
904   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
905
906   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
907   for (unsigned i = CSI.size(); i != 0; --i) {
908     unsigned Reg = CSI[i-1].getReg();
909     // Add the callee-saved register as live-in. It's killed at the spill.
910     MBB.addLiveIn(Reg);
911     if (Reg == FPReg)
912       // X86RegisterInfo::emitPrologue will handle spilling of frame register.
913       continue;
914     if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
915       CalleeFrameSize += SlotSize;
916       BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
917     } else {
918       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
919       TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
920                               RC, TRI);
921     }
922   }
923
924   X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
925   return true;
926 }
927
928 bool X86FrameInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
929                                                MachineBasicBlock::iterator MI,
930                                         const std::vector<CalleeSavedInfo> &CSI,
931                                           const TargetRegisterInfo *TRI) const {
932   if (CSI.empty())
933     return false;
934
935   DebugLoc DL = MBB.findDebugLoc(MI);
936
937   MachineFunction &MF = *MBB.getParent();
938   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
939   unsigned FPReg = TRI->getFrameRegister(MF);
940   bool isWin64 = STI.isTargetWin64();
941   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
942   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
943     unsigned Reg = CSI[i].getReg();
944     if (Reg == FPReg)
945       // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
946       continue;
947     if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
948       BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
949     } else {
950       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
951       TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
952                                RC, TRI);
953     }
954   }
955   return true;
956 }
957
958 void
959 X86FrameInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
960                                                    RegScavenger *RS) const {
961   MachineFrameInfo *MFI = MF.getFrameInfo();
962   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
963   unsigned SlotSize = RegInfo->getSlotSize();
964
965   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
966   int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
967
968   if (TailCallReturnAddrDelta < 0) {
969     // create RETURNADDR area
970     //   arg
971     //   arg
972     //   RETADDR
973     //   { ...
974     //     RETADDR area
975     //     ...
976     //   }
977     //   [EBP]
978     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
979                            (-1U*SlotSize)+TailCallReturnAddrDelta, true);
980   }
981
982   if (hasFP(MF)) {
983     assert((TailCallReturnAddrDelta <= 0) &&
984            "The Delta should always be zero or negative");
985     const TargetFrameInfo &TFI = *MF.getTarget().getFrameInfo();
986
987     // Create a frame entry for the EBP register that must be saved.
988     int FrameIdx = MFI->CreateFixedObject(SlotSize,
989                                           -(int)SlotSize +
990                                           TFI.getOffsetOfLocalArea() +
991                                           TailCallReturnAddrDelta,
992                                           true);
993     assert(FrameIdx == MFI->getObjectIndexBegin() &&
994            "Slot for EBP register must be last in order to be found!");
995     FrameIdx = 0;
996   }
997 }