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