Fix epilogue codegen to avoid leaving the stack pointer in an invalid
[oota-llvm.git] / lib / Target / ARM / ARMFrameInfo.cpp
1 //=======- ARMFrameInfo.cpp - ARM 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 ARM implementation of TargetFrameInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMFrameInfo.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMMachineFunctionInfo.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Target/TargetOptions.h"
22
23 using namespace llvm;
24
25 /// hasFP - Return true if the specified function should have a dedicated frame
26 /// pointer register.  This is true if the function has variable sized allocas
27 /// or if frame pointer elimination is disabled.
28 ///
29 bool ARMFrameInfo::hasFP(const MachineFunction &MF) const {
30   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
31
32   // Mac OS X requires FP not to be clobbered for backtracing purpose.
33   if (STI.isTargetDarwin())
34     return true;
35
36   const MachineFrameInfo *MFI = MF.getFrameInfo();
37   // Always eliminate non-leaf frame pointers.
38   return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
39           RegInfo->needsStackRealignment(MF) ||
40           MFI->hasVarSizedObjects() ||
41           MFI->isFrameAddressTaken());
42 }
43
44 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
45 // not required, we reserve argument space for call sites in the function
46 // immediately on entry to the current function. This eliminates the need for
47 // add/sub sp brackets around call sites. Returns true if the call frame is
48 // included as part of the stack frame.
49 bool ARMFrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
50   const MachineFrameInfo *FFI = MF.getFrameInfo();
51   unsigned CFSize = FFI->getMaxCallFrameSize();
52   // It's not always a good idea to include the call frame as part of the
53   // stack frame. ARM (especially Thumb) has small immediate offset to
54   // address the stack frame. So a large call frame can cause poor codegen
55   // and may even makes it impossible to scavenge a register.
56   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
57     return false;
58
59   return !MF.getFrameInfo()->hasVarSizedObjects();
60 }
61
62 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
63 // call frame pseudos can be simplified. Unlike most targets, having a FP
64 // is not sufficient here since we still may reference some objects via SP
65 // even when FP is available in Thumb2 mode.
66 bool ARMFrameInfo::canSimplifyCallFramePseudos(const MachineFunction &MF)const {
67   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
68 }
69
70 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
71   for (unsigned i = 0; CSRegs[i]; ++i)
72     if (Reg == CSRegs[i])
73       return true;
74   return false;
75 }
76
77 static bool isCSRestore(MachineInstr *MI,
78                         const ARMBaseInstrInfo &TII,
79                         const unsigned *CSRegs) {
80   // Integer spill area is handled with "pop".
81   if (MI->getOpcode() == ARM::LDMIA_RET ||
82       MI->getOpcode() == ARM::t2LDMIA_RET ||
83       MI->getOpcode() == ARM::LDMIA_UPD ||
84       MI->getOpcode() == ARM::t2LDMIA_UPD ||
85       MI->getOpcode() == ARM::VLDMDIA_UPD) {
86     // The first two operands are predicates. The last two are
87     // imp-def and imp-use of SP. Check everything in between.
88     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
89       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
90         return false;
91     return true;
92   }
93
94   return false;
95 }
96
97 static void
98 emitSPUpdate(bool isARM,
99              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
100              DebugLoc dl, const ARMBaseInstrInfo &TII,
101              int NumBytes,
102              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
103   if (isARM)
104     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
105                             Pred, PredReg, TII);
106   else
107     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
108                            Pred, PredReg, TII);
109 }
110
111 void ARMFrameInfo::emitPrologue(MachineFunction &MF) const {
112   MachineBasicBlock &MBB = MF.front();
113   MachineBasicBlock::iterator MBBI = MBB.begin();
114   MachineFrameInfo  *MFI = MF.getFrameInfo();
115   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
116   const ARMBaseRegisterInfo *RegInfo =
117     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
118   const ARMBaseInstrInfo &TII =
119     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
120   assert(!AFI->isThumb1OnlyFunction() &&
121          "This emitPrologue does not support Thumb1!");
122   bool isARM = !AFI->isThumbFunction();
123   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
124   unsigned NumBytes = MFI->getStackSize();
125   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
126   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
127   unsigned FramePtr = RegInfo->getFrameRegister(MF);
128
129   // Determine the sizes of each callee-save spill areas and record which frame
130   // belongs to which callee-save spill areas.
131   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
132   int FramePtrSpillFI = 0;
133
134   // Allocate the vararg register save area. This is not counted in NumBytes.
135   if (VARegSaveSize)
136     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
137
138   if (!AFI->hasStackFrame()) {
139     if (NumBytes != 0)
140       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
141     return;
142   }
143
144   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
145     unsigned Reg = CSI[i].getReg();
146     int FI = CSI[i].getFrameIdx();
147     switch (Reg) {
148     case ARM::R4:
149     case ARM::R5:
150     case ARM::R6:
151     case ARM::R7:
152     case ARM::LR:
153       if (Reg == FramePtr)
154         FramePtrSpillFI = FI;
155       AFI->addGPRCalleeSavedArea1Frame(FI);
156       GPRCS1Size += 4;
157       break;
158     case ARM::R8:
159     case ARM::R9:
160     case ARM::R10:
161     case ARM::R11:
162       if (Reg == FramePtr)
163         FramePtrSpillFI = FI;
164       if (STI.isTargetDarwin()) {
165         AFI->addGPRCalleeSavedArea2Frame(FI);
166         GPRCS2Size += 4;
167       } else {
168         AFI->addGPRCalleeSavedArea1Frame(FI);
169         GPRCS1Size += 4;
170       }
171       break;
172     default:
173       AFI->addDPRCalleeSavedAreaFrame(FI);
174       DPRCSSize += 8;
175     }
176   }
177   
178   // Move past area 1.
179   if (GPRCS1Size > 0) MBBI++;
180   
181   // Set FP to point to the stack slot that contains the previous FP.
182   // For Darwin, FP is R7, which has now been stored in spill area 1.
183   // Otherwise, if this is not Darwin, all the callee-saved registers go
184   // into spill area 1, including the FP in R11.  In either case, it is
185   // now safe to emit this assignment.
186   bool HasFP = hasFP(MF);
187   if (HasFP) {
188     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
189     MachineInstrBuilder MIB =
190       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
191       .addFrameIndex(FramePtrSpillFI).addImm(0);
192     AddDefaultCC(AddDefaultPred(MIB));
193   }
194   
195   // Move past area 2.
196   if (GPRCS2Size > 0) MBBI++;
197   
198   // Determine starting offsets of spill areas.
199   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
200   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
201   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
202   if (HasFP)
203     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
204                                 NumBytes);
205   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
206   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
207   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
208
209   // Move past area 3.
210   if (DPRCSSize > 0) MBBI++;
211   
212   NumBytes = DPRCSOffset;
213   if (NumBytes) {
214     // Adjust SP after all the callee-save spills.
215     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
216     if (HasFP && isARM)
217       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
218       // Note it's not safe to do this in Thumb2 mode because it would have
219       // taken two instructions:
220       // mov sp, r7
221       // sub sp, #24
222       // If an interrupt is taken between the two instructions, then sp is in
223       // an inconsistent state (pointing to the middle of callee-saved area).
224       // The interrupt handler can end up clobbering the registers.
225       AFI->setShouldRestoreSPFromFP(true);
226   }
227
228   if (STI.isTargetELF() && hasFP(MF))
229     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
230                              AFI->getFramePtrSpillOffset());
231
232   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
233   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
234   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
235
236   // If we need dynamic stack realignment, do it here. Be paranoid and make
237   // sure if we also have VLAs, we have a base pointer for frame access.
238   if (RegInfo->needsStackRealignment(MF)) {
239     unsigned MaxAlign = MFI->getMaxAlignment();
240     assert (!AFI->isThumb1OnlyFunction());
241     if (!AFI->isThumbFunction()) {
242       // Emit bic sp, sp, MaxAlign
243       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
244                                           TII.get(ARM::BICri), ARM::SP)
245                                   .addReg(ARM::SP, RegState::Kill)
246                                   .addImm(MaxAlign-1)));
247     } else {
248       // We cannot use sp as source/dest register here, thus we're emitting the
249       // following sequence:
250       // mov r4, sp
251       // bic r4, r4, MaxAlign
252       // mov sp, r4
253       // FIXME: It will be better just to find spare register here.
254       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
255         .addReg(ARM::SP, RegState::Kill);
256       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
257                                           TII.get(ARM::t2BICri), ARM::R4)
258                                   .addReg(ARM::R4, RegState::Kill)
259                                   .addImm(MaxAlign-1)));
260       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
261         .addReg(ARM::R4, RegState::Kill);
262     }
263
264     AFI->setShouldRestoreSPFromFP(true);
265   }
266
267   // If we need a base pointer, set it up here. It's whatever the value
268   // of the stack pointer is at this point. Any variable size objects
269   // will be allocated after this, so we can still use the base pointer
270   // to reference locals.
271   if (RegInfo->hasBasePointer(MF)) {
272     if (isARM)
273       BuildMI(MBB, MBBI, dl,
274               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
275         .addReg(ARM::SP)
276         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
277     else
278       BuildMI(MBB, MBBI, dl,
279               TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
280         .addReg(ARM::SP);
281   }
282
283   // If the frame has variable sized objects then the epilogue must restore
284   // the sp from fp.
285   if (MFI->hasVarSizedObjects())
286     AFI->setShouldRestoreSPFromFP(true);
287 }
288
289 void ARMFrameInfo::emitEpilogue(MachineFunction &MF,
290                                 MachineBasicBlock &MBB) const {
291   MachineBasicBlock::iterator MBBI = prior(MBB.end());
292   assert(MBBI->getDesc().isReturn() &&
293          "Can only insert epilog into returning blocks");
294   unsigned RetOpcode = MBBI->getOpcode();
295   DebugLoc dl = MBBI->getDebugLoc();
296   MachineFrameInfo *MFI = MF.getFrameInfo();
297   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
298   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
299   const ARMBaseInstrInfo &TII =
300     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
301   assert(!AFI->isThumb1OnlyFunction() &&
302          "This emitEpilogue does not support Thumb1!");
303   bool isARM = !AFI->isThumbFunction();
304
305   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
306   int NumBytes = (int)MFI->getStackSize();
307   unsigned FramePtr = RegInfo->getFrameRegister(MF);
308
309   if (!AFI->hasStackFrame()) {
310     if (NumBytes != 0)
311       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
312   } else {
313     // Unwind MBBI to point to first LDR / VLDRD.
314     const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
315     if (MBBI != MBB.begin()) {
316       do
317         --MBBI;
318       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
319       if (!isCSRestore(MBBI, TII, CSRegs))
320         ++MBBI;
321     }
322
323     // Move SP to start of FP callee save spill area.
324     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
325                  AFI->getGPRCalleeSavedArea2Size() +
326                  AFI->getDPRCalleeSavedAreaSize());
327
328     // Reset SP based on frame pointer only if the stack frame extends beyond
329     // frame pointer stack slot or target is ELF and the function has FP.
330     if (AFI->shouldRestoreSPFromFP()) {
331       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
332       if (NumBytes) {
333         if (isARM)
334           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
335                                   ARMCC::AL, 0, TII);
336         else {
337           // It's not possible to restore SP from FP in a single instruction.
338           // For Darwin, this looks like:
339           // mov sp, r7
340           // sub sp, #24
341           // This is bad, if an interrupt is taken after the mov, sp is in an
342           // inconsistent state.
343           // Use the first callee-saved register as a scratch register.
344           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
345                  "No scratch register to restore SP from FP!");
346           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
347                                  ARMCC::AL, 0, TII);
348           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
349             .addReg(ARM::R4);
350         }
351       } else {
352         // Thumb2 or ARM.
353         if (isARM)
354           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
355             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
356         else
357           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
358             .addReg(FramePtr);
359       }
360     } else if (NumBytes)
361       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
362
363     // Increment past our save areas.
364     if (AFI->getDPRCalleeSavedAreaSize()) MBBI++;
365     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
366     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
367   }
368
369   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
370       RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
371     // Tail call return: adjust the stack pointer and jump to callee.
372     MBBI = prior(MBB.end());
373     MachineOperand &JumpTarget = MBBI->getOperand(0);
374
375     // Jump to label or value in register.
376     if (RetOpcode == ARM::TCRETURNdi) {
377       BuildMI(MBB, MBBI, dl,
378             TII.get(STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)).
379         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
380                          JumpTarget.getTargetFlags());
381     } else if (RetOpcode == ARM::TCRETURNdiND) {
382       BuildMI(MBB, MBBI, dl,
383             TII.get(STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND)).
384         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
385                          JumpTarget.getTargetFlags());
386     } else if (RetOpcode == ARM::TCRETURNri) {
387       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
388         addReg(JumpTarget.getReg(), RegState::Kill);
389     } else if (RetOpcode == ARM::TCRETURNriND) {
390       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
391         addReg(JumpTarget.getReg(), RegState::Kill);
392     }
393
394     MachineInstr *NewMI = prior(MBBI);
395     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
396       NewMI->addOperand(MBBI->getOperand(i));
397
398     // Delete the pseudo instruction TCRETURN.
399     MBB.erase(MBBI);
400   }
401
402   if (VARegSaveSize)
403     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
404 }
405
406 // Provide a base+offset reference to an FI slot for debug info. It's the
407 // same as what we use for resolving the code-gen references for now.
408 // FIXME: This can go wrong when references are SP-relative and simple call
409 //        frames aren't used.
410 int
411 ARMFrameInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
412                                      unsigned &FrameReg) const {
413   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
414 }
415
416 int
417 ARMFrameInfo::ResolveFrameIndexReference(const MachineFunction &MF,
418                                          int FI,
419                                          unsigned &FrameReg,
420                                          int SPAdj) const {
421   const MachineFrameInfo *MFI = MF.getFrameInfo();
422   const ARMBaseRegisterInfo *RegInfo =
423     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
424   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
425   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
426   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
427   bool isFixed = MFI->isFixedObjectIndex(FI);
428
429   FrameReg = ARM::SP;
430   Offset += SPAdj;
431   if (AFI->isGPRCalleeSavedArea1Frame(FI))
432     return Offset - AFI->getGPRCalleeSavedArea1Offset();
433   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
434     return Offset - AFI->getGPRCalleeSavedArea2Offset();
435   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
436     return Offset - AFI->getDPRCalleeSavedAreaOffset();
437
438   // When dynamically realigning the stack, use the frame pointer for
439   // parameters, and the stack/base pointer for locals.
440   if (RegInfo->needsStackRealignment(MF)) {
441     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
442     if (isFixed) {
443       FrameReg = RegInfo->getFrameRegister(MF);
444       Offset = FPOffset;
445     } else if (MFI->hasVarSizedObjects()) {
446       assert(RegInfo->hasBasePointer(MF) &&
447              "VLAs and dynamic stack alignment, but missing base pointer!");
448       FrameReg = RegInfo->getBaseRegister();
449     }
450     return Offset;
451   }
452
453   // If there is a frame pointer, use it when we can.
454   if (hasFP(MF) && AFI->hasStackFrame()) {
455     // Use frame pointer to reference fixed objects. Use it for locals if
456     // there are VLAs (and thus the SP isn't reliable as a base).
457     if (isFixed || (MFI->hasVarSizedObjects() && !RegInfo->hasBasePointer(MF))) {
458       FrameReg = RegInfo->getFrameRegister(MF);
459       return FPOffset;
460     } else if (MFI->hasVarSizedObjects()) {
461       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
462       // Try to use the frame pointer if we can, else use the base pointer
463       // since it's available. This is handy for the emergency spill slot, in
464       // particular.
465       if (AFI->isThumb2Function()) {
466         if (FPOffset >= -255 && FPOffset < 0) {
467           FrameReg = RegInfo->getFrameRegister(MF);
468           return FPOffset;
469         }
470       } else
471         FrameReg = RegInfo->getBaseRegister();
472     } else if (AFI->isThumb2Function()) {
473       // In Thumb2 mode, the negative offset is very limited. Try to avoid
474       // out of range references.
475       if (FPOffset >= -255 && FPOffset < 0) {
476         FrameReg = RegInfo->getFrameRegister(MF);
477         return FPOffset;
478       }
479     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
480       // Otherwise, use SP or FP, whichever is closer to the stack slot.
481       FrameReg = RegInfo->getFrameRegister(MF);
482       return FPOffset;
483     }
484   }
485   // Use the base pointer if we have one.
486   if (RegInfo->hasBasePointer(MF))
487     FrameReg = RegInfo->getBaseRegister();
488   return Offset;
489 }
490
491 int ARMFrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
492   unsigned FrameReg;
493   return getFrameIndexReference(MF, FI, FrameReg);
494 }