Have getCalleeSavedRegs take a non-null MachineFunction all the
[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 DEBUG_TYPE "arm-register-info"
42
43 #define GET_REGINFO_TARGET_DESC
44 #include "ARMGenRegisterInfo.inc"
45
46 using namespace llvm;
47
48 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMSubtarget &sti)
49     : ARMGenRegisterInfo(ARM::LR, 0, 0, ARM::PC), STI(sti), BasePtr(ARM::R6) {
50   if (STI.isTargetMachO()) {
51     if (STI.isTargetDarwin() || STI.isThumb1Only())
52       FramePtr = ARM::R7;
53     else
54       FramePtr = ARM::R11;
55   } else if (STI.isTargetWindows())
56     FramePtr = ARM::R11;
57   else // ARM EABI
58     FramePtr = STI.isThumb() ? ARM::R7 : ARM::R11;
59 }
60
61 const MCPhysReg*
62 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
63   const MCPhysReg *RegList =
64       STI.isTargetDarwin() ? CSR_iOS_SaveList : CSR_AAPCS_SaveList;
65
66   const Function *F = MF->getFunction();
67   if (F->getCallingConv() == CallingConv::GHC) {
68     // GHC set of callee saved regs is empty as all those regs are
69     // used for passing STG regs around
70     return CSR_NoRegs_SaveList;
71   } else if (F->hasFnAttribute("interrupt")) {
72     if (STI.isMClass()) {
73       // M-class CPUs have hardware which saves the registers needed to allow a
74       // function conforming to the AAPCS to function as a handler.
75       return CSR_AAPCS_SaveList;
76     } else if (F->getFnAttribute("interrupt").getValueAsString() == "FIQ") {
77       // Fast interrupt mode gives the handler a private copy of R8-R14, so less
78       // need to be saved to restore user-mode state.
79       return CSR_FIQ_SaveList;
80     } else {
81       // Generally only R13-R14 (i.e. SP, LR) are automatically preserved by
82       // exception handling.
83       return CSR_GenericInt_SaveList;
84     }
85   }
86
87   return RegList;
88 }
89
90 const uint32_t*
91 ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
92   if (CC == CallingConv::GHC)
93     // This is academic becase all GHC calls are (supposed to be) tail calls
94     return CSR_NoRegs_RegMask;
95   return STI.isTargetDarwin() ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
96 }
97
98 const uint32_t*
99 ARMBaseRegisterInfo::getNoPreservedMask() const {
100   return CSR_NoRegs_RegMask;
101 }
102
103 const uint32_t*
104 ARMBaseRegisterInfo::getThisReturnPreservedMask(CallingConv::ID CC) const {
105   // This should return a register mask that is the same as that returned by
106   // getCallPreservedMask but that additionally preserves the register used for
107   // the first i32 argument (which must also be the register used to return a
108   // single i32 return value)
109   //
110   // In case that the calling convention does not use the same register for
111   // both or otherwise does not want to enable this optimization, the function
112   // should return NULL
113   if (CC == CallingConv::GHC)
114     // This is academic becase all GHC calls are (supposed to be) tail calls
115     return nullptr;
116   return STI.isTargetDarwin() ? CSR_iOS_ThisReturn_RegMask
117                               : CSR_AAPCS_ThisReturn_RegMask;
118 }
119
120 BitVector ARMBaseRegisterInfo::
121 getReservedRegs(const MachineFunction &MF) const {
122   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
123
124   // FIXME: avoid re-calculating this every time.
125   BitVector Reserved(getNumRegs());
126   Reserved.set(ARM::SP);
127   Reserved.set(ARM::PC);
128   Reserved.set(ARM::FPSCR);
129   Reserved.set(ARM::APSR_NZCV);
130   if (TFI->hasFP(MF))
131     Reserved.set(FramePtr);
132   if (hasBasePointer(MF))
133     Reserved.set(BasePtr);
134   // Some targets reserve R9.
135   if (STI.isR9Reserved())
136     Reserved.set(ARM::R9);
137   // Reserve D16-D31 if the subtarget doesn't support them.
138   if (!STI.hasVFP3() || STI.hasD16()) {
139     assert(ARM::D31 == ARM::D16 + 15);
140     for (unsigned i = 0; i != 16; ++i)
141       Reserved.set(ARM::D16 + i);
142   }
143   const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
144   for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
145     for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
146       if (Reserved.test(*SI)) Reserved.set(*I);
147
148   return Reserved;
149 }
150
151 const TargetRegisterClass *
152 ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
153                                                const MachineFunction &) const {
154   const TargetRegisterClass *Super = RC;
155   TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
156   do {
157     switch (Super->getID()) {
158     case ARM::GPRRegClassID:
159     case ARM::SPRRegClassID:
160     case ARM::DPRRegClassID:
161     case ARM::QPRRegClassID:
162     case ARM::QQPRRegClassID:
163     case ARM::QQQQPRRegClassID:
164     case ARM::GPRPairRegClassID:
165       return Super;
166     }
167     Super = *I++;
168   } while (Super);
169   return RC;
170 }
171
172 const TargetRegisterClass *
173 ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
174                                                                          const {
175   return &ARM::GPRRegClass;
176 }
177
178 const TargetRegisterClass *
179 ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
180   if (RC == &ARM::CCRRegClass)
181     return &ARM::rGPRRegClass;  // Can't copy CCR registers.
182   return RC;
183 }
184
185 unsigned
186 ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
187                                          MachineFunction &MF) const {
188   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
189
190   switch (RC->getID()) {
191   default:
192     return 0;
193   case ARM::tGPRRegClassID:
194     return TFI->hasFP(MF) ? 4 : 5;
195   case ARM::GPRRegClassID: {
196     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
197     return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
198   }
199   case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
200   case ARM::DPRRegClassID:
201     return 32 - 10;
202   }
203 }
204
205 // Get the other register in a GPRPair.
206 static unsigned getPairedGPR(unsigned Reg, bool Odd, const MCRegisterInfo *RI) {
207   for (MCSuperRegIterator Supers(Reg, RI); Supers.isValid(); ++Supers)
208     if (ARM::GPRPairRegClass.contains(*Supers))
209       return RI->getSubReg(*Supers, Odd ? ARM::gsub_1 : ARM::gsub_0);
210   return 0;
211 }
212
213 // Resolve the RegPairEven / RegPairOdd register allocator hints.
214 void
215 ARMBaseRegisterInfo::getRegAllocationHints(unsigned VirtReg,
216                                            ArrayRef<MCPhysReg> Order,
217                                            SmallVectorImpl<MCPhysReg> &Hints,
218                                            const MachineFunction &MF,
219                                            const VirtRegMap *VRM) const {
220   const MachineRegisterInfo &MRI = MF.getRegInfo();
221   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
222
223   unsigned Odd;
224   switch (Hint.first) {
225   case ARMRI::RegPairEven:
226     Odd = 0;
227     break;
228   case ARMRI::RegPairOdd:
229     Odd = 1;
230     break;
231   default:
232     TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);
233     return;
234   }
235
236   // This register should preferably be even (Odd == 0) or odd (Odd == 1).
237   // Check if the other part of the pair has already been assigned, and provide
238   // the paired register as the first hint.
239   unsigned PairedPhys = 0;
240   if (VRM && VRM->hasPhys(Hint.second)) {
241     PairedPhys = getPairedGPR(VRM->getPhys(Hint.second), Odd, this);
242     if (PairedPhys && MRI.isReserved(PairedPhys))
243       PairedPhys = 0;
244   }
245
246   // First prefer the paired physreg.
247   if (PairedPhys &&
248       std::find(Order.begin(), Order.end(), PairedPhys) != Order.end())
249     Hints.push_back(PairedPhys);
250
251   // Then prefer even or odd registers.
252   for (unsigned I = 0, E = Order.size(); I != E; ++I) {
253     unsigned Reg = Order[I];
254     if (Reg == PairedPhys || (getEncodingValue(Reg) & 1) != Odd)
255       continue;
256     // Don't provide hints that are paired to a reserved register.
257     unsigned Paired = getPairedGPR(Reg, !Odd, this);
258     if (!Paired || MRI.isReserved(Paired))
259       continue;
260     Hints.push_back(Reg);
261   }
262 }
263
264 void
265 ARMBaseRegisterInfo::updateRegAllocHint(unsigned Reg, unsigned NewReg,
266                                         MachineFunction &MF) const {
267   MachineRegisterInfo *MRI = &MF.getRegInfo();
268   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
269   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
270        Hint.first == (unsigned)ARMRI::RegPairEven) &&
271       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
272     // If 'Reg' is one of the even / odd register pair and it's now changed
273     // (e.g. coalesced) into a different register. The other register of the
274     // pair allocation hint must be updated to reflect the relationship
275     // change.
276     unsigned OtherReg = Hint.second;
277     Hint = MRI->getRegAllocationHint(OtherReg);
278     if (Hint.second == Reg)
279       // Make sure the pair has not already divorced.
280       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
281   }
282 }
283
284 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
285   const MachineFrameInfo *MFI = MF.getFrameInfo();
286   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
287   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
288
289   // When outgoing call frames are so large that we adjust the stack pointer
290   // around the call, we can no longer use the stack pointer to reach the
291   // emergency spill slot.
292   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
293     return true;
294
295   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
296   // negative range for ldr/str (255), and thumb1 is positive offsets only.
297   // It's going to be better to use the SP or Base Pointer instead. When there
298   // are variable sized objects, we can't reference off of the SP, so we
299   // reserve a Base Pointer.
300   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
301     // Conservatively estimate whether the negative offset from the frame
302     // pointer will be sufficient to reach. If a function has a smallish
303     // frame, it's less likely to have lots of spills and callee saved
304     // space, so it's all more likely to be within range of the frame pointer.
305     // If it's wrong, the scavenger will still enable access to work, it just
306     // won't be optimal.
307     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
308       return false;
309     return true;
310   }
311
312   return false;
313 }
314
315 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
316   const MachineRegisterInfo *MRI = &MF.getRegInfo();
317   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
318   // We can't realign the stack if:
319   // 1. Dynamic stack realignment is explicitly disabled,
320   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
321   // 3. There are VLAs in the function and the base pointer is disabled.
322   if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
323     return false;
324   if (AFI->isThumb1OnlyFunction())
325     return false;
326   // Stack realignment requires a frame pointer.  If we already started
327   // register allocation with frame pointer elimination, it is too late now.
328   if (!MRI->canReserveReg(FramePtr))
329     return false;
330   // We may also need a base pointer if there are dynamic allocas or stack
331   // pointer adjustments around calls.
332   if (MF.getSubtarget().getFrameLowering()->hasReservedCallFrame(MF))
333     return true;
334   // A base pointer is required and allowed.  Check that it isn't too late to
335   // reserve it.
336   return MRI->canReserveReg(BasePtr);
337 }
338
339 bool ARMBaseRegisterInfo::
340 needsStackRealignment(const MachineFunction &MF) const {
341   const MachineFrameInfo *MFI = MF.getFrameInfo();
342   const Function *F = MF.getFunction();
343   unsigned StackAlign =
344       MF.getSubtarget().getFrameLowering()->getStackAlignment();
345   bool requiresRealignment = ((MFI->getMaxAlignment() > StackAlign) ||
346                               F->hasFnAttribute(Attribute::StackAlignment));
347
348   return requiresRealignment && canRealignStack(MF);
349 }
350
351 bool ARMBaseRegisterInfo::
352 cannotEliminateFrame(const MachineFunction &MF) const {
353   const MachineFrameInfo *MFI = MF.getFrameInfo();
354   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
355     return true;
356   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
357     || needsStackRealignment(MF);
358 }
359
360 unsigned
361 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
362   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
363
364   if (TFI->hasFP(MF))
365     return FramePtr;
366   return ARM::SP;
367 }
368
369 /// emitLoadConstPool - Emits a load from constpool to materialize the
370 /// specified immediate.
371 void ARMBaseRegisterInfo::
372 emitLoadConstPool(MachineBasicBlock &MBB,
373                   MachineBasicBlock::iterator &MBBI,
374                   DebugLoc dl,
375                   unsigned DestReg, unsigned SubIdx, int Val,
376                   ARMCC::CondCodes Pred,
377                   unsigned PredReg, unsigned MIFlags) const {
378   MachineFunction &MF = *MBB.getParent();
379   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
380   MachineConstantPool *ConstantPool = MF.getConstantPool();
381   const Constant *C =
382         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
383   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
384
385   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
386     .addReg(DestReg, getDefRegState(true), SubIdx)
387     .addConstantPoolIndex(Idx)
388     .addImm(0).addImm(Pred).addReg(PredReg)
389     .setMIFlags(MIFlags);
390 }
391
392 bool ARMBaseRegisterInfo::
393 requiresRegisterScavenging(const MachineFunction &MF) const {
394   return true;
395 }
396
397 bool ARMBaseRegisterInfo::
398 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
399   return true;
400 }
401
402 bool ARMBaseRegisterInfo::
403 requiresFrameIndexScavenging(const MachineFunction &MF) const {
404   return true;
405 }
406
407 bool ARMBaseRegisterInfo::
408 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
409   return true;
410 }
411
412 int64_t ARMBaseRegisterInfo::
413 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
414   const MCInstrDesc &Desc = MI->getDesc();
415   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
416   int64_t InstrOffs = 0;
417   int Scale = 1;
418   unsigned ImmIdx = 0;
419   switch (AddrMode) {
420   case ARMII::AddrModeT2_i8:
421   case ARMII::AddrModeT2_i12:
422   case ARMII::AddrMode_i12:
423     InstrOffs = MI->getOperand(Idx+1).getImm();
424     Scale = 1;
425     break;
426   case ARMII::AddrMode5: {
427     // VFP address mode.
428     const MachineOperand &OffOp = MI->getOperand(Idx+1);
429     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
430     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
431       InstrOffs = -InstrOffs;
432     Scale = 4;
433     break;
434   }
435   case ARMII::AddrMode2: {
436     ImmIdx = Idx+2;
437     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
438     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
439       InstrOffs = -InstrOffs;
440     break;
441   }
442   case ARMII::AddrMode3: {
443     ImmIdx = Idx+2;
444     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
445     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
446       InstrOffs = -InstrOffs;
447     break;
448   }
449   case ARMII::AddrModeT1_s: {
450     ImmIdx = Idx+1;
451     InstrOffs = MI->getOperand(ImmIdx).getImm();
452     Scale = 4;
453     break;
454   }
455   default:
456     llvm_unreachable("Unsupported addressing mode!");
457   }
458
459   return InstrOffs * Scale;
460 }
461
462 /// needsFrameBaseReg - Returns true if the instruction's frame index
463 /// reference would be better served by a base register other than FP
464 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
465 /// references it should create new base registers for.
466 bool ARMBaseRegisterInfo::
467 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
468   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
469     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
470   }
471
472   // It's the load/store FI references that cause issues, as it can be difficult
473   // to materialize the offset if it won't fit in the literal field. Estimate
474   // based on the size of the local frame and some conservative assumptions
475   // about the rest of the stack frame (note, this is pre-regalloc, so
476   // we don't know everything for certain yet) whether this offset is likely
477   // to be out of range of the immediate. Return true if so.
478
479   // We only generate virtual base registers for loads and stores, so
480   // return false for everything else.
481   unsigned Opc = MI->getOpcode();
482   switch (Opc) {
483   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
484   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
485   case ARM::t2LDRi12: case ARM::t2LDRi8:
486   case ARM::t2STRi12: case ARM::t2STRi8:
487   case ARM::VLDRS: case ARM::VLDRD:
488   case ARM::VSTRS: case ARM::VSTRD:
489   case ARM::tSTRspi: case ARM::tLDRspi:
490     break;
491   default:
492     return false;
493   }
494
495   // Without a virtual base register, if the function has variable sized
496   // objects, all fixed-size local references will be via the frame pointer,
497   // Approximate the offset and see if it's legal for the instruction.
498   // Note that the incoming offset is based on the SP value at function entry,
499   // so it'll be negative.
500   MachineFunction &MF = *MI->getParent()->getParent();
501   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
502   MachineFrameInfo *MFI = MF.getFrameInfo();
503   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
504
505   // Estimate an offset from the frame pointer.
506   // Conservatively assume all callee-saved registers get pushed. R4-R6
507   // will be earlier than the FP, so we ignore those.
508   // R7, LR
509   int64_t FPOffset = Offset - 8;
510   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
511   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
512     FPOffset -= 80;
513   // Estimate an offset from the stack pointer.
514   // The incoming offset is relating to the SP at the start of the function,
515   // but when we access the local it'll be relative to the SP after local
516   // allocation, so adjust our SP-relative offset by that allocation size.
517   Offset = -Offset;
518   Offset += MFI->getLocalFrameSize();
519   // Assume that we'll have at least some spill slots allocated.
520   // FIXME: This is a total SWAG number. We should run some statistics
521   //        and pick a real one.
522   Offset += 128; // 128 bytes of spill slots
523
524   // If there's a frame pointer and the addressing mode allows it, try using it.
525   // The FP is only available if there is no dynamic realignment. We
526   // don't know for sure yet whether we'll need that, so we guess based
527   // on whether there are any local variables that would trigger it.
528   unsigned StackAlign = TFI->getStackAlignment();
529   if (TFI->hasFP(MF) && 
530       (MI->getDesc().TSFlags & ARMII::AddrModeMask) != ARMII::AddrModeT1_s &&
531       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
532     if (isFrameOffsetLegal(MI, FPOffset))
533       return false;
534   }
535   // If we can reference via the stack pointer, try that.
536   // FIXME: This (and the code that resolves the references) can be improved
537   //        to only disallow SP relative references in the live range of
538   //        the VLA(s). In practice, it's unclear how much difference that
539   //        would make, but it may be worth doing.
540   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
541     return false;
542
543   // The offset likely isn't legal, we want to allocate a virtual base register.
544   return true;
545 }
546
547 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
548 /// be a pointer to FrameIdx at the beginning of the basic block.
549 void ARMBaseRegisterInfo::
550 materializeFrameBaseRegister(MachineBasicBlock *MBB,
551                              unsigned BaseReg, int FrameIdx,
552                              int64_t Offset) const {
553   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
554   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
555     (AFI->isThumb1OnlyFunction() ? ARM::tADDframe : ARM::t2ADDri);
556
557   MachineBasicBlock::iterator Ins = MBB->begin();
558   DebugLoc DL;                  // Defaults to "unknown"
559   if (Ins != MBB->end())
560     DL = Ins->getDebugLoc();
561
562   const MachineFunction &MF = *MBB->getParent();
563   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
564   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
565   const MCInstrDesc &MCID = TII.get(ADDriOpc);
566   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
567
568   MachineInstrBuilder MIB = BuildMI(*MBB, Ins, DL, MCID, BaseReg)
569     .addFrameIndex(FrameIdx).addImm(Offset);
570
571   if (!AFI->isThumb1OnlyFunction())
572     AddDefaultCC(AddDefaultPred(MIB));
573 }
574
575 void ARMBaseRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
576                                             int64_t Offset) const {
577   MachineBasicBlock &MBB = *MI.getParent();
578   MachineFunction &MF = *MBB.getParent();
579   const ARMBaseInstrInfo &TII =
580       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().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 = 8;
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.getSubtarget().getInstrInfo());
680   const ARMFrameLowering *TFI = static_cast<const ARMFrameLowering *>(
681       MF.getSubtarget().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   assert(!MI.isDebugValue() && "DBG_VALUEs should be handled in target-independent code");
706
707   // Modify MI as necessary to handle as much of 'Offset' as possible
708   bool Done = false;
709   if (!AFI->isThumbFunction())
710     Done = rewriteARMFrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
711   else {
712     assert(AFI->isThumb2Function());
713     Done = rewriteT2FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
714   }
715   if (Done)
716     return;
717
718   // If we get here, the immediate doesn't fit into the instruction.  We folded
719   // as much as possible above, handle the rest, providing a register that is
720   // SP+LargeImm.
721   assert((Offset ||
722           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
723           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
724          "This code isn't needed if offset already handled!");
725
726   unsigned ScratchReg = 0;
727   int PIdx = MI.findFirstPredOperandIdx();
728   ARMCC::CondCodes Pred = (PIdx == -1)
729     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
730   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
731   if (Offset == 0)
732     // Must be addrmode4/6.
733     MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false, false, false);
734   else {
735     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
736     if (!AFI->isThumbFunction())
737       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
738                               Offset, Pred, PredReg, TII);
739     else {
740       assert(AFI->isThumb2Function());
741       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
742                              Offset, Pred, PredReg, TII);
743     }
744     // Update the original instruction to use the scratch register.
745     MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false,true);
746   }
747 }
748
749 bool ARMBaseRegisterInfo::shouldCoalesce(MachineInstr *MI,
750                                   const TargetRegisterClass *SrcRC,
751                                   unsigned SubReg,
752                                   const TargetRegisterClass *DstRC,
753                                   unsigned DstSubReg,
754                                   const TargetRegisterClass *NewRC) const {
755   auto MBB = MI->getParent();
756   auto MF = MBB->getParent();
757   const MachineRegisterInfo &MRI = MF->getRegInfo();
758   // If not copying into a sub-register this should be ok because we shouldn't
759   // need to split the reg.
760   if (!DstSubReg)
761     return true;
762   // Small registers don't frequently cause a problem, so we can coalesce them.
763   if (NewRC->getSize() < 32 && DstRC->getSize() < 32 && SrcRC->getSize() < 32)
764     return true;
765
766   auto NewRCWeight =
767               MRI.getTargetRegisterInfo()->getRegClassWeight(NewRC);
768   auto SrcRCWeight =
769               MRI.getTargetRegisterInfo()->getRegClassWeight(SrcRC);
770   auto DstRCWeight =
771               MRI.getTargetRegisterInfo()->getRegClassWeight(DstRC);
772   // If the source register class is more expensive than the destination, the
773   // coalescing is probably profitable.
774   if (SrcRCWeight.RegWeight > NewRCWeight.RegWeight)
775     return true;
776   if (DstRCWeight.RegWeight > NewRCWeight.RegWeight)
777     return true;
778
779   // If the register allocator isn't constrained, we can always allow coalescing
780   // unfortunately we don't know yet if we will be constrained.
781   // The goal of this heuristic is to restrict how many expensive registers
782   // we allow to coalesce in a given basic block.
783   auto AFI = MF->getInfo<ARMFunctionInfo>();
784   auto It = AFI->getCoalescedWeight(MBB);
785
786   DEBUG(dbgs() << "\tARM::shouldCoalesce - Coalesced Weight: "
787     << It->second << "\n");
788   DEBUG(dbgs() << "\tARM::shouldCoalesce - Reg Weight: "
789     << NewRCWeight.RegWeight << "\n");
790
791   // This number is the largest round number that which meets the criteria:
792   //  (1) addresses PR18825
793   //  (2) generates better code in some test cases (like vldm-shed-a9.ll)
794   //  (3) Doesn't regress any test cases (in-tree, test-suite, and SPEC)
795   // In practice the SizeMultiplier will only factor in for straight line code
796   // that uses a lot of NEON vectors, which isn't terribly common.
797   unsigned SizeMultiplier = MBB->size()/100;
798   SizeMultiplier = SizeMultiplier ? SizeMultiplier : 1;
799   if (It->second < NewRCWeight.WeightLimit * SizeMultiplier) {
800     It->second += NewRCWeight.RegWeight;
801     return true;
802   }
803   return false;
804 }