XCore target: Fix llvm.eh.return and EH info register handling
[oota-llvm.git] / lib / Target / XCore / XCoreFrameLowering.cpp
1 //===-- XCoreFrameLowering.cpp - Frame info for XCore Target --------------===//
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 XCore frame information that doesn't fit anywhere else
11 // cleanly...
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "XCoreFrameLowering.h"
16 #include "XCore.h"
17 #include "XCoreInstrInfo.h"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetOptions.h"
30
31 #include <algorithm>    // std::sort
32
33 using namespace llvm;
34
35 static const unsigned FramePtr = XCore::R10;
36 static const int MaxImmU16 = (1<<16) - 1;
37
38 // helper functions. FIXME: Eliminate.
39 static inline bool isImmU6(unsigned val) {
40   return val < (1 << 6);
41 }
42
43 static inline bool isImmU16(unsigned val) {
44   return val < (1 << 16);
45 }
46
47 static void EmitDefCfaRegister(MachineBasicBlock &MBB,
48                                MachineBasicBlock::iterator MBBI, DebugLoc dl,
49                                const TargetInstrInfo &TII,
50                                MachineModuleInfo *MMI, unsigned DRegNum) {
51   MCSymbol *Label = MMI->getContext().CreateTempSymbol();
52   BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(Label);
53   MMI->addFrameInst(MCCFIInstruction::createDefCfaRegister(Label, DRegNum));
54 }
55
56 static void EmitDefCfaOffset(MachineBasicBlock &MBB,
57                              MachineBasicBlock::iterator MBBI, DebugLoc dl,
58                              const TargetInstrInfo &TII,
59                              MachineModuleInfo *MMI, int Offset) {
60   MCSymbol *Label = MMI->getContext().CreateTempSymbol();
61   BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(Label);
62   MMI->addFrameInst(MCCFIInstruction::createDefCfaOffset(Label, -Offset));
63 }
64
65 static void EmitCfiOffset(MachineBasicBlock &MBB,
66                           MachineBasicBlock::iterator MBBI, DebugLoc dl,
67                           const TargetInstrInfo &TII, MachineModuleInfo *MMI,
68                           unsigned DRegNum, int Offset, MCSymbol *Label) {
69   if (!Label) {
70     Label = MMI->getContext().CreateTempSymbol();
71     BuildMI(MBB, MBBI, dl, TII.get(XCore::PROLOG_LABEL)).addSym(Label);
72   }
73   MMI->addFrameInst(MCCFIInstruction::createOffset(Label, DRegNum, Offset));
74 }
75
76 /// The SP register is moved in steps of 'MaxImmU16' towards the bottom of the
77 /// frame. During these steps, it may be necessary to spill registers.
78 /// IfNeededExtSP emits the necessary EXTSP instructions to move the SP only
79 /// as far as to make 'OffsetFromBottom' reachable using an STWSP_lru6.
80 /// \param OffsetFromTop the spill offset from the top of the frame.
81 /// \param [in,out] Adjusted the current SP offset from the top of the frame.
82 static void IfNeededExtSP(MachineBasicBlock &MBB,
83                           MachineBasicBlock::iterator MBBI, DebugLoc dl,
84                           const TargetInstrInfo &TII, MachineModuleInfo *MMI,
85                           int OffsetFromTop, int &Adjusted, int FrameSize,
86                           bool emitFrameMoves) {
87   while (OffsetFromTop > Adjusted) {
88     assert(Adjusted < FrameSize && "OffsetFromTop is beyond FrameSize");
89     int remaining = FrameSize - Adjusted;
90     int OpImm = (remaining > MaxImmU16) ? MaxImmU16 : remaining;
91     int Opcode = isImmU6(OpImm) ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
92     BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addImm(OpImm);
93     Adjusted += OpImm;
94     if (emitFrameMoves)
95       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
96   }
97 }
98
99 /// The SP register is moved in steps of 'MaxImmU16' towards the top of the
100 /// frame. During these steps, it may be necessary to re-load registers.
101 /// IfNeededLDAWSP emits the necessary LDAWSP instructions to move the SP only
102 /// as far as to make 'OffsetFromTop' reachable using an LDAWSP_lru6.
103 /// \param OffsetFromTop the spill offset from the top of the frame.
104 /// \param [in,out] RemainingAdj the current SP offset from the top of the frame.
105 static void IfNeededLDAWSP(MachineBasicBlock &MBB,
106                            MachineBasicBlock::iterator MBBI, DebugLoc dl,
107                            const TargetInstrInfo &TII, int OffsetFromTop,
108                            int &RemainingAdj) {
109   while (OffsetFromTop < RemainingAdj - MaxImmU16) {
110     assert(RemainingAdj && "OffsetFromTop is beyond FrameSize");
111     int OpImm = (RemainingAdj > MaxImmU16) ? MaxImmU16 : RemainingAdj;
112     int Opcode = isImmU6(OpImm) ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
113     BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(OpImm);
114     RemainingAdj -= OpImm;
115   }
116 }
117
118 /// Creates an ordered list of registers that are spilled
119 /// during the emitPrologue/emitEpilogue.
120 /// Registers are ordered according to their frame offset.
121 /// As offsets are negative, the largest offsets will be first.
122 static void GetSpillList(SmallVectorImpl<std::pair<int,unsigned> > &SpillList,
123                          MachineFrameInfo *MFI, XCoreFunctionInfo *XFI,
124                          bool fetchLR, bool fetchFP) {
125   if (fetchLR) {
126     int Offset = MFI->getObjectOffset(XFI->getLRSpillSlot());
127     SpillList.push_back(std::pair<int,unsigned>(Offset, XCore::LR));
128   }
129   if (fetchFP) {
130     int Offset = MFI->getObjectOffset(XFI->getFPSpillSlot());
131     SpillList.push_back(std::pair<int,unsigned>(Offset, FramePtr));
132   }
133   std::sort(SpillList.begin(), SpillList.end());
134 }
135
136 /// Creates an ordered list of EH info register 'spills'.
137 /// These slots are only used by the unwinder and calls to llvm.eh.return().
138 /// Registers are ordered according to their frame offset.
139 /// As offsets are negative, the largest offsets will be first.
140 static void GetEHSpillList(SmallVectorImpl<std::pair<int,unsigned> > &SpillList,
141                            MachineFrameInfo *MFI, XCoreFunctionInfo *XFI,
142                            const TargetLowering *TL) {
143   assert(XFI->hasEHSpillSlot() && "There are no EH register spill slots");
144   const int* EHSlot = XFI->getEHSpillSlot();
145   SpillList.push_back(
146       std::pair<int,unsigned>(MFI->getObjectOffset(EHSlot[0]),
147                               TL->getExceptionPointerRegister()));
148   SpillList.push_back(
149       std::pair<int,unsigned>(MFI->getObjectOffset(EHSlot[1]),
150                               TL->getExceptionSelectorRegister()));
151   std::sort(SpillList.begin(), SpillList.end());
152 }
153
154 /// Restore clobbered registers with their spill slot value.
155 /// The SP will be adjusted at the same time, thus the SpillList must be ordered
156 /// with the largest (negative) offsets first.
157 static void
158 RestoreSpillList(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
159                  DebugLoc dl, const TargetInstrInfo &TII, int &RemainingAdj,
160                  SmallVectorImpl<std::pair<int,unsigned> > &SpillList) {
161   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
162     unsigned SpilledReg = SpillList[i].second;
163     int SpillOffset = SpillList[i].first;
164     assert(SpillOffset % 4 == 0 && "Misaligned stack offset");
165     assert(SpillOffset <= 0 && "Unexpected positive stack offset");
166     int OffsetFromTop = - SpillOffset/4;
167     IfNeededLDAWSP(MBB, MBBI, dl, TII, OffsetFromTop, RemainingAdj);
168     int Offset = RemainingAdj - OffsetFromTop;
169     int Opcode = isImmU6(Offset) ? XCore::LDWSP_ru6 : XCore::LDWSP_lru6;
170     BuildMI(MBB, MBBI, dl, TII.get(Opcode), SpilledReg).addImm(Offset);
171   }
172 }
173
174 //===----------------------------------------------------------------------===//
175 // XCoreFrameLowering:
176 //===----------------------------------------------------------------------===//
177
178 XCoreFrameLowering::XCoreFrameLowering(const XCoreSubtarget &sti)
179   : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, 4, 0) {
180   // Do nothing
181 }
182
183 bool XCoreFrameLowering::hasFP(const MachineFunction &MF) const {
184   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
185          MF.getFrameInfo()->hasVarSizedObjects();
186 }
187
188 void XCoreFrameLowering::emitPrologue(MachineFunction &MF) const {
189   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
190   MachineBasicBlock::iterator MBBI = MBB.begin();
191   MachineFrameInfo *MFI = MF.getFrameInfo();
192   MachineModuleInfo *MMI = &MF.getMMI();
193   const MCRegisterInfo *MRI = MMI->getContext().getRegisterInfo();
194   const XCoreInstrInfo &TII =
195     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
196   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
197   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
198
199   if (MFI->getMaxAlignment() > getStackAlignment())
200     report_fatal_error("emitPrologue unsupported alignment: "
201                        + Twine(MFI->getMaxAlignment()));
202
203   const AttributeSet &PAL = MF.getFunction()->getAttributes();
204   if (PAL.hasAttrSomewhere(Attribute::Nest))
205     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDWSP_ru6), XCore::R11).addImm(0);
206
207   // Work out frame sizes.
208   // We will adjust the SP in stages towards the final FrameSize.
209   assert(MFI->getStackSize()%4 == 0 && "Misaligned frame size");
210   const int FrameSize = MFI->getStackSize() / 4;
211   int Adjusted = 0;
212
213   bool saveLR = XFI->hasLRSpillSlot();
214   bool UseENTSP = saveLR && FrameSize
215                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
216   if (UseENTSP)
217     saveLR = false;
218   bool FP = hasFP(MF);
219   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(MF);
220
221   if (UseENTSP) {
222     // Allocate space on the stack at the same time as saving LR.
223     Adjusted = (FrameSize > MaxImmU16) ? MaxImmU16 : FrameSize;
224     int Opcode = isImmU6(Adjusted) ? XCore::ENTSP_u6 : XCore::ENTSP_lu6;
225     MBB.addLiveIn(XCore::LR);
226     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode));
227     MIB.addImm(Adjusted);
228     MIB->addRegisterKilled(XCore::LR, MF.getTarget().getRegisterInfo(), true);
229     if (emitFrameMoves) {
230       EmitDefCfaOffset(MBB, MBBI, dl, TII, MMI, Adjusted*4);
231       unsigned DRegNum = MRI->getDwarfRegNum(XCore::LR, true);
232       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, 0, NULL);
233     }
234   }
235
236   // If necessary, save LR and FP to the stack, as we EXTSP.
237   SmallVector<std::pair<int,unsigned>,2> SpillList;
238   GetSpillList(SpillList, MFI, XFI, saveLR, FP);
239   // We want the nearest (negative) offsets first, so reverse list.
240   std::reverse(SpillList.begin(),SpillList.end());
241   for (unsigned i = 0, e = SpillList.size(); i != e; ++i) {
242     unsigned SpillReg = SpillList[i].second;
243     int SpillOffset = SpillList[i].first;
244     assert(SpillOffset % 4 == 0 && "Misaligned stack offset");
245     assert(SpillOffset <= 0 && "Unexpected positive stack offset");
246     int OffsetFromTop = - SpillOffset/4;
247     IfNeededExtSP(MBB, MBBI, dl, TII, MMI, OffsetFromTop, Adjusted, FrameSize,
248                   emitFrameMoves);
249     int Offset = Adjusted - OffsetFromTop;
250     int Opcode = isImmU6(Offset) ? XCore::STWSP_ru6 : XCore::STWSP_lru6;
251     MBB.addLiveIn(SpillReg);
252     BuildMI(MBB, MBBI, dl, TII.get(Opcode)).addReg(SpillReg, RegState::Kill)
253                                            .addImm(Offset);
254     if (emitFrameMoves) {
255       unsigned DRegNum = MRI->getDwarfRegNum(SpillReg, true);
256       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, SpillOffset, NULL);
257     }
258   }
259
260   // Complete any remaining Stack adjustment.
261   IfNeededExtSP(MBB, MBBI, dl, TII, MMI, FrameSize, Adjusted, FrameSize,
262                 emitFrameMoves);
263   assert(Adjusted==FrameSize && "IfNeededExtSP has not completed adjustment");
264
265   if (FP) {
266     // Set the FP from the SP.
267     BuildMI(MBB, MBBI, dl, TII.get(XCore::LDAWSP_ru6), FramePtr).addImm(0);
268     if (emitFrameMoves)
269       EmitDefCfaRegister(MBB, MBBI, dl, TII, MMI,
270                          MRI->getDwarfRegNum(FramePtr, true));
271   }
272
273   if (emitFrameMoves) {
274     // Frame moves for callee saved.
275     std::vector<std::pair<MCSymbol*, CalleeSavedInfo> >&SpillLabels =
276         XFI->getSpillLabels();
277     for (unsigned I = 0, E = SpillLabels.size(); I != E; ++I) {
278       MCSymbol *SpillLabel = SpillLabels[I].first;
279       CalleeSavedInfo &CSI = SpillLabels[I].second;
280       int Offset = MFI->getObjectOffset(CSI.getFrameIdx());
281       unsigned DRegNum = MRI->getDwarfRegNum(CSI.getReg(), true);
282       EmitCfiOffset(MBB, MBBI, dl, TII, MMI, DRegNum, Offset, SpillLabel);
283     }
284     if (XFI->hasEHSpillSlot()) {
285       // The unwinder requires stack slot & CFI offsets for the exception info.
286       // We do not save/spill these registers.
287       SmallVector<std::pair<int,unsigned>,2> SpillList;
288       GetEHSpillList(SpillList, MFI, XFI, MF.getTarget().getTargetLowering());
289       assert(SpillList.size()==2 && "Unexpected SpillList size");
290       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
291                     MRI->getDwarfRegNum(SpillList[0].second,true),
292                     SpillList[0].first, NULL);
293       EmitCfiOffset(MBB, MBBI, dl, TII, MMI,
294                     MRI->getDwarfRegNum(SpillList[1].second,true),
295                     SpillList[1].first, NULL);
296     }
297   }
298 }
299
300 void XCoreFrameLowering::emitEpilogue(MachineFunction &MF,
301                                      MachineBasicBlock &MBB) const {
302   MachineFrameInfo *MFI = MF.getFrameInfo();
303   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
304   const XCoreInstrInfo &TII =
305     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
306   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
307   DebugLoc dl = MBBI->getDebugLoc();
308   unsigned RetOpcode = MBBI->getOpcode();
309
310   // Work out frame sizes.
311   // We will adjust the SP in stages towards the final FrameSize.
312   int RemainingAdj = MFI->getStackSize();
313   assert(RemainingAdj%4 == 0 && "Misaligned frame size");
314   RemainingAdj /= 4;
315
316   if (RetOpcode == XCore::EH_RETURN) {
317     // 'Restore' the exception info the unwinder has placed into the stack slots.
318     SmallVector<std::pair<int,unsigned>,2> SpillList;
319     GetEHSpillList(SpillList, MFI, XFI, MF.getTarget().getTargetLowering());
320     RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
321
322     // Return to the landing pad.
323     unsigned EhStackReg = MBBI->getOperand(0).getReg();
324     unsigned EhHandlerReg = MBBI->getOperand(1).getReg();
325     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(EhStackReg);
326     BuildMI(MBB, MBBI, dl, TII.get(XCore::BAU_1r)).addReg(EhHandlerReg);
327     MBB.erase(MBBI);  // Erase the previous return instruction.
328     return;
329   }
330
331   bool restoreLR = XFI->hasLRSpillSlot();
332   bool UseRETSP = restoreLR && RemainingAdj
333                   && (MFI->getObjectOffset(XFI->getLRSpillSlot()) == 0);
334   if (UseRETSP)
335     restoreLR = false;
336   bool FP = hasFP(MF);
337
338   if (FP) // Restore the stack pointer.
339     BuildMI(MBB, MBBI, dl, TII.get(XCore::SETSP_1r)).addReg(FramePtr);
340
341   // If necessary, restore LR and FP from the stack, as we EXTSP.
342   SmallVector<std::pair<int,unsigned>,2> SpillList;
343   GetSpillList(SpillList, MFI, XFI, restoreLR, FP);
344   RestoreSpillList(MBB, MBBI, dl, TII, RemainingAdj, SpillList);
345
346   if (RemainingAdj) {
347     // Complete all but one of the remaining Stack adjustments.
348     IfNeededLDAWSP(MBB, MBBI, dl, TII, 0, RemainingAdj);
349     if (UseRETSP) {
350       // Fold prologue into return instruction
351       assert(RetOpcode == XCore::RETSP_u6
352              || RetOpcode == XCore::RETSP_lu6);
353       int Opcode = isImmU6(RemainingAdj) ? XCore::RETSP_u6 : XCore::RETSP_lu6;
354       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opcode))
355                                   .addImm(RemainingAdj);
356       for (unsigned i = 3, e = MBBI->getNumOperands(); i < e; ++i)
357         MIB->addOperand(MBBI->getOperand(i)); // copy any variadic operands
358       MBB.erase(MBBI);  // Erase the previous return instruction.
359     } else {
360       int Opcode = isImmU6(RemainingAdj) ? XCore::LDAWSP_ru6 :
361                                            XCore::LDAWSP_lru6;
362       BuildMI(MBB, MBBI, dl, TII.get(Opcode), XCore::SP).addImm(RemainingAdj);
363       // Don't erase the return instruction.
364     }
365   } // else Don't erase the return instruction.
366 }
367
368 bool XCoreFrameLowering::
369 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
370                           MachineBasicBlock::iterator MI,
371                           const std::vector<CalleeSavedInfo> &CSI,
372                           const TargetRegisterInfo *TRI) const {
373   if (CSI.empty())
374     return true;
375
376   MachineFunction *MF = MBB.getParent();
377   const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
378   XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
379   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
380
381   DebugLoc DL;
382   if (MI != MBB.end())
383     DL = MI->getDebugLoc();
384
385   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
386                                                     it != CSI.end(); ++it) {
387     unsigned Reg = it->getReg();
388     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
389            "LR & FP are always handled in emitPrologue");
390
391     // Add the callee-saved register as live-in. It's killed at the spill.
392     MBB.addLiveIn(Reg);
393     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
394     TII.storeRegToStackSlot(MBB, MI, Reg, true, it->getFrameIdx(), RC, TRI);
395     if (emitFrameMoves) {
396       MCSymbol *SaveLabel = MF->getContext().CreateTempSymbol();
397       BuildMI(MBB, MI, DL, TII.get(XCore::PROLOG_LABEL)).addSym(SaveLabel);
398       XFI->getSpillLabels().push_back(std::make_pair(SaveLabel, *it));
399     }
400   }
401   return true;
402 }
403
404 bool XCoreFrameLowering::
405 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
406                             MachineBasicBlock::iterator MI,
407                             const std::vector<CalleeSavedInfo> &CSI,
408                             const TargetRegisterInfo *TRI) const{
409   MachineFunction *MF = MBB.getParent();
410   const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
411   bool AtStart = MI == MBB.begin();
412   MachineBasicBlock::iterator BeforeI = MI;
413   if (!AtStart)
414     --BeforeI;
415   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
416                                                     it != CSI.end(); ++it) {
417     unsigned Reg = it->getReg();
418     assert(Reg != XCore::LR && !(Reg == XCore::R10 && hasFP(*MF)) &&
419            "LR & FP are always handled in emitEpilogue");
420
421     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
422     TII.loadRegFromStackSlot(MBB, MI, Reg, it->getFrameIdx(), RC, TRI);
423     assert(MI != MBB.begin() &&
424            "loadRegFromStackSlot didn't insert any code!");
425     // Insert in reverse order.  loadRegFromStackSlot can insert multiple
426     // instructions.
427     if (AtStart)
428       MI = MBB.begin();
429     else {
430       MI = BeforeI;
431       ++MI;
432     }
433   }
434   return true;
435 }
436
437 // This function eliminates ADJCALLSTACKDOWN,
438 // ADJCALLSTACKUP pseudo instructions
439 void XCoreFrameLowering::
440 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
441                               MachineBasicBlock::iterator I) const {
442   const XCoreInstrInfo &TII =
443     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
444   if (!hasReservedCallFrame(MF)) {
445     // Turn the adjcallstackdown instruction into 'extsp <amt>' and the
446     // adjcallstackup instruction into 'ldaw sp, sp[<amt>]'
447     MachineInstr *Old = I;
448     uint64_t Amount = Old->getOperand(0).getImm();
449     if (Amount != 0) {
450       // We need to keep the stack aligned properly.  To do this, we round the
451       // amount of space needed for the outgoing arguments up to the next
452       // alignment boundary.
453       unsigned Align = getStackAlignment();
454       Amount = (Amount+Align-1)/Align*Align;
455
456       assert(Amount%4 == 0);
457       Amount /= 4;
458
459       bool isU6 = isImmU6(Amount);
460       if (!isU6 && !isImmU16(Amount)) {
461         // FIX could emit multiple instructions in this case.
462 #ifndef NDEBUG
463         errs() << "eliminateCallFramePseudoInstr size too big: "
464                << Amount << "\n";
465 #endif
466         llvm_unreachable(0);
467       }
468
469       MachineInstr *New;
470       if (Old->getOpcode() == XCore::ADJCALLSTACKDOWN) {
471         int Opcode = isU6 ? XCore::EXTSP_u6 : XCore::EXTSP_lu6;
472         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode))
473           .addImm(Amount);
474       } else {
475         assert(Old->getOpcode() == XCore::ADJCALLSTACKUP);
476         int Opcode = isU6 ? XCore::LDAWSP_ru6 : XCore::LDAWSP_lru6;
477         New=BuildMI(MF, Old->getDebugLoc(), TII.get(Opcode), XCore::SP)
478           .addImm(Amount);
479       }
480
481       // Replace the pseudo instruction with a new instruction...
482       MBB.insert(I, New);
483     }
484   }
485   
486   MBB.erase(I);
487 }
488
489 void XCoreFrameLowering::
490 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
491                                      RegScavenger *RS) const {
492   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
493
494   bool LRUsed = MF.getRegInfo().isPhysRegUsed(XCore::LR);
495
496   if (!LRUsed && !MF.getFunction()->isVarArg() &&
497       MF.getFrameInfo()->estimateStackSize(MF))
498     // If we need to extend the stack it is more efficient to use entsp / retsp.
499     // We force the LR to be saved so these instructions are used.
500     LRUsed = true;
501
502   if (MF.getMMI().callsUnwindInit() || MF.getMMI().callsEHReturn()) {
503     // The unwinder expects to find spill slots for the exception info regs R0
504     // & R1. These are used during llvm.eh.return() to 'restore' the exception
505     // info. N.B. we do not spill or restore R0, R1 during normal operation.
506     XFI->createEHSpillSlot(MF);
507     // As we will  have a stack, we force the LR to be saved.
508     LRUsed = true;
509   }
510
511   if (LRUsed) {
512     // We will handle the LR in the prologue/epilogue
513     // and allocate space on the stack ourselves.
514     MF.getRegInfo().setPhysRegUnused(XCore::LR);
515     XFI->createLRSpillSlot(MF);
516   }
517
518   if (hasFP(MF))
519     // A callee save register is used to hold the FP.
520     // This needs saving / restoring in the epilogue / prologue.
521     XFI->createFPSpillSlot(MF);
522 }
523
524 void XCoreFrameLowering::
525 processFunctionBeforeFrameFinalized(MachineFunction &MF,
526                                     RegScavenger *RS) const {
527   assert(RS && "requiresRegisterScavenging failed");
528   MachineFrameInfo *MFI = MF.getFrameInfo();
529   const TargetRegisterClass *RC = &XCore::GRRegsRegClass;
530   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
531   // Reserve slots close to SP or frame pointer for Scavenging spills.
532   // When using SP for small frames, we don't need any scratch registers.
533   // When using SP for large frames, we may need 2 scratch registers.
534   // When using FP, for large or small frames, we may need 1 scratch register.
535   if (XFI->isLargeFrame(MF) || hasFP(MF))
536     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
537                                                        RC->getAlignment(),
538                                                        false));
539   if (XFI->isLargeFrame(MF) && !hasFP(MF))
540     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
541                                                        RC->getAlignment(),
542                                                        false));
543 }