Use direct types in Sparc def : Pat patterns.
[oota-llvm.git] / lib / Target / ARM / ARMBaseRegisterInfo.cpp
1 //===-- ARMBaseRegisterInfo.cpp - ARM Register Information ----------------===//
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 base ARM implementation of TargetRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMBaseRegisterInfo.h"
15 #include "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMFrameLowering.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SmallVector.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/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetFrameLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40
41 #define GET_REGINFO_TARGET_DESC
42 #include "ARMGenRegisterInfo.inc"
43
44 using namespace llvm;
45
46 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
47                                          const ARMSubtarget &sti)
48   : ARMGenRegisterInfo(ARM::LR, 0, 0, ARM::PC), TII(tii), STI(sti),
49     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
50     BasePtr(ARM::R6) {
51 }
52
53 const uint16_t*
54 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
55   bool ghcCall = false;
56  
57   if (MF) {
58     const Function *F = MF->getFunction();
59     ghcCall = (F ? F->getCallingConv() == CallingConv::GHC : false);
60   }
61  
62   if (ghcCall) {
63       return CSR_GHC_SaveList;
64   }
65   else {
66   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
67     ? CSR_iOS_SaveList : CSR_AAPCS_SaveList;
68   }
69 }
70
71 const uint32_t*
72 ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
73   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
74     ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
75 }
76
77 const uint32_t*
78 ARMBaseRegisterInfo::getNoPreservedMask() const {
79   return CSR_NoRegs_RegMask;
80 }
81
82 BitVector ARMBaseRegisterInfo::
83 getReservedRegs(const MachineFunction &MF) const {
84   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
85
86   // FIXME: avoid re-calculating this every time.
87   BitVector Reserved(getNumRegs());
88   Reserved.set(ARM::SP);
89   Reserved.set(ARM::PC);
90   Reserved.set(ARM::FPSCR);
91   if (TFI->hasFP(MF))
92     Reserved.set(FramePtr);
93   if (hasBasePointer(MF))
94     Reserved.set(BasePtr);
95   // Some targets reserve R9.
96   if (STI.isR9Reserved())
97     Reserved.set(ARM::R9);
98   // Reserve D16-D31 if the subtarget doesn't support them.
99   if (!STI.hasVFP3() || STI.hasD16()) {
100     assert(ARM::D31 == ARM::D16 + 15);
101     for (unsigned i = 0; i != 16; ++i)
102       Reserved.set(ARM::D16 + i);
103   }
104   const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
105   for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
106     for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
107       if (Reserved.test(*SI)) Reserved.set(*I);
108
109   return Reserved;
110 }
111
112 const TargetRegisterClass*
113 ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
114                                                                          const {
115   const TargetRegisterClass *Super = RC;
116   TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
117   do {
118     switch (Super->getID()) {
119     case ARM::GPRRegClassID:
120     case ARM::SPRRegClassID:
121     case ARM::DPRRegClassID:
122     case ARM::QPRRegClassID:
123     case ARM::QQPRRegClassID:
124     case ARM::QQQQPRRegClassID:
125     case ARM::GPRPairRegClassID:
126       return Super;
127     }
128     Super = *I++;
129   } while (Super);
130   return RC;
131 }
132
133 const TargetRegisterClass *
134 ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
135                                                                          const {
136   return &ARM::GPRRegClass;
137 }
138
139 const TargetRegisterClass *
140 ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
141   if (RC == &ARM::CCRRegClass)
142     return 0;  // Can't copy CCR registers.
143   return RC;
144 }
145
146 unsigned
147 ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
148                                          MachineFunction &MF) const {
149   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
150
151   switch (RC->getID()) {
152   default:
153     return 0;
154   case ARM::tGPRRegClassID:
155     return TFI->hasFP(MF) ? 4 : 5;
156   case ARM::GPRRegClassID: {
157     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
158     return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
159   }
160   case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
161   case ARM::DPRRegClassID:
162     return 32 - 10;
163   }
164 }
165
166 // Get the other register in a GPRPair.
167 static unsigned getPairedGPR(unsigned Reg, bool Odd, const MCRegisterInfo *RI) {
168   for (MCSuperRegIterator Supers(Reg, RI); Supers.isValid(); ++Supers)
169     if (ARM::GPRPairRegClass.contains(*Supers))
170       return RI->getSubReg(*Supers, Odd ? ARM::gsub_1 : ARM::gsub_0);
171   return 0;
172 }
173
174 // Resolve the RegPairEven / RegPairOdd register allocator hints.
175 void
176 ARMBaseRegisterInfo::getRegAllocationHints(unsigned VirtReg,
177                                            ArrayRef<MCPhysReg> Order,
178                                            SmallVectorImpl<MCPhysReg> &Hints,
179                                            const MachineFunction &MF,
180                                            const VirtRegMap *VRM) const {
181   const MachineRegisterInfo &MRI = MF.getRegInfo();
182   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
183
184   unsigned Odd;
185   switch (Hint.first) {
186   case ARMRI::RegPairEven:
187     Odd = 0;
188     break;
189   case ARMRI::RegPairOdd:
190     Odd = 1;
191     break;
192   default:
193     TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);
194     return;
195   }
196
197   // This register should preferably be even (Odd == 0) or odd (Odd == 1).
198   // Check if the other part of the pair has already been assigned, and provide
199   // the paired register as the first hint.
200   unsigned PairedPhys = 0;
201   if (VRM && VRM->hasPhys(Hint.second)) {
202     PairedPhys = getPairedGPR(VRM->getPhys(Hint.second), Odd, this);
203     if (PairedPhys && MRI.isReserved(PairedPhys))
204       PairedPhys = 0;
205   }
206
207   // First prefer the paired physreg.
208   if (PairedPhys &&
209       std::find(Order.begin(), Order.end(), PairedPhys) != Order.end())
210     Hints.push_back(PairedPhys);
211
212   // Then prefer even or odd registers.
213   for (unsigned I = 0, E = Order.size(); I != E; ++I) {
214     unsigned Reg = Order[I];
215     if (Reg == PairedPhys || (getEncodingValue(Reg) & 1) != Odd)
216       continue;
217     // Don't provide hints that are paired to a reserved register.
218     unsigned Paired = getPairedGPR(Reg, !Odd, this);
219     if (!Paired || MRI.isReserved(Paired))
220       continue;
221     Hints.push_back(Reg);
222   }
223 }
224
225 void
226 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
227                                         MachineFunction &MF) const {
228   MachineRegisterInfo *MRI = &MF.getRegInfo();
229   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
230   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
231        Hint.first == (unsigned)ARMRI::RegPairEven) &&
232       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
233     // If 'Reg' is one of the even / odd register pair and it's now changed
234     // (e.g. coalesced) into a different register. The other register of the
235     // pair allocation hint must be updated to reflect the relationship
236     // change.
237     unsigned OtherReg = Hint.second;
238     Hint = MRI->getRegAllocationHint(OtherReg);
239     if (Hint.second == Reg)
240       // Make sure the pair has not already divorced.
241       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
242   }
243 }
244
245 bool
246 ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
247   // CortexA9 has a Write-after-write hazard for NEON registers.
248   if (!STI.isLikeA9())
249     return false;
250
251   switch (RC->getID()) {
252   case ARM::DPRRegClassID:
253   case ARM::DPR_8RegClassID:
254   case ARM::DPR_VFP2RegClassID:
255   case ARM::QPRRegClassID:
256   case ARM::QPR_8RegClassID:
257   case ARM::QPR_VFP2RegClassID:
258   case ARM::SPRRegClassID:
259   case ARM::SPR_8RegClassID:
260     // Avoid reusing S, D, and Q registers.
261     // Don't increase register pressure for QQ and QQQQ.
262     return true;
263   default:
264     return false;
265   }
266 }
267
268 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
269   const MachineFrameInfo *MFI = MF.getFrameInfo();
270   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
271   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
272
273   // When outgoing call frames are so large that we adjust the stack pointer
274   // around the call, we can no longer use the stack pointer to reach the
275   // emergency spill slot.
276   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
277     return true;
278
279   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
280   // negative range for ldr/str (255), and thumb1 is positive offsets only.
281   // It's going to be better to use the SP or Base Pointer instead. When there
282   // are variable sized objects, we can't reference off of the SP, so we
283   // reserve a Base Pointer.
284   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
285     // Conservatively estimate whether the negative offset from the frame
286     // pointer will be sufficient to reach. If a function has a smallish
287     // frame, it's less likely to have lots of spills and callee saved
288     // space, so it's all more likely to be within range of the frame pointer.
289     // If it's wrong, the scavenger will still enable access to work, it just
290     // won't be optimal.
291     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
292       return false;
293     return true;
294   }
295
296   return false;
297 }
298
299 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
300   const MachineRegisterInfo *MRI = &MF.getRegInfo();
301   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
302   // We can't realign the stack if:
303   // 1. Dynamic stack realignment is explicitly disabled,
304   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
305   // 3. There are VLAs in the function and the base pointer is disabled.
306   if (!MF.getTarget().Options.RealignStack)
307     return false;
308   if (AFI->isThumb1OnlyFunction())
309     return false;
310   // Stack realignment requires a frame pointer.  If we already started
311   // register allocation with frame pointer elimination, it is too late now.
312   if (!MRI->canReserveReg(FramePtr))
313     return false;
314   // We may also need a base pointer if there are dynamic allocas or stack
315   // pointer adjustments around calls.
316   if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
317     return true;
318   // A base pointer is required and allowed.  Check that it isn't too late to
319   // reserve it.
320   return MRI->canReserveReg(BasePtr);
321 }
322
323 bool ARMBaseRegisterInfo::
324 needsStackRealignment(const MachineFunction &MF) const {
325   const MachineFrameInfo *MFI = MF.getFrameInfo();
326   const Function *F = MF.getFunction();
327   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
328   bool requiresRealignment =
329     ((MFI->getMaxAlignment() > StackAlign) ||
330      F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
331                                      Attribute::StackAlignment));
332
333   return requiresRealignment && canRealignStack(MF);
334 }
335
336 bool ARMBaseRegisterInfo::
337 cannotEliminateFrame(const MachineFunction &MF) const {
338   const MachineFrameInfo *MFI = MF.getFrameInfo();
339   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
340     return true;
341   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
342     || needsStackRealignment(MF);
343 }
344
345 unsigned
346 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
347   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
348
349   if (TFI->hasFP(MF))
350     return FramePtr;
351   return ARM::SP;
352 }
353
354 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
355   llvm_unreachable("What is the exception register");
356 }
357
358 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
359   llvm_unreachable("What is the exception handler register");
360 }
361
362 /// emitLoadConstPool - Emits a load from constpool to materialize the
363 /// specified immediate.
364 void ARMBaseRegisterInfo::
365 emitLoadConstPool(MachineBasicBlock &MBB,
366                   MachineBasicBlock::iterator &MBBI,
367                   DebugLoc dl,
368                   unsigned DestReg, unsigned SubIdx, int Val,
369                   ARMCC::CondCodes Pred,
370                   unsigned PredReg, unsigned MIFlags) const {
371   MachineFunction &MF = *MBB.getParent();
372   MachineConstantPool *ConstantPool = MF.getConstantPool();
373   const Constant *C =
374         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
375   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
376
377   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
378     .addReg(DestReg, getDefRegState(true), SubIdx)
379     .addConstantPoolIndex(Idx)
380     .addImm(0).addImm(Pred).addReg(PredReg)
381     .setMIFlags(MIFlags);
382 }
383
384 bool ARMBaseRegisterInfo::
385 requiresRegisterScavenging(const MachineFunction &MF) const {
386   return true;
387 }
388
389 bool ARMBaseRegisterInfo::
390 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
391   return true;
392 }
393
394 bool ARMBaseRegisterInfo::
395 requiresFrameIndexScavenging(const MachineFunction &MF) const {
396   return true;
397 }
398
399 bool ARMBaseRegisterInfo::
400 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
401   return true;
402 }
403
404 int64_t ARMBaseRegisterInfo::
405 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
406   const MCInstrDesc &Desc = MI->getDesc();
407   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
408   int64_t InstrOffs = 0;
409   int Scale = 1;
410   unsigned ImmIdx = 0;
411   switch (AddrMode) {
412   case ARMII::AddrModeT2_i8:
413   case ARMII::AddrModeT2_i12:
414   case ARMII::AddrMode_i12:
415     InstrOffs = MI->getOperand(Idx+1).getImm();
416     Scale = 1;
417     break;
418   case ARMII::AddrMode5: {
419     // VFP address mode.
420     const MachineOperand &OffOp = MI->getOperand(Idx+1);
421     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
422     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
423       InstrOffs = -InstrOffs;
424     Scale = 4;
425     break;
426   }
427   case ARMII::AddrMode2: {
428     ImmIdx = Idx+2;
429     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
430     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
431       InstrOffs = -InstrOffs;
432     break;
433   }
434   case ARMII::AddrMode3: {
435     ImmIdx = Idx+2;
436     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
437     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
438       InstrOffs = -InstrOffs;
439     break;
440   }
441   case ARMII::AddrModeT1_s: {
442     ImmIdx = Idx+1;
443     InstrOffs = MI->getOperand(ImmIdx).getImm();
444     Scale = 4;
445     break;
446   }
447   default:
448     llvm_unreachable("Unsupported addressing mode!");
449   }
450
451   return InstrOffs * Scale;
452 }
453
454 /// needsFrameBaseReg - Returns true if the instruction's frame index
455 /// reference would be better served by a base register other than FP
456 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
457 /// references it should create new base registers for.
458 bool ARMBaseRegisterInfo::
459 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
460   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
461     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
462   }
463
464   // It's the load/store FI references that cause issues, as it can be difficult
465   // to materialize the offset if it won't fit in the literal field. Estimate
466   // based on the size of the local frame and some conservative assumptions
467   // about the rest of the stack frame (note, this is pre-regalloc, so
468   // we don't know everything for certain yet) whether this offset is likely
469   // to be out of range of the immediate. Return true if so.
470
471   // We only generate virtual base registers for loads and stores, so
472   // return false for everything else.
473   unsigned Opc = MI->getOpcode();
474   switch (Opc) {
475   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
476   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
477   case ARM::t2LDRi12: case ARM::t2LDRi8:
478   case ARM::t2STRi12: case ARM::t2STRi8:
479   case ARM::VLDRS: case ARM::VLDRD:
480   case ARM::VSTRS: case ARM::VSTRD:
481   case ARM::tSTRspi: case ARM::tLDRspi:
482     break;
483   default:
484     return false;
485   }
486
487   // Without a virtual base register, if the function has variable sized
488   // objects, all fixed-size local references will be via the frame pointer,
489   // Approximate the offset and see if it's legal for the instruction.
490   // Note that the incoming offset is based on the SP value at function entry,
491   // so it'll be negative.
492   MachineFunction &MF = *MI->getParent()->getParent();
493   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
494   MachineFrameInfo *MFI = MF.getFrameInfo();
495   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
496
497   // Estimate an offset from the frame pointer.
498   // Conservatively assume all callee-saved registers get pushed. R4-R6
499   // will be earlier than the FP, so we ignore those.
500   // R7, LR
501   int64_t FPOffset = Offset - 8;
502   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
503   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
504     FPOffset -= 80;
505   // Estimate an offset from the stack pointer.
506   // The incoming offset is relating to the SP at the start of the function,
507   // but when we access the local it'll be relative to the SP after local
508   // allocation, so adjust our SP-relative offset by that allocation size.
509   Offset = -Offset;
510   Offset += MFI->getLocalFrameSize();
511   // Assume that we'll have at least some spill slots allocated.
512   // FIXME: This is a total SWAG number. We should run some statistics
513   //        and pick a real one.
514   Offset += 128; // 128 bytes of spill slots
515
516   // If there is a frame pointer, try using it.
517   // The FP is only available if there is no dynamic realignment. We
518   // don't know for sure yet whether we'll need that, so we guess based
519   // on whether there are any local variables that would trigger it.
520   unsigned StackAlign = TFI->getStackAlignment();
521   if (TFI->hasFP(MF) &&
522       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
523     if (isFrameOffsetLegal(MI, FPOffset))
524       return false;
525   }
526   // If we can reference via the stack pointer, try that.
527   // FIXME: This (and the code that resolves the references) can be improved
528   //        to only disallow SP relative references in the live range of
529   //        the VLA(s). In practice, it's unclear how much difference that
530   //        would make, but it may be worth doing.
531   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
532     return false;
533
534   // The offset likely isn't legal, we want to allocate a virtual base register.
535   return true;
536 }
537
538 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
539 /// be a pointer to FrameIdx at the beginning of the basic block.
540 void ARMBaseRegisterInfo::
541 materializeFrameBaseRegister(MachineBasicBlock *MBB,
542                              unsigned BaseReg, int FrameIdx,
543                              int64_t Offset) const {
544   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
545   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
546     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
547
548   MachineBasicBlock::iterator Ins = MBB->begin();
549   DebugLoc DL;                  // Defaults to "unknown"
550   if (Ins != MBB->end())
551     DL = Ins->getDebugLoc();
552
553   const MCInstrDesc &MCID = TII.get(ADDriOpc);
554   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
555   const MachineFunction &MF = *MBB->getParent();
556   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
557
558   MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
559     .addFrameIndex(FrameIdx).addImm(Offset));
560
561   if (!AFI->isThumb1OnlyFunction())
562     AddDefaultCC(MIB);
563 }
564
565 void
566 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
567                                        unsigned BaseReg, int64_t Offset) const {
568   MachineInstr &MI = *I;
569   MachineBasicBlock &MBB = *MI.getParent();
570   MachineFunction &MF = *MBB.getParent();
571   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
572   int Off = Offset; // ARM doesn't need the general 64-bit offsets
573   unsigned i = 0;
574
575   assert(!AFI->isThumb1OnlyFunction() &&
576          "This resolveFrameIndex does not support Thumb1!");
577
578   while (!MI.getOperand(i).isFI()) {
579     ++i;
580     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
581   }
582   bool Done = false;
583   if (!AFI->isThumbFunction())
584     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
585   else {
586     assert(AFI->isThumb2Function());
587     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
588   }
589   assert (Done && "Unable to resolve frame index!");
590   (void)Done;
591 }
592
593 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
594                                              int64_t Offset) const {
595   const MCInstrDesc &Desc = MI->getDesc();
596   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
597   unsigned i = 0;
598
599   while (!MI->getOperand(i).isFI()) {
600     ++i;
601     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
602   }
603
604   // AddrMode4 and AddrMode6 cannot handle any offset.
605   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
606     return Offset == 0;
607
608   unsigned NumBits = 0;
609   unsigned Scale = 1;
610   bool isSigned = true;
611   switch (AddrMode) {
612   case ARMII::AddrModeT2_i8:
613   case ARMII::AddrModeT2_i12:
614     // i8 supports only negative, and i12 supports only positive, so
615     // based on Offset sign, consider the appropriate instruction
616     Scale = 1;
617     if (Offset < 0) {
618       NumBits = 8;
619       Offset = -Offset;
620     } else {
621       NumBits = 12;
622     }
623     break;
624   case ARMII::AddrMode5:
625     // VFP address mode.
626     NumBits = 8;
627     Scale = 4;
628     break;
629   case ARMII::AddrMode_i12:
630   case ARMII::AddrMode2:
631     NumBits = 12;
632     break;
633   case ARMII::AddrMode3:
634     NumBits = 8;
635     break;
636   case ARMII::AddrModeT1_s:
637     NumBits = 5;
638     Scale = 4;
639     isSigned = false;
640     break;
641   default:
642     llvm_unreachable("Unsupported addressing mode!");
643   }
644
645   Offset += getFrameIndexInstrOffset(MI, i);
646   // Make sure the offset is encodable for instructions that scale the
647   // immediate.
648   if ((Offset & (Scale-1)) != 0)
649     return false;
650
651   if (isSigned && Offset < 0)
652     Offset = -Offset;
653
654   unsigned Mask = (1 << NumBits) - 1;
655   if ((unsigned)Offset <= Mask * Scale)
656     return true;
657
658   return false;
659 }
660
661 void
662 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
663                                          int SPAdj, unsigned FIOperandNum,
664                                          RegScavenger *RS) const {
665   MachineInstr &MI = *II;
666   MachineBasicBlock &MBB = *MI.getParent();
667   MachineFunction &MF = *MBB.getParent();
668   const ARMFrameLowering *TFI =
669     static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
670   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
671   assert(!AFI->isThumb1OnlyFunction() &&
672          "This eliminateFrameIndex does not support Thumb1!");
673   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
674   unsigned FrameReg;
675
676   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
677
678   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
679   // call frame setup/destroy instructions have already been eliminated.  That
680   // means the stack pointer cannot be used to access the emergency spill slot
681   // when !hasReservedCallFrame().
682 #ifndef NDEBUG
683   if (RS && FrameReg == ARM::SP && RS->isScavengingFrameIndex(FrameIndex)){
684     assert(TFI->hasReservedCallFrame(MF) &&
685            "Cannot use SP to access the emergency spill slot in "
686            "functions without a reserved call frame");
687     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
688            "Cannot use SP to access the emergency spill slot in "
689            "functions with variable sized frame objects");
690   }
691 #endif // NDEBUG
692
693   // Special handling of dbg_value instructions.
694   if (MI.isDebugValue()) {
695     MI.getOperand(FIOperandNum).  ChangeToRegister(FrameReg, false /*isDef*/);
696     MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset);
697     return;
698   }
699
700   // Modify MI as necessary to handle as much of 'Offset' as possible
701   bool Done = false;
702   if (!AFI->isThumbFunction())
703     Done = rewriteARMFrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
704   else {
705     assert(AFI->isThumb2Function());
706     Done = rewriteT2FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
707   }
708   if (Done)
709     return;
710
711   // If we get here, the immediate doesn't fit into the instruction.  We folded
712   // as much as possible above, handle the rest, providing a register that is
713   // SP+LargeImm.
714   assert((Offset ||
715           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
716           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
717          "This code isn't needed if offset already handled!");
718
719   unsigned ScratchReg = 0;
720   int PIdx = MI.findFirstPredOperandIdx();
721   ARMCC::CondCodes Pred = (PIdx == -1)
722     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
723   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
724   if (Offset == 0)
725     // Must be addrmode4/6.
726     MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false, false, false);
727   else {
728     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
729     if (!AFI->isThumbFunction())
730       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
731                               Offset, Pred, PredReg, TII);
732     else {
733       assert(AFI->isThumb2Function());
734       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
735                              Offset, Pred, PredReg, TII);
736     }
737     // Update the original instruction to use the scratch register.
738     MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false,true);
739   }
740 }