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