Handle frame offset due to return address pushed on the stack
[oota-llvm.git] / lib / Target / X86 / X86RegisterInfo.cpp
1 //===- X86RegisterInfo.cpp - X86 Register Information -----------*- C++ -*-===//
2 //
3 // This file contains the X86 implementation of the MRegisterInfo class.  This
4 // file is responsible for the frame pointer elimination optimization on X86.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "X86.h"
9 #include "X86RegisterInfo.h"
10 #include "X86InstrBuilder.h"
11 #include "llvm/Constants.h"
12 #include "llvm/Type.h"
13 #include "llvm/CodeGen/MachineInstrBuilder.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "Support/CommandLine.h"
17
18 namespace {
19   cl::opt<bool>
20   NoFPElim("no-fp-elim",
21            cl::desc("Disable frame pointer elimination optimization"));
22 }
23
24 static unsigned getIdx(const TargetRegisterClass *RC) {
25   switch (RC->getSize()) {
26   default: assert(0 && "Invalid data size!");
27   case 1:  return 0;
28   case 2:  return 1;
29   case 4:  return 2;
30   case 10: return 3;
31   }
32 }
33
34 void X86RegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
35                                           MachineBasicBlock::iterator &MBBI,
36                                           unsigned SrcReg, int FrameIdx,
37                                           const TargetRegisterClass *RC) const {
38   static const unsigned Opcode[] =
39     { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32, X86::FSTPr80 };
40   MachineInstr *MI = addFrameReference(BuildMI(Opcode[getIdx(RC)], 5),
41                                        FrameIdx).addReg(SrcReg);
42   MBBI = MBB.insert(MBBI, MI)+1;
43 }
44
45 void X86RegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
46                                            MachineBasicBlock::iterator &MBBI,
47                                            unsigned DestReg, int FrameIdx,
48                                            const TargetRegisterClass *RC) const{
49   static const unsigned Opcode[] =
50     { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, X86::FLDr80 };
51   MachineInstr *MI = addFrameReference(BuildMI(Opcode[getIdx(RC)], 4, DestReg),
52                                        FrameIdx);
53   MBBI = MBB.insert(MBBI, MI)+1;
54 }
55
56 void X86RegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
57                                    MachineBasicBlock::iterator &MBBI,
58                                    unsigned DestReg, unsigned SrcReg,
59                                    const TargetRegisterClass *RC) const {
60   static const unsigned Opcode[] =
61     { X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV };
62   MachineInstr *MI = BuildMI(Opcode[getIdx(RC)],1,DestReg).addReg(SrcReg);
63   MBBI = MBB.insert(MBBI, MI)+1;
64 }
65
66 const unsigned* X86RegisterInfo::getCalleeSaveRegs() const {
67   static const unsigned CalleeSaveRegs[] = {
68     X86::ESI, X86::EDI, X86::EBX, X86::EBP, 0
69   };
70   return CalleeSaveRegs;
71 }
72
73
74 //===----------------------------------------------------------------------===//
75 // Stack Frame Processing methods
76 //===----------------------------------------------------------------------===//
77
78 // hasFP - Return true if the specified function should have a dedicated frame
79 // pointer register.  This is true if the function has variable sized allocas or
80 // if frame pointer elimination is disabled.
81 //
82 static bool hasFP(MachineFunction &MF) {
83   return NoFPElim || MF.getFrameInfo()->hasVarSizedObjects();
84 }
85
86 // hasSPAdjust - Return true if this function has ESP adjustment instructions in
87 // the prolog and epilog which allocate local stack space.  This is neccesary
88 // because we elide these instructions if there are no function calls in the
89 // current function (ie, this is a leaf function).  In this case, we can refer
90 // beyond the stack pointer because we know that nothing will trample on that
91 // part of the stack.
92 //
93 static bool hasSPAdjust(MachineFunction &MF) {
94   assert(!hasFP(MF) && "Can only eliminate SP adjustment if no frame-pointer!");
95   return MF.getFrameInfo()->hasCalls();
96 }
97
98 void X86RegisterInfo::eliminateCallFramePseudoInstr(MachineFunction &MF,
99                                                     MachineBasicBlock &MBB,
100                                          MachineBasicBlock::iterator &I) const {
101   MachineInstr *New = 0, *Old = *I;;
102   if (hasFP(MF)) {
103     // If we have a frame pointer, turn the adjcallstackup instruction into a
104     // 'sub ESP, <amt>' and the adjcallstackdown instruction into 'add ESP,
105     // <amt>'
106     unsigned Amount = Old->getOperand(0).getImmedValue();
107     if (Amount != 0) {
108       if (Old->getOpcode() == X86::ADJCALLSTACKDOWN) {
109         New=BuildMI(X86::SUBri32, 2, X86::ESP).addReg(X86::ESP).addZImm(Amount);
110       } else {
111         assert(Old->getOpcode() == X86::ADJCALLSTACKUP);
112         New=BuildMI(X86::ADDri32, 2, X86::ESP).addReg(X86::ESP).addZImm(Amount);
113       }
114     }
115   }
116
117   if (New)
118     *I = New;        // Replace the pseudo instruction with a new instruction...
119   else
120     I = MBB.erase(I);// Just delete the pseudo instruction...
121   delete Old;
122 }
123
124 void X86RegisterInfo::eliminateFrameIndex(MachineFunction &MF,
125                                         MachineBasicBlock::iterator &II) const {
126   unsigned i = 0;
127   MachineInstr &MI = **II;
128   while (!MI.getOperand(i).isFrameIndex()) {
129     ++i;
130     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
131   }
132
133   int FrameIndex = MI.getOperand(i).getFrameIndex();
134
135   // This must be part of a four operand memory reference.  Replace the
136   // FrameIndex with base register with EBP.  Add add an offset to the offset.
137   MI.SetMachineOperandReg(i, hasFP(MF) ? X86::EBP : X86::ESP);
138
139   // Now add the frame object offset to the offset from EBP.
140   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
141                MI.getOperand(i+3).getImmedValue()+4;
142
143   if (!hasFP(MF) && hasSPAdjust(MF)) {
144     const MachineFrameInfo *MFI = MF.getFrameInfo();
145     Offset += MFI->getStackSize();
146   }
147
148   MI.SetMachineOperandConst(i+3, MachineOperand::MO_SignExtendedImmed, Offset);
149 }
150
151 void X86RegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
152   const {
153   if (hasFP(MF)) {
154     // Create a frame entry for the EBP register that must be saved.
155     int FrameIdx = MF.getFrameInfo()->CreateStackObject(4, 4);
156     assert(FrameIdx == MF.getFrameInfo()->getObjectIndexEnd()-1 &&
157            "Slot for EBP register must be last in order to be found!");
158   }
159 }
160
161 void X86RegisterInfo::emitPrologue(MachineFunction &MF) const {
162   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
163   MachineBasicBlock::iterator MBBI = MBB.begin();
164   MachineFrameInfo *MFI = MF.getFrameInfo();
165   MachineInstr *MI;
166
167   // Get the number of bytes to allocate from the FrameInfo
168   unsigned NumBytes = MFI->getStackSize();
169   if (hasFP(MF)) {
170     // Get the offset of the stack slot for the EBP register... which is
171     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
172     int EBPOffset = MFI->getObjectOffset(MFI->getObjectIndexEnd()-1)+4;
173
174     MI = addRegOffset(BuildMI(X86::MOVrm32, 5),    // mov [ESP-<offset>], EBP
175                       X86::ESP, EBPOffset).addReg(X86::EBP);
176     MBBI = MBB.insert(MBBI, MI)+1;
177     
178     MI = BuildMI(X86::MOVrr32, 2, X86::EBP).addReg(X86::ESP);
179     MBBI = MBB.insert(MBBI, MI)+1;
180   } else {
181     // If we don't have a frame pointer, and the function contains no call sites
182     // (it's a leaf function), we don't have to emit ANY stack adjustment
183     // instructions at all, we can just refer to the area beyond the stack
184     // pointer.  This can be important for small functions.
185     //
186     if (!hasSPAdjust(MF)) return;
187
188     // When we have no frame pointer, we reserve argument space for call sites
189     // in the function immediately on entry to the current function.  This
190     // eliminates the need for add/sub ESP brackets around call sites.
191     //
192     NumBytes += MFI->getMaxCallFrameSize();
193
194     // Update frame info to pretend that this is part of the stack...
195     MFI->setStackSize(NumBytes);
196   }
197
198   if (NumBytes) {
199     // adjust stack pointer: ESP -= numbytes
200     MI  = BuildMI(X86::SUBri32, 2, X86::ESP).addReg(X86::ESP).addZImm(NumBytes);
201     MBBI = 1+MBB.insert(MBBI, MI);
202   }
203 }
204
205 void X86RegisterInfo::emitEpilogue(MachineFunction &MF,
206                                    MachineBasicBlock &MBB) const {
207   const MachineFrameInfo *MFI = MF.getFrameInfo();
208   MachineBasicBlock::iterator MBBI = MBB.end()-1;
209   MachineInstr *MI;
210   assert((*MBBI)->getOpcode() == X86::RET &&
211          "Can only insert epilog into returning blocks");
212
213   if (hasFP(MF)) {
214     // Get the offset of the stack slot for the EBP register... which is
215     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
216     int EBPOffset = MFI->getObjectOffset(MFI->getObjectIndexEnd()-1)+4;
217     
218     // mov ESP, EBP
219     MI = BuildMI(X86::MOVrr32, 1,X86::ESP).addReg(X86::EBP);
220     MBBI = 1+MBB.insert(MBBI, MI);
221
222     // mov EBP, [ESP-<offset>]
223     MI = addRegOffset(BuildMI(X86::MOVmr32, 5, X86::EBP), X86::ESP, EBPOffset);
224     MBBI = 1+MBB.insert(MBBI, MI);
225   } else {
226     if (!hasSPAdjust(MF)) return;
227
228     // Get the number of bytes allocated from the FrameInfo...
229     unsigned NumBytes = MFI->getStackSize();
230
231     if (NumBytes) {    // adjust stack pointer back: ESP += numbytes
232       MI =BuildMI(X86::ADDri32, 2, X86::ESP).addReg(X86::ESP).addZImm(NumBytes);
233       MBBI = 1+MBB.insert(MBBI, MI);
234     }
235   }
236 }
237
238
239 //===----------------------------------------------------------------------===//
240 // Register Class Implementation Code
241 //===----------------------------------------------------------------------===//
242
243 //===----------------------------------------------------------------------===//
244 //   8 Bit Integer Registers
245 //
246 namespace {
247   const unsigned ByteRegClassRegs[] = {
248     X86::AL, X86::CL, X86::DL, X86::BL, X86::AH, X86::CH, X86::DH, X86::BH,
249   };
250
251   TargetRegisterClass X86ByteRegisterClassInstance(1, 1, ByteRegClassRegs,
252  ByteRegClassRegs+sizeof(ByteRegClassRegs)/sizeof(ByteRegClassRegs[0]));
253
254 //===----------------------------------------------------------------------===//
255 //   16 Bit Integer Registers
256 //
257   const unsigned ShortRegClassRegs[] = {
258     X86::AX, X86::CX, X86::DX, X86::BX, X86::SI, X86::DI, X86::BP, X86::SP
259   };
260
261   struct R16CL : public TargetRegisterClass {
262     R16CL():TargetRegisterClass(2, 2, ShortRegClassRegs, ShortRegClassRegs+8) {}
263     iterator allocation_order_end(MachineFunction &MF)   const {
264       if (hasFP(MF))     // Does the function dedicate EBP to being a frame ptr?
265         return end()-2;  // Don't allocate SP or BP
266       else
267         return end()-1;  // Don't allocate SP
268     }
269   } X86ShortRegisterClassInstance;
270
271 //===----------------------------------------------------------------------===//
272 //   32 Bit Integer Registers
273 //
274   const unsigned IntRegClassRegs[] = {
275     X86::EAX, X86::ECX, X86::EDX, X86::EBX,
276     X86::ESI, X86::EDI, X86::EBP, X86::ESP
277   };
278
279   struct R32CL : public TargetRegisterClass {
280     R32CL() : TargetRegisterClass(4, 4, IntRegClassRegs, IntRegClassRegs+8) {}
281     iterator allocation_order_end(MachineFunction &MF)   const {
282       if (hasFP(MF))     // Does the function dedicate EBP to being a frame ptr?
283         return end()-2;  // Don't allocate ESP or EBP
284       else
285         return end()-1;  // Don't allocate ESP
286     }
287   } X86IntRegisterClassInstance;
288
289 //===----------------------------------------------------------------------===//
290 //   Pseudo Floating Point Registers
291 //
292   const unsigned PFPRegClassRegs[] = {
293 #define PFP(ENUM, NAME, FLAGS, TSFLAGS, ALIAS_SET) X86::ENUM,
294 #include "X86RegisterInfo.def"
295   };
296
297   TargetRegisterClass X86FPRegisterClassInstance(10, 4, PFPRegClassRegs,
298       PFPRegClassRegs+sizeof(PFPRegClassRegs)/sizeof(PFPRegClassRegs[0]));
299
300 //===----------------------------------------------------------------------===//
301 // Register class array...
302 //
303   const TargetRegisterClass * const X86RegClasses[] = {
304     &X86ByteRegisterClassInstance,
305     &X86ShortRegisterClassInstance,
306     &X86IntRegisterClassInstance,
307     &X86FPRegisterClassInstance,
308   };
309 }
310
311
312 // Create static lists to contain register alias sets...
313 #define ALIASLIST(NAME, ...) \
314   static const unsigned NAME[] = { __VA_ARGS__ };
315 #include "X86RegisterInfo.def"
316
317
318 // X86Regs - Turn the X86RegisterInfo.def file into a bunch of register
319 // descriptors
320 //
321 static const MRegisterDesc X86Regs[] = {
322 #define R(ENUM, NAME, FLAGS, TSFLAGS, ALIAS_SET) \
323          { NAME, ALIAS_SET, FLAGS, TSFLAGS },
324 #include "X86RegisterInfo.def"
325 };
326
327 X86RegisterInfo::X86RegisterInfo()
328   : MRegisterInfo(X86Regs, sizeof(X86Regs)/sizeof(X86Regs[0]),
329                   X86RegClasses,
330                   X86RegClasses+sizeof(X86RegClasses)/sizeof(X86RegClasses[0]),
331                   X86::ADJCALLSTACKDOWN, X86::ADJCALLSTACKUP) {
332 }
333
334
335
336 const TargetRegisterClass*
337 X86RegisterInfo::getRegClassForType(const Type* Ty) const {
338   switch (Ty->getPrimitiveID()) {
339   case Type::LongTyID:
340   case Type::ULongTyID: assert(0 && "Long values can't fit in registers!");
341   default:              assert(0 && "Invalid type to getClass!");
342   case Type::BoolTyID:
343   case Type::SByteTyID:
344   case Type::UByteTyID:   return &X86ByteRegisterClassInstance;
345   case Type::ShortTyID:
346   case Type::UShortTyID:  return &X86ShortRegisterClassInstance;
347   case Type::IntTyID:
348   case Type::UIntTyID:
349   case Type::PointerTyID: return &X86IntRegisterClassInstance;
350     
351   case Type::FloatTyID:
352   case Type::DoubleTyID: return &X86FPRegisterClassInstance;
353   }
354 }