Add parameter to getDwarfRegNum to permit targets
[oota-llvm.git] / lib / Target / ARM / ARMRegisterInfo.cpp
1 //===- ARMRegisterInfo.cpp - ARM Register Information -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the "Instituto Nokia de Tecnologia" and
6 // is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains the ARM implementation of the MRegisterInfo class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMInstrInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineLocation.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 static cl::opt<bool> ThumbRegScavenging("enable-thumb-reg-scavenging",
40                                cl::Hidden,
41                                cl::desc("Enable register scavenging on Thumb"));
42
43 unsigned ARMRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
44   using namespace ARM;
45   switch (RegEnum) {
46   case R0:  case S0:  case D0:  return 0;
47   case R1:  case S1:  case D1:  return 1;
48   case R2:  case S2:  case D2:  return 2;
49   case R3:  case S3:  case D3:  return 3;
50   case R4:  case S4:  case D4:  return 4;
51   case R5:  case S5:  case D5:  return 5;
52   case R6:  case S6:  case D6:  return 6;
53   case R7:  case S7:  case D7:  return 7;
54   case R8:  case S8:  case D8:  return 8;
55   case R9:  case S9:  case D9:  return 9;
56   case R10: case S10: case D10: return 10;
57   case R11: case S11: case D11: return 11;
58   case R12: case S12: case D12: return 12;
59   case SP:  case S13: case D13: return 13;
60   case LR:  case S14: case D14: return 14;
61   case PC:  case S15: case D15: return 15;
62   case S16: return 16;
63   case S17: return 17;
64   case S18: return 18;
65   case S19: return 19;
66   case S20: return 20;
67   case S21: return 21;
68   case S22: return 22;
69   case S23: return 23;
70   case S24: return 24;
71   case S25: return 25;
72   case S26: return 26;
73   case S27: return 27;
74   case S28: return 28;
75   case S29: return 29;
76   case S30: return 30;
77   case S31: return 31;
78   default:
79     assert(0 && "Unknown ARM register!");
80     abort();
81   }
82 }
83
84 ARMRegisterInfo::ARMRegisterInfo(const TargetInstrInfo &tii,
85                                  const ARMSubtarget &sti)
86   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
87     TII(tii), STI(sti),
88     FramePtr((STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
89 }
90
91 bool ARMRegisterInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
92                                                 MachineBasicBlock::iterator MI,
93                                 const std::vector<CalleeSavedInfo> &CSI) const {
94   MachineFunction &MF = *MBB.getParent();
95   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
96   if (!AFI->isThumbFunction() || CSI.empty())
97     return false;
98
99   MachineInstrBuilder MIB = BuildMI(MBB, MI, TII.get(ARM::tPUSH));
100   for (unsigned i = CSI.size(); i != 0; --i) {
101     unsigned Reg = CSI[i-1].getReg();
102     // Add the callee-saved register as live-in. It's killed at the spill.
103     MBB.addLiveIn(Reg);
104     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
105   }
106   return true;
107 }
108
109 bool ARMRegisterInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
110                                                  MachineBasicBlock::iterator MI,
111                                 const std::vector<CalleeSavedInfo> &CSI) const {
112   MachineFunction &MF = *MBB.getParent();
113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
114   if (!AFI->isThumbFunction() || CSI.empty())
115     return false;
116
117   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
118   MachineInstr *PopMI = new MachineInstr(TII.get(ARM::tPOP));
119   MBB.insert(MI, PopMI);
120   for (unsigned i = CSI.size(); i != 0; --i) {
121     unsigned Reg = CSI[i-1].getReg();
122     if (Reg == ARM::LR) {
123       // Special epilogue for vararg functions. See emitEpilogue
124       if (isVarArg)
125         continue;
126       Reg = ARM::PC;
127       PopMI->setInstrDescriptor(TII.get(ARM::tPOP_RET));
128       MBB.erase(MI);
129     }
130     PopMI->addRegOperand(Reg, true);
131   }
132   return true;
133 }
134
135 static inline
136 const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
137   return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
138 }
139
140 static inline
141 const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
142   return MIB.addReg(0);
143 }
144
145 static const MachineInstrBuilder &ARMInstrAddOperand(MachineInstrBuilder &MIB,
146                                                      MachineOperand &MO) {
147   if (MO.isRegister())
148     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit());
149   else if (MO.isImmediate())
150     MIB = MIB.addImm(MO.getImm());
151   else if (MO.isFrameIndex())
152     MIB = MIB.addFrameIndex(MO.getFrameIndex());
153   else
154     assert(0 && "Unknown operand for ARMInstrAddOperand!");
155
156   return MIB;
157 }
158
159 void ARMRegisterInfo::
160 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
161                     unsigned SrcReg, int FI,
162                     const TargetRegisterClass *RC) const {
163   if (RC == ARM::GPRRegisterClass) {
164     MachineFunction &MF = *MBB.getParent();
165     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
166     if (AFI->isThumbFunction())
167       BuildMI(MBB, I, TII.get(ARM::tSpill)).addReg(SrcReg, false, false, true)
168         .addFrameIndex(FI).addImm(0);
169     else
170       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::STR))
171                      .addReg(SrcReg, false, false, true)
172                      .addFrameIndex(FI).addReg(0).addImm(0));
173   } else if (RC == ARM::DPRRegisterClass) {
174     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTD))
175                    .addReg(SrcReg, false, false, true)
176                    .addFrameIndex(FI).addImm(0));
177   } else {
178     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
179     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTS))
180                    .addReg(SrcReg, false, false, true)
181                    .addFrameIndex(FI).addImm(0));
182   }
183 }
184
185 void ARMRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
186                                      SmallVectorImpl<MachineOperand> &Addr,
187                                      const TargetRegisterClass *RC,
188                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
189   unsigned Opc = 0;
190   if (RC == ARM::GPRRegisterClass) {
191     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
192     if (AFI->isThumbFunction()) {
193       Opc = Addr[0].isFrameIndex() ? ARM::tSpill : ARM::tSTR;
194       MachineInstrBuilder MIB = 
195         BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, true);
196       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
197         MIB = ARMInstrAddOperand(MIB, Addr[i]);
198       NewMIs.push_back(MIB);
199       return;
200     }
201     Opc = ARM::STR;
202   } else if (RC == ARM::DPRRegisterClass) {
203     Opc = ARM::FSTD;
204   } else {
205     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
206     Opc = ARM::FSTS;
207   }
208
209   MachineInstrBuilder MIB = 
210     BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, true);
211   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
212     MIB = ARMInstrAddOperand(MIB, Addr[i]);
213   AddDefaultPred(MIB);
214   NewMIs.push_back(MIB);
215   return;
216 }
217
218 void ARMRegisterInfo::
219 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
220                      unsigned DestReg, int FI,
221                      const TargetRegisterClass *RC) const {
222   if (RC == ARM::GPRRegisterClass) {
223     MachineFunction &MF = *MBB.getParent();
224     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
225     if (AFI->isThumbFunction())
226       BuildMI(MBB, I, TII.get(ARM::tRestore), DestReg)
227         .addFrameIndex(FI).addImm(0);
228     else
229       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::LDR), DestReg)
230                      .addFrameIndex(FI).addReg(0).addImm(0));
231   } else if (RC == ARM::DPRRegisterClass) {
232     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDD), DestReg)
233                    .addFrameIndex(FI).addImm(0));
234   } else {
235     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
236     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDS), DestReg)
237                    .addFrameIndex(FI).addImm(0));
238   }
239 }
240
241 void ARMRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
242                                       SmallVectorImpl<MachineOperand> &Addr,
243                                       const TargetRegisterClass *RC,
244                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
245   unsigned Opc = 0;
246   if (RC == ARM::GPRRegisterClass) {
247     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
248     if (AFI->isThumbFunction()) {
249       Opc = Addr[0].isFrameIndex() ? ARM::tRestore : ARM::tLDR;
250       MachineInstrBuilder MIB = BuildMI(TII.get(Opc), DestReg);
251       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
252         MIB = ARMInstrAddOperand(MIB, Addr[i]);
253       NewMIs.push_back(MIB);
254       return;
255     }
256     Opc = ARM::LDR;
257   } else if (RC == ARM::DPRRegisterClass) {
258     Opc = ARM::FLDD;
259   } else {
260     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
261     Opc = ARM::FLDS;
262   }
263
264   MachineInstrBuilder MIB =  BuildMI(TII.get(Opc), DestReg);
265   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
266     MIB = ARMInstrAddOperand(MIB, Addr[i]);
267   AddDefaultPred(MIB);
268   NewMIs.push_back(MIB);
269   return;
270 }
271
272 void ARMRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
273                                    MachineBasicBlock::iterator I,
274                                    unsigned DestReg, unsigned SrcReg,
275                                    const TargetRegisterClass *DestRC,
276                                    const TargetRegisterClass *SrcRC) const {
277   if (DestRC != SrcRC) {
278     cerr << "Not yet supported!";
279     abort();
280   }
281
282   if (DestRC == ARM::GPRRegisterClass) {
283     MachineFunction &MF = *MBB.getParent();
284     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
285     if (AFI->isThumbFunction())
286       BuildMI(MBB, I, TII.get(ARM::tMOVr), DestReg).addReg(SrcReg);
287     else
288       AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::MOVr), DestReg)
289                                   .addReg(SrcReg)));
290   } else if (DestRC == ARM::SPRRegisterClass)
291     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FCPYS), DestReg)
292                    .addReg(SrcReg));
293   else if (DestRC == ARM::DPRRegisterClass)
294     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FCPYD), DestReg)
295                    .addReg(SrcReg));
296   else
297     abort();
298 }
299
300 /// emitLoadConstPool - Emits a load from constpool to materialize the
301 /// specified immediate.
302 static void emitLoadConstPool(MachineBasicBlock &MBB,
303                               MachineBasicBlock::iterator &MBBI,
304                               unsigned DestReg, int Val,
305                               ARMCC::CondCodes Pred, unsigned PredReg,
306                               const TargetInstrInfo &TII, bool isThumb) {
307   MachineFunction &MF = *MBB.getParent();
308   MachineConstantPool *ConstantPool = MF.getConstantPool();
309   Constant *C = ConstantInt::get(Type::Int32Ty, Val);
310   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 2);
311   if (isThumb)
312     BuildMI(MBB, MBBI, TII.get(ARM::tLDRcp), DestReg).addConstantPoolIndex(Idx);
313   else
314     BuildMI(MBB, MBBI, TII.get(ARM::LDRcp), DestReg).addConstantPoolIndex(Idx)
315       .addReg(0).addImm(0).addImm((unsigned)Pred).addReg(PredReg);
316 }
317
318 void ARMRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
319                                     MachineBasicBlock::iterator I,
320                                     unsigned DestReg,
321                                     const MachineInstr *Orig) const {
322   if (Orig->getOpcode() == ARM::MOVi2pieces) {
323     emitLoadConstPool(MBB, I, DestReg,
324                       Orig->getOperand(1).getImmedValue(),
325                       (ARMCC::CondCodes)Orig->getOperand(2).getImmedValue(),
326                       Orig->getOperand(3).getReg(),
327                       TII, false);
328     return;
329   }
330
331   MachineInstr *MI = Orig->clone();
332   MI->getOperand(0).setReg(DestReg);
333   MBB.insert(I, MI);
334 }
335
336 /// isLowRegister - Returns true if the register is low register r0-r7.
337 ///
338 static bool isLowRegister(unsigned Reg) {
339   using namespace ARM;
340   switch (Reg) {
341   case R0:  case R1:  case R2:  case R3:
342   case R4:  case R5:  case R6:  case R7:
343     return true;
344   default:
345     return false;
346   }
347 }
348
349 MachineInstr *ARMRegisterInfo::foldMemoryOperand(MachineInstr *MI,
350                                                  unsigned OpNum, int FI) const {
351   unsigned Opc = MI->getOpcode();
352   MachineInstr *NewMI = NULL;
353   switch (Opc) {
354   default: break;
355   case ARM::MOVr: {
356     if (MI->getOperand(4).getReg() == ARM::CPSR)
357       // If it is updating CPSR, then it cannot be foled.
358       break;
359     unsigned Pred = MI->getOperand(2).getImmedValue();
360     unsigned PredReg = MI->getOperand(3).getReg();
361     if (OpNum == 0) { // move -> store
362       unsigned SrcReg = MI->getOperand(1).getReg();
363       NewMI = BuildMI(TII.get(ARM::STR)).addReg(SrcReg).addFrameIndex(FI)
364         .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
365     } else {          // move -> load
366       unsigned DstReg = MI->getOperand(0).getReg();
367       NewMI = BuildMI(TII.get(ARM::LDR), DstReg).addFrameIndex(FI).addReg(0)
368         .addImm(0).addImm(Pred).addReg(PredReg);
369     }
370     break;
371   }
372   case ARM::tMOVr: {
373     if (OpNum == 0) { // move -> store
374       unsigned SrcReg = MI->getOperand(1).getReg();
375       if (isPhysicalRegister(SrcReg) && !isLowRegister(SrcReg))
376         // tSpill cannot take a high register operand.
377         break;
378       NewMI = BuildMI(TII.get(ARM::tSpill)).addReg(SrcReg).addFrameIndex(FI)
379         .addImm(0);
380     } else {          // move -> load
381       unsigned DstReg = MI->getOperand(0).getReg();
382       if (isPhysicalRegister(DstReg) && !isLowRegister(DstReg))
383         // tRestore cannot target a high register operand.
384         break;
385       NewMI = BuildMI(TII.get(ARM::tRestore), DstReg).addFrameIndex(FI)
386         .addImm(0);
387     }
388     break;
389   }
390   case ARM::FCPYS: {
391     unsigned Pred = MI->getOperand(2).getImmedValue();
392     unsigned PredReg = MI->getOperand(3).getReg();
393     if (OpNum == 0) { // move -> store
394       unsigned SrcReg = MI->getOperand(1).getReg();
395       NewMI = BuildMI(TII.get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
396         .addImm(0).addImm(Pred).addReg(PredReg);
397     } else {          // move -> load
398       unsigned DstReg = MI->getOperand(0).getReg();
399       NewMI = BuildMI(TII.get(ARM::FLDS), DstReg).addFrameIndex(FI)
400         .addImm(0).addImm(Pred).addReg(PredReg);
401     }
402     break;
403   }
404   case ARM::FCPYD: {
405     unsigned Pred = MI->getOperand(2).getImmedValue();
406     unsigned PredReg = MI->getOperand(3).getReg();
407     if (OpNum == 0) { // move -> store
408       unsigned SrcReg = MI->getOperand(1).getReg();
409       NewMI = BuildMI(TII.get(ARM::FSTD)).addReg(SrcReg).addFrameIndex(FI)
410         .addImm(0).addImm(Pred).addReg(PredReg);
411     } else {          // move -> load
412       unsigned DstReg = MI->getOperand(0).getReg();
413       NewMI = BuildMI(TII.get(ARM::FLDD), DstReg).addFrameIndex(FI)
414         .addImm(0).addImm(Pred).addReg(PredReg);
415     }
416     break;
417   }
418   }
419
420   if (NewMI)
421     NewMI->copyKillDeadInfo(MI);
422   return NewMI;
423 }
424
425 const unsigned*
426 ARMRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
427   static const unsigned CalleeSavedRegs[] = {
428     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
429     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
430
431     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
432     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
433     0
434   };
435
436   static const unsigned DarwinCalleeSavedRegs[] = {
437     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
438     ARM::R11, ARM::R10, ARM::R9, ARM::R8,
439
440     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
441     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
442     0
443   };
444   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
445 }
446
447 const TargetRegisterClass* const *
448 ARMRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
449   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
450     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
451     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
452     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
453
454     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
455     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
456     0
457   };
458   return CalleeSavedRegClasses;
459 }
460
461 BitVector ARMRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
462   // FIXME: avoid re-calculating this everytime.
463   BitVector Reserved(getNumRegs());
464   Reserved.set(ARM::SP);
465   Reserved.set(ARM::PC);
466   if (STI.isTargetDarwin() || hasFP(MF))
467     Reserved.set(FramePtr);
468   // Some targets reserve R9.
469   if (STI.isR9Reserved())
470     Reserved.set(ARM::R9);
471   return Reserved;
472 }
473
474 bool
475 ARMRegisterInfo::isReservedReg(const MachineFunction &MF, unsigned Reg) const {
476   switch (Reg) {
477   default: break;
478   case ARM::SP:
479   case ARM::PC:
480     return true;
481   case ARM::R7:
482   case ARM::R11:
483     if (FramePtr == Reg && (STI.isTargetDarwin() || hasFP(MF)))
484       return true;
485     break;
486   case ARM::R9:
487     return STI.isR9Reserved();
488   }
489
490   return false;
491 }
492
493 bool
494 ARMRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
495   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
496   return ThumbRegScavenging || !AFI->isThumbFunction();
497 }
498
499 /// hasFP - Return true if the specified function should have a dedicated frame
500 /// pointer register.  This is true if the function has variable sized allocas
501 /// or if frame pointer elimination is disabled.
502 ///
503 bool ARMRegisterInfo::hasFP(const MachineFunction &MF) const {
504   return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
505 }
506
507 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
508 // not required, we reserve argument space for call sites in the function
509 // immediately on entry to the current function. This eliminates the need for
510 // add/sub sp brackets around call sites. Returns true if the call frame is
511 // included as part of the stack frame.
512 bool ARMRegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
513   const MachineFrameInfo *FFI = MF.getFrameInfo();
514   unsigned CFSize = FFI->getMaxCallFrameSize();
515   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
516   // It's not always a good idea to include the call frame as part of the
517   // stack frame. ARM (especially Thumb) has small immediate offset to
518   // address the stack frame. So a large call frame can cause poor codegen
519   // and may even makes it impossible to scavenge a register.
520   if (AFI->isThumbFunction()) {
521     if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
522       return false;
523   } else {
524     if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
525       return false;
526   }
527   return !MF.getFrameInfo()->hasVarSizedObjects();
528 }
529
530 /// emitARMRegPlusImmediate - Emits a series of instructions to materialize
531 /// a destreg = basereg + immediate in ARM code.
532 static
533 void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
534                              MachineBasicBlock::iterator &MBBI,
535                              unsigned DestReg, unsigned BaseReg, int NumBytes,
536                              ARMCC::CondCodes Pred, unsigned PredReg,
537                              const TargetInstrInfo &TII) {
538   bool isSub = NumBytes < 0;
539   if (isSub) NumBytes = -NumBytes;
540
541   while (NumBytes) {
542     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
543     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
544     assert(ThisVal && "Didn't extract field correctly");
545     
546     // We will handle these bits from offset, clear them.
547     NumBytes &= ~ThisVal;
548     
549     // Get the properly encoded SOImmVal field.
550     int SOImmVal = ARM_AM::getSOImmVal(ThisVal);
551     assert(SOImmVal != -1 && "Bit extraction didn't work?");
552     
553     // Build the new ADD / SUB.
554     BuildMI(MBB, MBBI, TII.get(isSub ? ARM::SUBri : ARM::ADDri), DestReg)
555       .addReg(BaseReg, false, false, true).addImm(SOImmVal)
556       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
557     BaseReg = DestReg;
558   }
559 }
560
561 /// calcNumMI - Returns the number of instructions required to materialize
562 /// the specific add / sub r, c instruction.
563 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
564                           unsigned NumBits, unsigned Scale) {
565   unsigned NumMIs = 0;
566   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
567
568   if (Opc == ARM::tADDrSPi) {
569     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
570     Bytes -= ThisVal;
571     NumMIs++;
572     NumBits = 8;
573     Scale = 1;  // Followed by a number of tADDi8.
574     Chunk = ((1 << NumBits) - 1) * Scale;
575   }
576
577   NumMIs += Bytes / Chunk;
578   if ((Bytes % Chunk) != 0)
579     NumMIs++;
580   if (ExtraOpc)
581     NumMIs++;
582   return NumMIs;
583 }
584
585 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
586 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
587 /// in a register using mov / mvn sequences or load the immediate from a
588 /// constpool entry.
589 static
590 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
591                                MachineBasicBlock::iterator &MBBI,
592                                unsigned DestReg, unsigned BaseReg,
593                                int NumBytes, bool CanChangeCC,
594                                const TargetInstrInfo &TII) {
595     bool isHigh = !isLowRegister(DestReg) ||
596                   (BaseReg != 0 && !isLowRegister(BaseReg));
597     bool isSub = false;
598     // Subtract doesn't have high register version. Load the negative value
599     // if either base or dest register is a high register. Also, if do not
600     // issue sub as part of the sequence if condition register is to be
601     // preserved.
602     if (NumBytes < 0 && !isHigh && CanChangeCC) {
603       isSub = true;
604       NumBytes = -NumBytes;
605     }
606     unsigned LdReg = DestReg;
607     if (DestReg == ARM::SP) {
608       assert(BaseReg == ARM::SP && "Unexpected!");
609       LdReg = ARM::R3;
610       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R12)
611         .addReg(ARM::R3, false, false, true);
612     }
613
614     if (NumBytes <= 255 && NumBytes >= 0)
615       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
616     else if (NumBytes < 0 && NumBytes >= -255) {
617       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
618       BuildMI(MBB, MBBI, TII.get(ARM::tNEG), LdReg)
619         .addReg(LdReg, false, false, true);
620     } else
621       emitLoadConstPool(MBB, MBBI, LdReg, NumBytes, ARMCC::AL, 0, TII, true);
622
623     // Emit add / sub.
624     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
625     const MachineInstrBuilder MIB = BuildMI(MBB, MBBI, TII.get(Opc), DestReg);
626     if (DestReg == ARM::SP || isSub)
627       MIB.addReg(BaseReg).addReg(LdReg, false, false, true);
628     else
629       MIB.addReg(LdReg).addReg(BaseReg, false, false, true);
630     if (DestReg == ARM::SP)
631       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R3)
632         .addReg(ARM::R12, false, false, true);
633 }
634
635 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
636 /// a destreg = basereg + immediate in Thumb code.
637 static
638 void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
639                                MachineBasicBlock::iterator &MBBI,
640                                unsigned DestReg, unsigned BaseReg,
641                                int NumBytes, const TargetInstrInfo &TII) {
642   bool isSub = NumBytes < 0;
643   unsigned Bytes = (unsigned)NumBytes;
644   if (isSub) Bytes = -NumBytes;
645   bool isMul4 = (Bytes & 3) == 0;
646   bool isTwoAddr = false;
647   bool DstNotEqBase = false;
648   unsigned NumBits = 1;
649   unsigned Scale = 1;
650   int Opc = 0;
651   int ExtraOpc = 0;
652
653   if (DestReg == BaseReg && BaseReg == ARM::SP) {
654     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
655     NumBits = 7;
656     Scale = 4;
657     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
658     isTwoAddr = true;
659   } else if (!isSub && BaseReg == ARM::SP) {
660     // r1 = add sp, 403
661     // =>
662     // r1 = add sp, 100 * 4
663     // r1 = add r1, 3
664     if (!isMul4) {
665       Bytes &= ~3;
666       ExtraOpc = ARM::tADDi3;
667     }
668     NumBits = 8;
669     Scale = 4;
670     Opc = ARM::tADDrSPi;
671   } else {
672     // sp = sub sp, c
673     // r1 = sub sp, c
674     // r8 = sub sp, c
675     if (DestReg != BaseReg)
676       DstNotEqBase = true;
677     NumBits = 8;
678     Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
679     isTwoAddr = true;
680   }
681
682   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
683   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
684   if (NumMIs > Threshold) {
685     // This will expand into too many instructions. Load the immediate from a
686     // constpool entry.
687     emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII);
688     return;
689   }
690
691   if (DstNotEqBase) {
692     if (isLowRegister(DestReg) && isLowRegister(BaseReg)) {
693       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
694       unsigned Chunk = (1 << 3) - 1;
695       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
696       Bytes -= ThisVal;
697       BuildMI(MBB, MBBI, TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3), DestReg)
698         .addReg(BaseReg, false, false, true).addImm(ThisVal);
699     } else {
700       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), DestReg)
701         .addReg(BaseReg, false, false, true);
702     }
703     BaseReg = DestReg;
704   }
705
706   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
707   while (Bytes) {
708     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
709     Bytes -= ThisVal;
710     ThisVal /= Scale;
711     // Build the new tADD / tSUB.
712     if (isTwoAddr)
713       BuildMI(MBB, MBBI, TII.get(Opc), DestReg).addReg(DestReg).addImm(ThisVal);
714     else {
715       bool isKill = BaseReg != ARM::SP;
716       BuildMI(MBB, MBBI, TII.get(Opc), DestReg)
717         .addReg(BaseReg, false, false, isKill).addImm(ThisVal);
718       BaseReg = DestReg;
719
720       if (Opc == ARM::tADDrSPi) {
721         // r4 = add sp, imm
722         // r4 = add r4, imm
723         // ...
724         NumBits = 8;
725         Scale = 1;
726         Chunk = ((1 << NumBits) - 1) * Scale;
727         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
728         isTwoAddr = true;
729       }
730     }
731   }
732
733   if (ExtraOpc)
734     BuildMI(MBB, MBBI, TII.get(ExtraOpc), DestReg)
735       .addReg(DestReg, false, false, true)
736       .addImm(((unsigned)NumBytes) & 3);
737 }
738
739 static
740 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
741                   int NumBytes, ARMCC::CondCodes Pred, unsigned PredReg,
742                   bool isThumb, const TargetInstrInfo &TII) {
743   if (isThumb)
744     emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII);
745   else
746     emitARMRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes,
747                             Pred, PredReg, TII);
748 }
749
750 void ARMRegisterInfo::
751 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
752                               MachineBasicBlock::iterator I) const {
753   if (!hasReservedCallFrame(MF)) {
754     // If we have alloca, convert as follows:
755     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
756     // ADJCALLSTACKUP   -> add, sp, sp, amount
757     MachineInstr *Old = I;
758     unsigned Amount = Old->getOperand(0).getImmedValue();
759     if (Amount != 0) {
760       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
761       // We need to keep the stack aligned properly.  To do this, we round the
762       // amount of space needed for the outgoing arguments up to the next
763       // alignment boundary.
764       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
765       Amount = (Amount+Align-1)/Align*Align;
766
767       // Replace the pseudo instruction with a new instruction...
768       unsigned Opc = Old->getOpcode();
769       bool isThumb = AFI->isThumbFunction();
770       ARMCC::CondCodes Pred = isThumb
771         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(1).getImmedValue();
772       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
773         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
774         unsigned PredReg = isThumb ? 0 : Old->getOperand(2).getReg();
775         emitSPUpdate(MBB, I, -Amount, Pred, PredReg, isThumb, TII);
776       } else {
777         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
778         unsigned PredReg = isThumb ? 0 : Old->getOperand(3).getReg();
779         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
780         emitSPUpdate(MBB, I, Amount, Pred, PredReg, isThumb, TII);
781       }
782     }
783   }
784   MBB.erase(I);
785 }
786
787 /// emitThumbConstant - Emit a series of instructions to materialize a
788 /// constant.
789 static void emitThumbConstant(MachineBasicBlock &MBB,
790                               MachineBasicBlock::iterator &MBBI,
791                               unsigned DestReg, int Imm,
792                               const TargetInstrInfo &TII) {
793   bool isSub = Imm < 0;
794   if (isSub) Imm = -Imm;
795
796   int Chunk = (1 << 8) - 1;
797   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
798   Imm -= ThisVal;
799   BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), DestReg).addImm(ThisVal);
800   if (Imm > 0) 
801     emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII);
802   if (isSub)
803     BuildMI(MBB, MBBI, TII.get(ARM::tNEG), DestReg)
804       .addReg(DestReg, false, false, true);
805 }
806
807 /// findScratchRegister - Find a 'free' ARM register. If register scavenger
808 /// is not being used, R12 is available. Otherwise, try for a call-clobbered
809 /// register first and then a spilled callee-saved register if that fails.
810 static
811 unsigned findScratchRegister(RegScavenger *RS, const TargetRegisterClass *RC,
812                              ARMFunctionInfo *AFI) {
813   unsigned Reg = RS ? RS->FindUnusedReg(RC, true) : (unsigned) ARM::R12;
814   if (Reg == 0)
815     // Try a already spilled CS register.
816     Reg = RS->FindUnusedReg(RC, AFI->getSpilledCSRegisters());
817
818   return Reg;
819 }
820
821 void ARMRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
822                                           int SPAdj, RegScavenger *RS) const{
823   unsigned i = 0;
824   MachineInstr &MI = *II;
825   MachineBasicBlock &MBB = *MI.getParent();
826   MachineFunction &MF = *MBB.getParent();
827   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
828   bool isThumb = AFI->isThumbFunction();
829
830   while (!MI.getOperand(i).isFrameIndex()) {
831     ++i;
832     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
833   }
834   
835   unsigned FrameReg = ARM::SP;
836   int FrameIndex = MI.getOperand(i).getFrameIndex();
837   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) + 
838                MF.getFrameInfo()->getStackSize() + SPAdj;
839
840   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
841     Offset -= AFI->getGPRCalleeSavedArea1Offset();
842   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
843     Offset -= AFI->getGPRCalleeSavedArea2Offset();
844   else if (AFI->isDPRCalleeSavedAreaFrame(FrameIndex))
845     Offset -= AFI->getDPRCalleeSavedAreaOffset();
846   else if (hasFP(MF)) {
847     assert(SPAdj == 0 && "Unexpected");
848     // There is alloca()'s in this function, must reference off the frame
849     // pointer instead.
850     FrameReg = getFrameRegister(MF);
851     Offset -= AFI->getFramePtrSpillOffset();
852   }
853
854   unsigned Opcode = MI.getOpcode();
855   const TargetInstrDescriptor &Desc = TII.get(Opcode);
856   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
857   bool isSub = false;
858
859   if (Opcode == ARM::ADDri) {
860     Offset += MI.getOperand(i+1).getImm();
861     if (Offset == 0) {
862       // Turn it into a move.
863       MI.setInstrDescriptor(TII.get(ARM::MOVr));
864       MI.getOperand(i).ChangeToRegister(FrameReg, false);
865       MI.RemoveOperand(i+1);
866       return;
867     } else if (Offset < 0) {
868       Offset = -Offset;
869       isSub = true;
870       MI.setInstrDescriptor(TII.get(ARM::SUBri));
871     }
872
873     // Common case: small offset, fits into instruction.
874     int ImmedOffset = ARM_AM::getSOImmVal(Offset);
875     if (ImmedOffset != -1) {
876       // Replace the FrameIndex with sp / fp
877       MI.getOperand(i).ChangeToRegister(FrameReg, false);
878       MI.getOperand(i+1).ChangeToImmediate(ImmedOffset);
879       return;
880     }
881     
882     // Otherwise, we fallback to common code below to form the imm offset with
883     // a sequence of ADDri instructions.  First though, pull as much of the imm
884     // into this ADDri as possible.
885     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
886     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
887     
888     // We will handle these bits from offset, clear them.
889     Offset &= ~ThisImmVal;
890     
891     // Get the properly encoded SOImmVal field.
892     int ThisSOImmVal = ARM_AM::getSOImmVal(ThisImmVal);
893     assert(ThisSOImmVal != -1 && "Bit extraction didn't work?");    
894     MI.getOperand(i+1).ChangeToImmediate(ThisSOImmVal);
895   } else if (Opcode == ARM::tADDrSPi) {
896     Offset += MI.getOperand(i+1).getImm();
897
898     // Can't use tADDrSPi if it's based off the frame pointer.
899     unsigned NumBits = 0;
900     unsigned Scale = 1;
901     if (FrameReg != ARM::SP) {
902       Opcode = ARM::tADDi3;
903       MI.setInstrDescriptor(TII.get(ARM::tADDi3));
904       NumBits = 3;
905     } else {
906       NumBits = 8;
907       Scale = 4;
908       assert((Offset & 3) == 0 &&
909              "Thumb add/sub sp, #imm immediate must be multiple of 4!");
910     }
911
912     if (Offset == 0) {
913       // Turn it into a move.
914       MI.setInstrDescriptor(TII.get(ARM::tMOVr));
915       MI.getOperand(i).ChangeToRegister(FrameReg, false);
916       MI.RemoveOperand(i+1);
917       return;
918     }
919
920     // Common case: small offset, fits into instruction.
921     unsigned Mask = (1 << NumBits) - 1;
922     if (((Offset / Scale) & ~Mask) == 0) {
923       // Replace the FrameIndex with sp / fp
924       MI.getOperand(i).ChangeToRegister(FrameReg, false);
925       MI.getOperand(i+1).ChangeToImmediate(Offset / Scale);
926       return;
927     }
928
929     unsigned DestReg = MI.getOperand(0).getReg();
930     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
931     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
932     // MI would expand into a large number of instructions. Don't try to
933     // simplify the immediate.
934     if (NumMIs > 2) {
935       emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII);
936       MBB.erase(II);
937       return;
938     }
939
940     if (Offset > 0) {
941       // Translate r0 = add sp, imm to
942       // r0 = add sp, 255*4
943       // r0 = add r0, (imm - 255*4)
944       MI.getOperand(i).ChangeToRegister(FrameReg, false);
945       MI.getOperand(i+1).ChangeToImmediate(Mask);
946       Offset = (Offset - Mask * Scale);
947       MachineBasicBlock::iterator NII = next(II);
948       emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII);
949     } else {
950       // Translate r0 = add sp, -imm to
951       // r0 = -imm (this is then translated into a series of instructons)
952       // r0 = add r0, sp
953       emitThumbConstant(MBB, II, DestReg, Offset, TII);
954       MI.setInstrDescriptor(TII.get(ARM::tADDhirr));
955       MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
956       MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
957     }
958     return;
959   } else {
960     unsigned ImmIdx = 0;
961     int InstrOffs = 0;
962     unsigned NumBits = 0;
963     unsigned Scale = 1;
964     switch (AddrMode) {
965     case ARMII::AddrMode2: {
966       ImmIdx = i+2;
967       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
968       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
969         InstrOffs *= -1;
970       NumBits = 12;
971       break;
972     }
973     case ARMII::AddrMode3: {
974       ImmIdx = i+2;
975       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
976       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
977         InstrOffs *= -1;
978       NumBits = 8;
979       break;
980     }
981     case ARMII::AddrMode5: {
982       ImmIdx = i+1;
983       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
984       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
985         InstrOffs *= -1;
986       NumBits = 8;
987       Scale = 4;
988       break;
989     }
990     case ARMII::AddrModeTs: {
991       ImmIdx = i+1;
992       InstrOffs = MI.getOperand(ImmIdx).getImm();
993       NumBits = (FrameReg == ARM::SP) ? 8 : 5;
994       Scale = 4;
995       break;
996     }
997     default:
998       assert(0 && "Unsupported addressing mode!");
999       abort();
1000       break;
1001     }
1002
1003     Offset += InstrOffs * Scale;
1004     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1005     if (Offset < 0 && !isThumb) {
1006       Offset = -Offset;
1007       isSub = true;
1008     }
1009
1010     // Common case: small offset, fits into instruction.
1011     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1012     int ImmedOffset = Offset / Scale;
1013     unsigned Mask = (1 << NumBits) - 1;
1014     if ((unsigned)Offset <= Mask * Scale) {
1015       // Replace the FrameIndex with sp
1016       MI.getOperand(i).ChangeToRegister(FrameReg, false);
1017       if (isSub)
1018         ImmedOffset |= 1 << NumBits;
1019       ImmOp.ChangeToImmediate(ImmedOffset);
1020       return;
1021     }
1022
1023     bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
1024     if (AddrMode == ARMII::AddrModeTs) {
1025       // Thumb tLDRspi, tSTRspi. These will change to instructions that use
1026       // a different base register.
1027       NumBits = 5;
1028       Mask = (1 << NumBits) - 1;
1029     }
1030     // If this is a thumb spill / restore, we will be using a constpool load to
1031     // materialize the offset.
1032     if (AddrMode == ARMII::AddrModeTs && isThumSpillRestore)
1033       ImmOp.ChangeToImmediate(0);
1034     else {
1035       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1036       ImmedOffset = ImmedOffset & Mask;
1037       if (isSub)
1038         ImmedOffset |= 1 << NumBits;
1039       ImmOp.ChangeToImmediate(ImmedOffset);
1040       Offset &= ~(Mask*Scale);
1041     }
1042   }
1043   
1044   // If we get here, the immediate doesn't fit into the instruction.  We folded
1045   // as much as possible above, handle the rest, providing a register that is
1046   // SP+LargeImm.
1047   assert(Offset && "This code isn't needed if offset already handled!");
1048
1049   if (isThumb) {
1050     if (TII.isLoad(Opcode)) {
1051       // Use the destination register to materialize sp + offset.
1052       unsigned TmpReg = MI.getOperand(0).getReg();
1053       bool UseRR = false;
1054       if (Opcode == ARM::tRestore) {
1055         if (FrameReg == ARM::SP)
1056           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1057         else {
1058           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1059           UseRR = true;
1060         }
1061       } else
1062         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1063       MI.setInstrDescriptor(TII.get(ARM::tLDR));
1064       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1065       if (UseRR)
1066         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
1067       else
1068         MI.addRegOperand(0, false); // tLDR has an extra register operand.
1069     } else if (TII.isStore(Opcode)) {
1070       // FIXME! This is horrific!!! We need register scavenging.
1071       // Our temporary workaround has marked r3 unavailable. Of course, r3 is
1072       // also a ABI register so it's possible that is is the register that is
1073       // being storing here. If that's the case, we do the following:
1074       // r12 = r2
1075       // Use r2 to materialize sp + offset
1076       // str r3, r2
1077       // r2 = r12
1078       unsigned ValReg = MI.getOperand(0).getReg();
1079       unsigned TmpReg = ARM::R3;
1080       bool UseRR = false;
1081       if (ValReg == ARM::R3) {
1082         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1083           .addReg(ARM::R2, false, false, true);
1084         TmpReg = ARM::R2;
1085       }
1086       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1087         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1088           .addReg(ARM::R3, false, false, true);
1089       if (Opcode == ARM::tSpill) {
1090         if (FrameReg == ARM::SP)
1091           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1092         else {
1093           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1094           UseRR = true;
1095         }
1096       } else
1097         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1098       MI.setInstrDescriptor(TII.get(ARM::tSTR));
1099       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1100       if (UseRR)
1101         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
1102       else
1103         MI.addRegOperand(0, false); // tSTR has an extra register operand.
1104
1105       MachineBasicBlock::iterator NII = next(II);
1106       if (ValReg == ARM::R3)
1107         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R2)
1108           .addReg(ARM::R12, false, false, true);
1109       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1110         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R3)
1111           .addReg(ARM::R12, false, false, true);
1112     } else
1113       assert(false && "Unexpected opcode!");
1114   } else {
1115     // Insert a set of r12 with the full address: r12 = sp + offset
1116     // If the offset we have is too large to fit into the instruction, we need
1117     // to form it with a series of ADDri's.  Do this by taking 8-bit chunks
1118     // out of 'Offset'.
1119     unsigned ScratchReg = findScratchRegister(RS, &ARM::GPRRegClass, AFI);
1120     if (ScratchReg == 0)
1121       // No register is "free". Scavenge a register.
1122       ScratchReg = RS->scavengeRegister(&ARM::GPRRegClass, II, SPAdj);
1123     int PIdx = MI.findFirstPredOperandIdx();
1124     ARMCC::CondCodes Pred = (PIdx == -1)
1125       ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImmedValue();
1126     unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1127     emitARMRegPlusImmediate(MBB, II, ScratchReg, FrameReg,
1128                             isSub ? -Offset : Offset, Pred, PredReg, TII);
1129     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1130   }
1131 }
1132
1133 static unsigned estimateStackSize(MachineFunction &MF, MachineFrameInfo *MFI) {
1134   const MachineFrameInfo *FFI = MF.getFrameInfo();
1135   int Offset = 0;
1136   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
1137     int FixedOff = -FFI->getObjectOffset(i);
1138     if (FixedOff > Offset) Offset = FixedOff;
1139   }
1140   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
1141     Offset += FFI->getObjectSize(i);
1142     unsigned Align = FFI->getObjectAlignment(i);
1143     // Adjust to alignment boundary
1144     Offset = (Offset+Align-1)/Align*Align;
1145   }
1146   return (unsigned)Offset;
1147 }
1148
1149 void
1150 ARMRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1151                                                       RegScavenger *RS) const {
1152   // This tells PEI to spill the FP as if it is any other callee-save register
1153   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1154   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1155   // to combine multiple loads / stores.
1156   bool CanEliminateFrame = true;
1157   bool CS1Spilled = false;
1158   bool LRSpilled = false;
1159   unsigned NumGPRSpills = 0;
1160   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1161   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1162   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1163
1164   // Don't spill FP if the frame can be eliminated. This is determined
1165   // by scanning the callee-save registers to see if any is used.
1166   const unsigned *CSRegs = getCalleeSavedRegs();
1167   const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
1168   for (unsigned i = 0; CSRegs[i]; ++i) {
1169     unsigned Reg = CSRegs[i];
1170     bool Spilled = false;
1171     if (MF.isPhysRegUsed(Reg)) {
1172       AFI->setCSRegisterIsSpilled(Reg);
1173       Spilled = true;
1174       CanEliminateFrame = false;
1175     } else {
1176       // Check alias registers too.
1177       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
1178         if (MF.isPhysRegUsed(*Aliases)) {
1179           Spilled = true;
1180           CanEliminateFrame = false;
1181         }
1182       }
1183     }
1184
1185     if (CSRegClasses[i] == &ARM::GPRRegClass) {
1186       if (Spilled) {
1187         NumGPRSpills++;
1188
1189         if (!STI.isTargetDarwin()) {
1190           if (Reg == ARM::LR)
1191             LRSpilled = true;
1192           CS1Spilled = true;
1193           continue;
1194         }
1195
1196         // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1197         switch (Reg) {
1198         case ARM::LR:
1199           LRSpilled = true;
1200           // Fallthrough
1201         case ARM::R4:
1202         case ARM::R5:
1203         case ARM::R6:
1204         case ARM::R7:
1205           CS1Spilled = true;
1206           break;
1207         default:
1208           break;
1209         }
1210       } else { 
1211         if (!STI.isTargetDarwin()) {
1212           UnspilledCS1GPRs.push_back(Reg);
1213           continue;
1214         }
1215
1216         switch (Reg) {
1217         case ARM::R4:
1218         case ARM::R5:
1219         case ARM::R6:
1220         case ARM::R7:
1221         case ARM::LR:
1222           UnspilledCS1GPRs.push_back(Reg);
1223           break;
1224         default:
1225           UnspilledCS2GPRs.push_back(Reg);
1226           break;
1227         }
1228       }
1229     }
1230   }
1231
1232   bool ForceLRSpill = false;
1233   if (!LRSpilled && AFI->isThumbFunction()) {
1234     unsigned FnSize = ARM::GetFunctionSize(MF);
1235     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1236     // use of BL to implement far jump. If it turns out that it's not needed
1237     // then the branch fix up path will undo it.
1238     if (FnSize >= (1 << 11)) {
1239       CanEliminateFrame = false;
1240       ForceLRSpill = true;
1241     }
1242   }
1243
1244   bool ExtraCSSpill = false;
1245   if (!CanEliminateFrame || hasFP(MF)) {
1246     AFI->setHasStackFrame(true);
1247
1248     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1249     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1250     if (!LRSpilled && CS1Spilled) {
1251       MF.setPhysRegUsed(ARM::LR);
1252       AFI->setCSRegisterIsSpilled(ARM::LR);
1253       NumGPRSpills++;
1254       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1255                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1256       ForceLRSpill = false;
1257       ExtraCSSpill = true;
1258     }
1259
1260     // Darwin ABI requires FP to point to the stack slot that contains the
1261     // previous FP.
1262     if (STI.isTargetDarwin() || hasFP(MF)) {
1263       MF.setPhysRegUsed(FramePtr);
1264       NumGPRSpills++;
1265     }
1266
1267     // If stack and double are 8-byte aligned and we are spilling an odd number
1268     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
1269     // the integer and double callee save areas.
1270     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1271     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1272       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1273         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1274           unsigned Reg = UnspilledCS1GPRs[i];
1275           // Don't spiil high register if the function is thumb
1276           if (!AFI->isThumbFunction() || isLowRegister(Reg) || Reg == ARM::LR) {
1277             MF.setPhysRegUsed(Reg);
1278             AFI->setCSRegisterIsSpilled(Reg);
1279             if (!isReservedReg(MF, Reg))
1280               ExtraCSSpill = true;
1281             break;
1282           }
1283         }
1284       } else if (!UnspilledCS2GPRs.empty() &&
1285                  !AFI->isThumbFunction()) {
1286         unsigned Reg = UnspilledCS2GPRs.front();
1287         MF.setPhysRegUsed(Reg);
1288         AFI->setCSRegisterIsSpilled(Reg);
1289         if (!isReservedReg(MF, Reg))
1290           ExtraCSSpill = true;
1291       }
1292     }
1293
1294     // Estimate if we might need to scavenge a register at some point in order
1295     // to materialize a stack offset. If so, either spill one additiona
1296     // callee-saved register or reserve a special spill slot to facilitate
1297     // register scavenging.
1298     if (RS && !ExtraCSSpill && !AFI->isThumbFunction()) {
1299       MachineFrameInfo  *MFI = MF.getFrameInfo();
1300       unsigned Size = estimateStackSize(MF, MFI);
1301       unsigned Limit = (1 << 12) - 1;
1302       for (MachineFunction::iterator BB = MF.begin(),E = MF.end();BB != E; ++BB)
1303         for (MachineBasicBlock::iterator I= BB->begin(); I != BB->end(); ++I) {
1304           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1305             if (I->getOperand(i).isFrameIndex()) {
1306               unsigned Opcode = I->getOpcode();
1307               const TargetInstrDescriptor &Desc = TII.get(Opcode);
1308               unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1309               if (AddrMode == ARMII::AddrMode3) {
1310                 Limit = (1 << 8) - 1;
1311                 goto DoneEstimating;
1312               } else if (AddrMode == ARMII::AddrMode5) {
1313                 unsigned ThisLimit = ((1 << 8) - 1) * 4;
1314                 if (ThisLimit < Limit)
1315                   Limit = ThisLimit;
1316               }
1317             }
1318         }
1319     DoneEstimating:
1320       if (Size >= Limit) {
1321         // If any non-reserved CS register isn't spilled, just spill one or two
1322         // extra. That should take care of it!
1323         unsigned NumExtras = TargetAlign / 4;
1324         SmallVector<unsigned, 2> Extras;
1325         while (NumExtras && !UnspilledCS1GPRs.empty()) {
1326           unsigned Reg = UnspilledCS1GPRs.back();
1327           UnspilledCS1GPRs.pop_back();
1328           if (!isReservedReg(MF, Reg)) {
1329             Extras.push_back(Reg);
1330             NumExtras--;
1331           }
1332         }
1333         while (NumExtras && !UnspilledCS2GPRs.empty()) {
1334           unsigned Reg = UnspilledCS2GPRs.back();
1335           UnspilledCS2GPRs.pop_back();
1336           if (!isReservedReg(MF, Reg)) {
1337             Extras.push_back(Reg);
1338             NumExtras--;
1339           }
1340         }
1341         if (Extras.size() && NumExtras == 0) {
1342           for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1343             MF.setPhysRegUsed(Extras[i]);
1344             AFI->setCSRegisterIsSpilled(Extras[i]);
1345           }
1346         } else {
1347           // Reserve a slot closest to SP or frame pointer.
1348           const TargetRegisterClass *RC = &ARM::GPRRegClass;
1349           RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1350                                                            RC->getAlignment()));
1351         }
1352       }
1353     }
1354   }
1355
1356   if (ForceLRSpill) {
1357     MF.setPhysRegUsed(ARM::LR);
1358     AFI->setCSRegisterIsSpilled(ARM::LR);
1359     AFI->setLRIsSpilledForFarJump(true);
1360   }
1361 }
1362
1363 /// Move iterator pass the next bunch of callee save load / store ops for
1364 /// the particular spill area (1: integer area 1, 2: integer area 2,
1365 /// 3: fp area, 0: don't care).
1366 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1367                                    MachineBasicBlock::iterator &MBBI,
1368                                    int Opc, unsigned Area,
1369                                    const ARMSubtarget &STI) {
1370   while (MBBI != MBB.end() &&
1371          MBBI->getOpcode() == Opc && MBBI->getOperand(1).isFrameIndex()) {
1372     if (Area != 0) {
1373       bool Done = false;
1374       unsigned Category = 0;
1375       switch (MBBI->getOperand(0).getReg()) {
1376       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1377       case ARM::LR:
1378         Category = 1;
1379         break;
1380       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1381         Category = STI.isTargetDarwin() ? 2 : 1;
1382         break;
1383       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1384       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1385         Category = 3;
1386         break;
1387       default:
1388         Done = true;
1389         break;
1390       }
1391       if (Done || Category != Area)
1392         break;
1393     }
1394
1395     ++MBBI;
1396   }
1397 }
1398
1399 void ARMRegisterInfo::emitPrologue(MachineFunction &MF) const {
1400   MachineBasicBlock &MBB = MF.front();
1401   MachineBasicBlock::iterator MBBI = MBB.begin();
1402   MachineFrameInfo  *MFI = MF.getFrameInfo();
1403   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1404   bool isThumb = AFI->isThumbFunction();
1405   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1406   unsigned NumBytes = MFI->getStackSize();
1407   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1408
1409   if (isThumb) {
1410     // Check if R3 is live in. It might have to be used as a scratch register.
1411     for (MachineFunction::livein_iterator I=MF.livein_begin(),E=MF.livein_end();
1412          I != E; ++I) {
1413       if ((*I).first == ARM::R3) {
1414         AFI->setR3IsLiveIn(true);
1415         break;
1416       }
1417     }
1418
1419     // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
1420     NumBytes = (NumBytes + 3) & ~3;
1421     MFI->setStackSize(NumBytes);
1422   }
1423
1424   // Determine the sizes of each callee-save spill areas and record which frame
1425   // belongs to which callee-save spill areas.
1426   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1427   int FramePtrSpillFI = 0;
1428
1429   if (VARegSaveSize)
1430     emitSPUpdate(MBB, MBBI, -VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1431
1432   if (!AFI->hasStackFrame()) {
1433     if (NumBytes != 0)
1434       emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1435     return;
1436   }
1437
1438   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1439     unsigned Reg = CSI[i].getReg();
1440     int FI = CSI[i].getFrameIdx();
1441     switch (Reg) {
1442     case ARM::R4:
1443     case ARM::R5:
1444     case ARM::R6:
1445     case ARM::R7:
1446     case ARM::LR:
1447       if (Reg == FramePtr)
1448         FramePtrSpillFI = FI;
1449       AFI->addGPRCalleeSavedArea1Frame(FI);
1450       GPRCS1Size += 4;
1451       break;
1452     case ARM::R8:
1453     case ARM::R9:
1454     case ARM::R10:
1455     case ARM::R11:
1456       if (Reg == FramePtr)
1457         FramePtrSpillFI = FI;
1458       if (STI.isTargetDarwin()) {
1459         AFI->addGPRCalleeSavedArea2Frame(FI);
1460         GPRCS2Size += 4;
1461       } else {
1462         AFI->addGPRCalleeSavedArea1Frame(FI);
1463         GPRCS1Size += 4;
1464       }
1465       break;
1466     default:
1467       AFI->addDPRCalleeSavedAreaFrame(FI);
1468       DPRCSSize += 8;
1469     }
1470   }
1471
1472   if (!isThumb) {
1473     // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1474     emitSPUpdate(MBB, MBBI, -GPRCS1Size, ARMCC::AL, 0, isThumb, TII);
1475     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 1, STI);
1476   } else if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH)
1477     ++MBBI;
1478
1479   // Darwin ABI requires FP to point to the stack slot that contains the
1480   // previous FP.
1481   if (STI.isTargetDarwin() || hasFP(MF)) {
1482     MachineInstrBuilder MIB =
1483       BuildMI(MBB, MBBI, TII.get(isThumb ? ARM::tADDrSPi : ARM::ADDri),FramePtr)
1484       .addFrameIndex(FramePtrSpillFI).addImm(0);
1485     if (!isThumb) AddDefaultCC(AddDefaultPred(MIB));
1486   }
1487
1488   if (!isThumb) {
1489     // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1490     emitSPUpdate(MBB, MBBI, -GPRCS2Size, ARMCC::AL, 0, false, TII);
1491
1492     // Build the new SUBri to adjust SP for FP callee-save spill area.
1493     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 2, STI);
1494     emitSPUpdate(MBB, MBBI, -DPRCSSize, ARMCC::AL, 0, false, TII);
1495   }
1496
1497   // Determine starting offsets of spill areas.
1498   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1499   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1500   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1501   AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
1502   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1503   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1504   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1505   
1506   NumBytes = DPRCSOffset;
1507   if (NumBytes) {
1508     // Insert it after all the callee-save spills.
1509     if (!isThumb)
1510       movePastCSLoadStoreOps(MBB, MBBI, ARM::FSTD, 3, STI);
1511     emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1512   }
1513
1514   if(STI.isTargetELF() && hasFP(MF)) {
1515     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1516                              AFI->getFramePtrSpillOffset());
1517   }
1518
1519   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1520   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1521   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1522 }
1523
1524 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1525   for (unsigned i = 0; CSRegs[i]; ++i)
1526     if (Reg == CSRegs[i])
1527       return true;
1528   return false;
1529 }
1530
1531 static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
1532   return ((MI->getOpcode() == ARM::FLDD ||
1533            MI->getOpcode() == ARM::LDR  ||
1534            MI->getOpcode() == ARM::tRestore) &&
1535           MI->getOperand(1).isFrameIndex() &&
1536           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1537 }
1538
1539 void ARMRegisterInfo::emitEpilogue(MachineFunction &MF,
1540                                    MachineBasicBlock &MBB) const {
1541   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1542   assert((MBBI->getOpcode() == ARM::BX_RET ||
1543           MBBI->getOpcode() == ARM::tBX_RET ||
1544           MBBI->getOpcode() == ARM::tPOP_RET) &&
1545          "Can only insert epilog into returning blocks");
1546
1547   MachineFrameInfo *MFI = MF.getFrameInfo();
1548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1549   bool isThumb = AFI->isThumbFunction();
1550   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1551   int NumBytes = (int)MFI->getStackSize();
1552   if (!AFI->hasStackFrame()) {
1553     if (NumBytes != 0)
1554       emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1555   } else {
1556     // Unwind MBBI to point to first LDR / FLDD.
1557     const unsigned *CSRegs = getCalleeSavedRegs();
1558     if (MBBI != MBB.begin()) {
1559       do
1560         --MBBI;
1561       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
1562       if (!isCSRestore(MBBI, CSRegs))
1563         ++MBBI;
1564     }
1565
1566     // Move SP to start of FP callee save spill area.
1567     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1568                  AFI->getGPRCalleeSavedArea2Size() +
1569                  AFI->getDPRCalleeSavedAreaSize());
1570     if (isThumb) {
1571       if (hasFP(MF)) {
1572         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1573         // Reset SP based on frame pointer only if the stack frame extends beyond
1574         // frame pointer stack slot or target is ELF and the function has FP.
1575         if (NumBytes)
1576           emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes, TII);
1577         else
1578           BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::SP).addReg(FramePtr);
1579       } else {
1580         if (MBBI->getOpcode() == ARM::tBX_RET &&
1581             &MBB.front() != MBBI &&
1582             prior(MBBI)->getOpcode() == ARM::tPOP) {
1583           MachineBasicBlock::iterator PMBBI = prior(MBBI);
1584           emitSPUpdate(MBB, PMBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1585         } else
1586           emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1587       }
1588     } else {
1589       // Darwin ABI requires FP to point to the stack slot that contains the
1590       // previous FP.
1591       if ((STI.isTargetDarwin() && NumBytes) || hasFP(MF)) {
1592         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1593         // Reset SP based on frame pointer only if the stack frame extends beyond
1594         // frame pointer stack slot or target is ELF and the function has FP.
1595         if (AFI->getGPRCalleeSavedArea2Size() ||
1596             AFI->getDPRCalleeSavedAreaSize()  ||
1597             AFI->getDPRCalleeSavedAreaOffset()||
1598             hasFP(MF))
1599           if (NumBytes)
1600             BuildMI(MBB, MBBI, TII.get(ARM::SUBri), ARM::SP).addReg(FramePtr)
1601               .addImm(NumBytes)
1602               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1603           else
1604             BuildMI(MBB, MBBI, TII.get(ARM::MOVr), ARM::SP).addReg(FramePtr)
1605               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1606       } else if (NumBytes) {
1607         emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, false, TII);
1608       }
1609
1610       // Move SP to start of integer callee save spill area 2.
1611       movePastCSLoadStoreOps(MBB, MBBI, ARM::FLDD, 3, STI);
1612       emitSPUpdate(MBB, MBBI, AFI->getDPRCalleeSavedAreaSize(), ARMCC::AL, 0,
1613                    false, TII);
1614
1615       // Move SP to start of integer callee save spill area 1.
1616       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 2, STI);
1617       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea2Size(), ARMCC::AL, 0,
1618                    false, TII);
1619
1620       // Move SP to SP upon entry to the function.
1621       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 1, STI);
1622       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea1Size(), ARMCC::AL, 0,
1623                    false, TII);
1624     }
1625   }
1626
1627   if (VARegSaveSize) {
1628     if (isThumb)
1629       // Epilogue for vararg functions: pop LR to R3 and branch off it.
1630       // FIXME: Verify this is still ok when R3 is no longer being reserved.
1631       BuildMI(MBB, MBBI, TII.get(ARM::tPOP)).addReg(ARM::R3);
1632
1633     emitSPUpdate(MBB, MBBI, VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1634
1635     if (isThumb) {
1636       BuildMI(MBB, MBBI, TII.get(ARM::tBX_RET_vararg)).addReg(ARM::R3);
1637       MBB.erase(MBBI);
1638     }
1639   }
1640 }
1641
1642 unsigned ARMRegisterInfo::getRARegister() const {
1643   return ARM::LR;
1644 }
1645
1646 unsigned ARMRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1647   if (STI.isTargetDarwin() || hasFP(MF))
1648     return (STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11;
1649   else
1650     return ARM::SP;
1651 }
1652
1653 unsigned ARMRegisterInfo::getEHExceptionRegister() const {
1654   assert(0 && "What is the exception register");
1655   return 0;
1656 }
1657
1658 unsigned ARMRegisterInfo::getEHHandlerRegister() const {
1659   assert(0 && "What is the exception handler register");
1660   return 0;
1661 }
1662
1663 int ARMRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1664   assert(0 && "What is the dwarf register number");
1665   return -1;
1666 }
1667
1668 #include "ARMGenRegisterInfo.inc"
1669