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