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