ARM asm parser wasn't able to parse a "mov" instruction while in Thumb
[oota-llvm.git] / lib / Target / ARM / Thumb1RegisterInfo.cpp
1 //===- Thumb1RegisterInfo.cpp - Thumb-1 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 Thumb-1 implementation of the TargetRegisterInfo
11 // class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMBaseInstrInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "Thumb1InstrInfo.h"
21 #include "Thumb1RegisterInfo.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineLocation.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37
38 namespace llvm {
39 extern cl::opt<bool> ReuseFrameIndexVals;
40 }
41
42 using namespace llvm;
43
44 Thumb1RegisterInfo::Thumb1RegisterInfo(const ARMBaseInstrInfo &tii,
45                                        const ARMSubtarget &sti)
46   : ARMBaseRegisterInfo(tii, sti) {
47 }
48
49 const TargetRegisterClass*
50 Thumb1RegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
51                                                                          const {
52   if (RC == ARM::tGPRRegisterClass || RC->hasSuperClass(ARM::tGPRRegisterClass))
53     return ARM::tGPRRegisterClass;
54   return ARMBaseRegisterInfo::getLargestLegalSuperClass(RC);
55 }
56
57 const TargetRegisterClass *
58 Thumb1RegisterInfo::getPointerRegClass(unsigned Kind) const {
59   return ARM::tGPRRegisterClass;
60 }
61
62 /// emitLoadConstPool - Emits a load from constpool to materialize the
63 /// specified immediate.
64 void
65 Thumb1RegisterInfo::emitLoadConstPool(MachineBasicBlock &MBB,
66                                       MachineBasicBlock::iterator &MBBI,
67                                       DebugLoc dl,
68                                       unsigned DestReg, unsigned SubIdx,
69                                       int Val,
70                                       ARMCC::CondCodes Pred, unsigned PredReg,
71                                       unsigned MIFlags) const {
72   MachineFunction &MF = *MBB.getParent();
73   MachineConstantPool *ConstantPool = MF.getConstantPool();
74   const Constant *C = ConstantInt::get(
75           Type::getInt32Ty(MBB.getParent()->getFunction()->getContext()), Val);
76   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
77
78   BuildMI(MBB, MBBI, dl, TII.get(ARM::tLDRpci))
79     .addReg(DestReg, getDefRegState(true), SubIdx)
80     .addConstantPoolIndex(Idx).addImm(Pred).addReg(PredReg)
81     .setMIFlags(MIFlags);
82 }
83
84
85 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
86 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
87 /// in a register using mov / mvn sequences or load the immediate from a
88 /// constpool entry.
89 static
90 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
91                               MachineBasicBlock::iterator &MBBI,
92                               DebugLoc dl,
93                               unsigned DestReg, unsigned BaseReg,
94                               int NumBytes, bool CanChangeCC,
95                               const TargetInstrInfo &TII,
96                               const ARMBaseRegisterInfo& MRI,
97                               unsigned MIFlags = MachineInstr::NoFlags) {
98     MachineFunction &MF = *MBB.getParent();
99     bool isHigh = !isARMLowRegister(DestReg) ||
100                   (BaseReg != 0 && !isARMLowRegister(BaseReg));
101     bool isSub = false;
102     // Subtract doesn't have high register version. Load the negative value
103     // if either base or dest register is a high register. Also, if do not
104     // issue sub as part of the sequence if condition register is to be
105     // preserved.
106     if (NumBytes < 0 && !isHigh && CanChangeCC) {
107       isSub = true;
108       NumBytes = -NumBytes;
109     }
110     unsigned LdReg = DestReg;
111     if (DestReg == ARM::SP) {
112       assert(BaseReg == ARM::SP && "Unexpected!");
113       LdReg = MF.getRegInfo().createVirtualRegister(ARM::tGPRRegisterClass);
114     }
115
116     if (NumBytes <= 255 && NumBytes >= 0)
117       AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8), LdReg))
118         .addImm(NumBytes).setMIFlags(MIFlags);
119     else if (NumBytes < 0 && NumBytes >= -255) {
120       AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8), LdReg))
121         .addImm(NumBytes).setMIFlags(MIFlags);
122       AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tRSB), LdReg))
123         .addReg(LdReg, RegState::Kill).setMIFlags(MIFlags);
124     } else
125       MRI.emitLoadConstPool(MBB, MBBI, dl, LdReg, 0, NumBytes,
126                             ARMCC::AL, 0, MIFlags);
127
128     // Emit add / sub.
129     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
130     MachineInstrBuilder MIB =
131       BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
132     if (Opc != ARM::tADDhirr)
133       MIB = AddDefaultT1CC(MIB);
134     if (DestReg == ARM::SP || isSub)
135       MIB.addReg(BaseReg).addReg(LdReg, RegState::Kill);
136     else
137       MIB.addReg(LdReg).addReg(BaseReg, RegState::Kill);
138     AddDefaultPred(MIB);
139 }
140
141 /// calcNumMI - Returns the number of instructions required to materialize
142 /// the specific add / sub r, c instruction.
143 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
144                           unsigned NumBits, unsigned Scale) {
145   unsigned NumMIs = 0;
146   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
147
148   if (Opc == ARM::tADDrSPi) {
149     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
150     Bytes -= ThisVal;
151     NumMIs++;
152     NumBits = 8;
153     Scale = 1;  // Followed by a number of tADDi8.
154     Chunk = ((1 << NumBits) - 1) * Scale;
155   }
156
157   NumMIs += Bytes / Chunk;
158   if ((Bytes % Chunk) != 0)
159     NumMIs++;
160   if (ExtraOpc)
161     NumMIs++;
162   return NumMIs;
163 }
164
165 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
166 /// a destreg = basereg + immediate in Thumb code.
167 void llvm::emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
168                                      MachineBasicBlock::iterator &MBBI,
169                                      DebugLoc dl,
170                                      unsigned DestReg, unsigned BaseReg,
171                                      int NumBytes, const TargetInstrInfo &TII,
172                                      const ARMBaseRegisterInfo& MRI,
173                                      unsigned MIFlags) {
174   bool isSub = NumBytes < 0;
175   unsigned Bytes = (unsigned)NumBytes;
176   if (isSub) Bytes = -NumBytes;
177   bool isMul4 = (Bytes & 3) == 0;
178   bool isTwoAddr = false;
179   bool DstNotEqBase = false;
180   unsigned NumBits = 1;
181   unsigned Scale = 1;
182   int Opc = 0;
183   int ExtraOpc = 0;
184   bool NeedCC = false;
185   bool NeedPred = false;
186
187   if (DestReg == BaseReg && BaseReg == ARM::SP) {
188     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
189     NumBits = 7;
190     Scale = 4;
191     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
192     isTwoAddr = true;
193   } else if (!isSub && BaseReg == ARM::SP) {
194     // r1 = add sp, 403
195     // =>
196     // r1 = add sp, 100 * 4
197     // r1 = add r1, 3
198     if (!isMul4) {
199       Bytes &= ~3;
200       ExtraOpc = ARM::tADDi3;
201     }
202     NumBits = 8;
203     Scale = 4;
204     Opc = ARM::tADDrSPi;
205   } else {
206     // sp = sub sp, c
207     // r1 = sub sp, c
208     // r8 = sub sp, c
209     if (DestReg != BaseReg)
210       DstNotEqBase = true;
211     NumBits = 8;
212     if (DestReg == ARM::SP) {
213       Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
214       assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
215       NumBits = 7;
216       Scale = 4;
217     } else {
218       Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
219       NumBits = 8;
220       NeedPred = NeedCC = true;
221     }
222     isTwoAddr = true;
223   }
224
225   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
226   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
227   if (NumMIs > Threshold) {
228     // This will expand into too many instructions. Load the immediate from a
229     // constpool entry.
230     emitThumbRegPlusImmInReg(MBB, MBBI, dl,
231                              DestReg, BaseReg, NumBytes, true,
232                              TII, MRI, MIFlags);
233     return;
234   }
235
236   if (DstNotEqBase) {
237     if (isARMLowRegister(DestReg) && isARMLowRegister(BaseReg)) {
238       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
239       unsigned Chunk = (1 << 3) - 1;
240       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
241       Bytes -= ThisVal;
242       const TargetInstrDesc &TID = TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3);
243       const MachineInstrBuilder MIB =
244         AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TID, DestReg).setMIFlags(MIFlags));
245       AddDefaultPred(MIB.addReg(BaseReg, RegState::Kill).addImm(ThisVal));
246     } else {
247       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), DestReg)
248         .addReg(BaseReg, RegState::Kill)
249         .setMIFlags(MIFlags);
250     }
251     BaseReg = DestReg;
252   }
253
254   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
255   while (Bytes) {
256     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
257     Bytes -= ThisVal;
258     ThisVal /= Scale;
259     // Build the new tADD / tSUB.
260     if (isTwoAddr) {
261       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
262       if (NeedCC)
263         MIB = AddDefaultT1CC(MIB);
264       MIB.addReg(DestReg).addImm(ThisVal);
265       if (NeedPred)
266         MIB = AddDefaultPred(MIB);
267       MIB.setMIFlags(MIFlags);
268     }
269     else {
270       bool isKill = BaseReg != ARM::SP;
271       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
272       if (NeedCC)
273         MIB = AddDefaultT1CC(MIB);
274       MIB.addReg(BaseReg, getKillRegState(isKill)).addImm(ThisVal);
275       if (NeedPred)
276         MIB = AddDefaultPred(MIB);
277       MIB.setMIFlags(MIFlags);
278
279       BaseReg = DestReg;
280       if (Opc == ARM::tADDrSPi) {
281         // r4 = add sp, imm
282         // r4 = add r4, imm
283         // ...
284         NumBits = 8;
285         Scale = 1;
286         Chunk = ((1 << NumBits) - 1) * Scale;
287         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
288         NeedPred = NeedCC = isTwoAddr = true;
289       }
290     }
291   }
292
293   if (ExtraOpc) {
294     const TargetInstrDesc &TID = TII.get(ExtraOpc);
295     AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TID, DestReg))
296                    .addReg(DestReg, RegState::Kill)
297                    .addImm(((unsigned)NumBytes) & 3)
298                    .setMIFlags(MIFlags));
299   }
300 }
301
302 static void emitSPUpdate(MachineBasicBlock &MBB,
303                          MachineBasicBlock::iterator &MBBI,
304                          const TargetInstrInfo &TII, DebugLoc dl,
305                          const Thumb1RegisterInfo &MRI,
306                          int NumBytes) {
307   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
308                             MRI);
309 }
310
311 void Thumb1RegisterInfo::
312 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
313                               MachineBasicBlock::iterator I) const {
314   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
315
316   if (!TFI->hasReservedCallFrame(MF)) {
317     // If we have alloca, convert as follows:
318     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
319     // ADJCALLSTACKUP   -> add, sp, sp, amount
320     MachineInstr *Old = I;
321     DebugLoc dl = Old->getDebugLoc();
322     unsigned Amount = Old->getOperand(0).getImm();
323     if (Amount != 0) {
324       // We need to keep the stack aligned properly.  To do this, we round the
325       // amount of space needed for the outgoing arguments up to the next
326       // alignment boundary.
327       unsigned Align = TFI->getStackAlignment();
328       Amount = (Amount+Align-1)/Align*Align;
329
330       // Replace the pseudo instruction with a new instruction...
331       unsigned Opc = Old->getOpcode();
332       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
333         emitSPUpdate(MBB, I, TII, dl, *this, -Amount);
334       } else {
335         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
336         emitSPUpdate(MBB, I, TII, dl, *this, Amount);
337       }
338     }
339   }
340   MBB.erase(I);
341 }
342
343 /// emitThumbConstant - Emit a series of instructions to materialize a
344 /// constant.
345 static void emitThumbConstant(MachineBasicBlock &MBB,
346                               MachineBasicBlock::iterator &MBBI,
347                               unsigned DestReg, int Imm,
348                               const TargetInstrInfo &TII,
349                               const Thumb1RegisterInfo& MRI,
350                               DebugLoc dl) {
351   bool isSub = Imm < 0;
352   if (isSub) Imm = -Imm;
353
354   int Chunk = (1 << 8) - 1;
355   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
356   Imm -= ThisVal;
357   AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8),
358                                         DestReg))
359                  .addImm(ThisVal));
360   if (Imm > 0)
361     emitThumbRegPlusImmediate(MBB, MBBI, dl, DestReg, DestReg, Imm, TII, MRI);
362   if (isSub) {
363     const TargetInstrDesc &TID = TII.get(ARM::tRSB);
364     AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TID, DestReg))
365                    .addReg(DestReg, RegState::Kill));
366   }
367 }
368
369 static void removeOperands(MachineInstr &MI, unsigned i) {
370   unsigned Op = i;
371   for (unsigned e = MI.getNumOperands(); i != e; ++i)
372     MI.RemoveOperand(Op);
373 }
374
375 /// convertToNonSPOpcode - Change the opcode to the non-SP version, because
376 /// we're replacing the frame index with a non-SP register.
377 static unsigned convertToNonSPOpcode(unsigned Opcode) {
378   switch (Opcode) {
379   case ARM::tLDRspi:
380   case ARM::tRestore:           // FIXME: Should this opcode be here?
381     return ARM::tLDRi;
382
383   case ARM::tSTRspi:
384   case ARM::tSpill:             // FIXME: Should this opcode be here?
385     return ARM::tSTRi;
386   }
387
388   return Opcode;
389 }
390
391 bool Thumb1RegisterInfo::
392 rewriteFrameIndex(MachineBasicBlock::iterator II, unsigned FrameRegIdx,
393                   unsigned FrameReg, int &Offset,
394                   const ARMBaseInstrInfo &TII) const {
395   MachineInstr &MI = *II;
396   MachineBasicBlock &MBB = *MI.getParent();
397   DebugLoc dl = MI.getDebugLoc();
398   unsigned Opcode = MI.getOpcode();
399   const TargetInstrDesc &Desc = MI.getDesc();
400   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
401
402   if (Opcode == ARM::tADDrSPi) {
403     Offset += MI.getOperand(FrameRegIdx+1).getImm();
404
405     // Can't use tADDrSPi if it's based off the frame pointer.
406     unsigned NumBits = 0;
407     unsigned Scale = 1;
408     if (FrameReg != ARM::SP) {
409       Opcode = ARM::tADDi3;
410       MI.setDesc(TII.get(Opcode));
411       NumBits = 3;
412     } else {
413       NumBits = 8;
414       Scale = 4;
415       assert((Offset & 3) == 0 &&
416              "Thumb add/sub sp, #imm immediate must be multiple of 4!");
417     }
418
419     unsigned PredReg;
420     if (Offset == 0 && getInstrPredicate(&MI, PredReg) == ARMCC::AL) {
421       // Turn it into a move.
422       MI.setDesc(TII.get(ARM::tMOVgpr2tgpr));
423       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
424       // Remove offset and remaining explicit predicate operands.
425       do MI.RemoveOperand(FrameRegIdx+1);
426       while (MI.getNumOperands() > FrameRegIdx+1 &&
427              (!MI.getOperand(FrameRegIdx+1).isReg() ||
428               !MI.getOperand(FrameRegIdx+1).isImm()));
429       return true;
430     }
431
432     // Common case: small offset, fits into instruction.
433     unsigned Mask = (1 << NumBits) - 1;
434     if (((Offset / Scale) & ~Mask) == 0) {
435       // Replace the FrameIndex with sp / fp
436       if (Opcode == ARM::tADDi3) {
437         removeOperands(MI, FrameRegIdx);
438         MachineInstrBuilder MIB(&MI);
439         AddDefaultPred(AddDefaultT1CC(MIB).addReg(FrameReg)
440                        .addImm(Offset / Scale));
441       } else {
442         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
443         MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset / Scale);
444       }
445       return true;
446     }
447
448     unsigned DestReg = MI.getOperand(0).getReg();
449     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
450     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
451     // MI would expand into a large number of instructions. Don't try to
452     // simplify the immediate.
453     if (NumMIs > 2) {
454       emitThumbRegPlusImmediate(MBB, II, dl, DestReg, FrameReg, Offset, TII,
455                                 *this);
456       MBB.erase(II);
457       return true;
458     }
459
460     if (Offset > 0) {
461       // Translate r0 = add sp, imm to
462       // r0 = add sp, 255*4
463       // r0 = add r0, (imm - 255*4)
464       if (Opcode == ARM::tADDi3) {
465         removeOperands(MI, FrameRegIdx);
466         MachineInstrBuilder MIB(&MI);
467         AddDefaultPred(AddDefaultT1CC(MIB).addReg(FrameReg).addImm(Mask));
468       } else {
469         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
470         MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Mask);
471       }
472       Offset = (Offset - Mask * Scale);
473       MachineBasicBlock::iterator NII = llvm::next(II);
474       emitThumbRegPlusImmediate(MBB, NII, dl, DestReg, DestReg, Offset, TII,
475                                 *this);
476     } else {
477       // Translate r0 = add sp, -imm to
478       // r0 = -imm (this is then translated into a series of instructons)
479       // r0 = add r0, sp
480       emitThumbConstant(MBB, II, DestReg, Offset, TII, *this, dl);
481
482       MI.setDesc(TII.get(ARM::tADDhirr));
483       MI.getOperand(FrameRegIdx).ChangeToRegister(DestReg, false, false, true);
484       MI.getOperand(FrameRegIdx+1).ChangeToRegister(FrameReg, false);
485       if (Opcode == ARM::tADDi3) {
486         MachineInstrBuilder MIB(&MI);
487         AddDefaultPred(MIB);
488       }
489     }
490     return true;
491   } else {
492     if (AddrMode != ARMII::AddrModeT1_s)
493       llvm_unreachable("Unsupported addressing mode!");
494
495     unsigned ImmIdx = FrameRegIdx + 1;
496     int InstrOffs = MI.getOperand(ImmIdx).getImm();
497     unsigned NumBits = (FrameReg == ARM::SP) ? 8 : 5;
498     unsigned Scale = 4;
499
500     Offset += InstrOffs * Scale;
501     assert((Offset & (Scale - 1)) == 0 && "Can't encode this offset!");
502
503     // Common case: small offset, fits into instruction.
504     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
505     int ImmedOffset = Offset / Scale;
506     unsigned Mask = (1 << NumBits) - 1;
507
508     if ((unsigned)Offset <= Mask * Scale) {
509       // Replace the FrameIndex with the frame register (e.g., sp).
510       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
511       ImmOp.ChangeToImmediate(ImmedOffset);
512
513       // If we're using a register where sp was stored, convert the instruction
514       // to the non-SP version.
515       unsigned NewOpc = convertToNonSPOpcode(Opcode);
516       if (NewOpc != Opcode && FrameReg != ARM::SP)
517         MI.setDesc(TII.get(NewOpc));
518
519       return true;
520     }
521
522     NumBits = 5;
523     Mask = (1 << NumBits) - 1;
524
525     // If this is a thumb spill / restore, we will be using a constpool load to
526     // materialize the offset.
527     if (Opcode == ARM::tRestore || Opcode == ARM::tSpill) {
528       ImmOp.ChangeToImmediate(0);
529     } else {
530       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
531       ImmedOffset = ImmedOffset & Mask;
532       ImmOp.ChangeToImmediate(ImmedOffset);
533       Offset &= ~(Mask * Scale);
534     }
535   }
536
537   return Offset == 0;
538 }
539
540 void
541 Thumb1RegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
542                                       unsigned BaseReg, int64_t Offset) const {
543   MachineInstr &MI = *I;
544   int Off = Offset; // ARM doesn't need the general 64-bit offsets
545   unsigned i = 0;
546
547   while (!MI.getOperand(i).isFI()) {
548     ++i;
549     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
550   }
551   bool Done = false;
552   Done = rewriteFrameIndex(MI, i, BaseReg, Off, TII);
553   assert (Done && "Unable to resolve frame index!");
554 }
555
556 /// saveScavengerRegister - Spill the register so it can be used by the
557 /// register scavenger. Return true.
558 bool
559 Thumb1RegisterInfo::saveScavengerRegister(MachineBasicBlock &MBB,
560                                           MachineBasicBlock::iterator I,
561                                           MachineBasicBlock::iterator &UseMI,
562                                           const TargetRegisterClass *RC,
563                                           unsigned Reg) const {
564   // Thumb1 can't use the emergency spill slot on the stack because
565   // ldr/str immediate offsets must be positive, and if we're referencing
566   // off the frame pointer (if, for example, there are alloca() calls in
567   // the function, the offset will be negative. Use R12 instead since that's
568   // a call clobbered register that we know won't be used in Thumb1 mode.
569   DebugLoc DL;
570   BuildMI(MBB, I, DL, TII.get(ARM::tMOVtgpr2gpr)).
571     addReg(ARM::R12, RegState::Define).addReg(Reg, RegState::Kill);
572
573   // The UseMI is where we would like to restore the register. If there's
574   // interference with R12 before then, however, we'll need to restore it
575   // before that instead and adjust the UseMI.
576   bool done = false;
577   for (MachineBasicBlock::iterator II = I; !done && II != UseMI ; ++II) {
578     if (II->isDebugValue())
579       continue;
580     // If this instruction affects R12, adjust our restore point.
581     for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
582       const MachineOperand &MO = II->getOperand(i);
583       if (!MO.isReg() || MO.isUndef() || !MO.getReg() ||
584           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
585         continue;
586       if (MO.getReg() == ARM::R12) {
587         UseMI = II;
588         done = true;
589         break;
590       }
591     }
592   }
593   // Restore the register from R12
594   BuildMI(MBB, UseMI, DL, TII.get(ARM::tMOVgpr2tgpr)).
595     addReg(Reg, RegState::Define).addReg(ARM::R12, RegState::Kill);
596
597   return true;
598 }
599
600 void
601 Thumb1RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
602                                         int SPAdj, RegScavenger *RS) const {
603   unsigned VReg = 0;
604   unsigned i = 0;
605   MachineInstr &MI = *II;
606   MachineBasicBlock &MBB = *MI.getParent();
607   MachineFunction &MF = *MBB.getParent();
608   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
609   DebugLoc dl = MI.getDebugLoc();
610
611   while (!MI.getOperand(i).isFI()) {
612     ++i;
613     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
614   }
615
616   unsigned FrameReg = ARM::SP;
617   int FrameIndex = MI.getOperand(i).getIndex();
618   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
619                MF.getFrameInfo()->getStackSize() + SPAdj;
620
621   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
622     Offset -= AFI->getGPRCalleeSavedArea1Offset();
623   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
624     Offset -= AFI->getGPRCalleeSavedArea2Offset();
625   else if (MF.getFrameInfo()->hasVarSizedObjects()) {
626     assert(SPAdj == 0 && MF.getTarget().getFrameLowering()->hasFP(MF) &&
627            "Unexpected");
628     // There are alloca()'s in this function, must reference off the frame
629     // pointer or base pointer instead.
630     if (!hasBasePointer(MF)) {
631       FrameReg = getFrameRegister(MF);
632       Offset -= AFI->getFramePtrSpillOffset();
633     } else
634       FrameReg = BasePtr;
635   }
636
637   // Special handling of dbg_value instructions.
638   if (MI.isDebugValue()) {
639     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
640     MI.getOperand(i+1).ChangeToImmediate(Offset);
641     return;
642   }
643
644   // Modify MI as necessary to handle as much of 'Offset' as possible
645   assert(AFI->isThumbFunction() &&
646          "This eliminateFrameIndex only supports Thumb1!");
647   if (rewriteFrameIndex(MI, i, FrameReg, Offset, TII))
648     return;
649
650   // If we get here, the immediate doesn't fit into the instruction.  We folded
651   // as much as possible above, handle the rest, providing a register that is
652   // SP+LargeImm.
653   assert(Offset && "This code isn't needed if offset already handled!");
654
655   unsigned Opcode = MI.getOpcode();
656   const TargetInstrDesc &Desc = MI.getDesc();
657
658   // Remove predicate first.
659   int PIdx = MI.findFirstPredOperandIdx();
660   if (PIdx != -1)
661     removeOperands(MI, PIdx);
662
663   if (Desc.mayLoad()) {
664     // Use the destination register to materialize sp + offset.
665     unsigned TmpReg = MI.getOperand(0).getReg();
666     bool UseRR = false;
667     if (Opcode == ARM::tRestore) {
668       if (FrameReg == ARM::SP)
669         emitThumbRegPlusImmInReg(MBB, II, dl, TmpReg, FrameReg,
670                                  Offset, false, TII, *this);
671       else {
672         emitLoadConstPool(MBB, II, dl, TmpReg, 0, Offset);
673         UseRR = true;
674       }
675     } else {
676       emitThumbRegPlusImmediate(MBB, II, dl, TmpReg, FrameReg, Offset, TII,
677                                 *this);
678     }
679
680     MI.setDesc(TII.get(UseRR ? ARM::tLDRr : ARM::tLDRi));
681     MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
682     if (UseRR)
683       // Use [reg, reg] addrmode. Replace the immediate operand w/ the frame
684       // register. The offset is already handled in the vreg value.
685       MI.getOperand(i+1).ChangeToRegister(FrameReg, false, false, false);
686   } else if (Desc.mayStore()) {
687       VReg = MF.getRegInfo().createVirtualRegister(ARM::tGPRRegisterClass);
688       bool UseRR = false;
689
690       if (Opcode == ARM::tSpill) {
691         if (FrameReg == ARM::SP)
692           emitThumbRegPlusImmInReg(MBB, II, dl, VReg, FrameReg,
693                                    Offset, false, TII, *this);
694         else {
695           emitLoadConstPool(MBB, II, dl, VReg, 0, Offset);
696           UseRR = true;
697         }
698       } else
699         emitThumbRegPlusImmediate(MBB, II, dl, VReg, FrameReg, Offset, TII,
700                                   *this);
701       MI.setDesc(TII.get(UseRR ? ARM::tSTRr : ARM::tSTRi));
702       MI.getOperand(i).ChangeToRegister(VReg, false, false, true);
703       if (UseRR)
704         // Use [reg, reg] addrmode. Replace the immediate operand w/ the frame
705         // register. The offset is already handled in the vreg value.
706         MI.getOperand(i+1).ChangeToRegister(FrameReg, false, false, false);
707   } else {
708     assert(false && "Unexpected opcode!");
709   }
710
711   // Add predicate back if it's needed.
712   if (MI.getDesc().isPredicable()) {
713     MachineInstrBuilder MIB(&MI);
714     AddDefaultPred(MIB);
715   }
716 }