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