Thumb1RegisterInfo.cpp revision c9aed19747608b7688a64f2f382a008889f8e57d
1//===- Thumb1RegisterInfo.cpp - Thumb-1 Register Information ----*- C++ -*-===//
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 Thumb-1 implementation of the TargetRegisterInfo
11// class.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ARM.h"
16#include "ARMAddressingModes.h"
17#include "ARMBaseInstrInfo.h"
18#include "ARMMachineFunctionInfo.h"
19#include "ARMSubtarget.h"
20#include "Thumb1InstrInfo.h"
21#include "Thumb1RegisterInfo.h"
22#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
25#include "llvm/LLVMContext.h"
26#include "llvm/CodeGen/MachineConstantPool.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineLocation.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/ADT/BitVector.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39
40namespace llvm {
41extern cl::opt<bool> ReuseFrameIndexVals;
42}
43
44using namespace llvm;
45
46Thumb1RegisterInfo::Thumb1RegisterInfo(const ARMBaseInstrInfo &tii,
47                                       const ARMSubtarget &sti)
48  : ARMBaseRegisterInfo(tii, sti) {
49}
50
51/// emitLoadConstPool - Emits a load from constpool to materialize the
52/// specified immediate.
53void Thumb1RegisterInfo::emitLoadConstPool(MachineBasicBlock &MBB,
54                                           MachineBasicBlock::iterator &MBBI,
55                                           DebugLoc dl,
56                                           unsigned DestReg, unsigned SubIdx,
57                                           int Val,
58                                           ARMCC::CondCodes Pred,
59                                           unsigned PredReg) const {
60  MachineFunction &MF = *MBB.getParent();
61  MachineConstantPool *ConstantPool = MF.getConstantPool();
62  const Constant *C = ConstantInt::get(
63          Type::getInt32Ty(MBB.getParent()->getFunction()->getContext()), Val);
64  unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
65
66  BuildMI(MBB, MBBI, dl, TII.get(ARM::tLDRcp))
67          .addReg(DestReg, getDefRegState(true), SubIdx)
68          .addConstantPoolIndex(Idx).addImm(Pred).addReg(PredReg);
69}
70
71bool Thumb1RegisterInfo::hasReservedCallFrame(const MachineFunction &MF) const {
72  const MachineFrameInfo *FFI = MF.getFrameInfo();
73  unsigned CFSize = FFI->getMaxCallFrameSize();
74  // It's not always a good idea to include the call frame as part of the
75  // stack frame. ARM (especially Thumb) has small immediate offset to
76  // address the stack frame. So a large call frame can cause poor codegen
77  // and may even makes it impossible to scavenge a register.
78  if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
79    return false;
80
81  return !MF.getFrameInfo()->hasVarSizedObjects();
82}
83
84
85/// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
86/// a destreg = basereg + immediate in Thumb code. Materialize the immediate
87/// in a register using mov / mvn sequences or load the immediate from a
88/// constpool entry.
89static
90void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
91                              MachineBasicBlock::iterator &MBBI,
92                              unsigned DestReg, unsigned BaseReg,
93                              int NumBytes, bool CanChangeCC,
94                              const TargetInstrInfo &TII,
95                              const Thumb1RegisterInfo& MRI,
96                              DebugLoc dl) {
97    MachineFunction &MF = *MBB.getParent();
98    bool isHigh = !isARMLowRegister(DestReg) ||
99                  (BaseReg != 0 && !isARMLowRegister(BaseReg));
100    bool isSub = false;
101    // Subtract doesn't have high register version. Load the negative value
102    // if either base or dest register is a high register. Also, if do not
103    // issue sub as part of the sequence if condition register is to be
104    // preserved.
105    if (NumBytes < 0 && !isHigh && CanChangeCC) {
106      isSub = true;
107      NumBytes = -NumBytes;
108    }
109    unsigned LdReg = DestReg;
110    if (DestReg == ARM::SP) {
111      assert(BaseReg == ARM::SP && "Unexpected!");
112      LdReg = MF.getRegInfo().createVirtualRegister(ARM::tGPRRegisterClass);
113    }
114
115    if (NumBytes <= 255 && NumBytes >= 0)
116      AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8), LdReg))
117        .addImm(NumBytes);
118    else if (NumBytes < 0 && NumBytes >= -255) {
119      AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8), LdReg))
120        .addImm(NumBytes);
121      AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tRSB), LdReg))
122        .addReg(LdReg, RegState::Kill);
123    } else
124      MRI.emitLoadConstPool(MBB, MBBI, dl, LdReg, 0, NumBytes);
125
126    // Emit add / sub.
127    int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
128    MachineInstrBuilder MIB =
129      BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
130    if (Opc != ARM::tADDhirr)
131      MIB = AddDefaultT1CC(MIB);
132    if (DestReg == ARM::SP || isSub)
133      MIB.addReg(BaseReg).addReg(LdReg, RegState::Kill);
134    else
135      MIB.addReg(LdReg).addReg(BaseReg, RegState::Kill);
136    AddDefaultPred(MIB);
137}
138
139/// calcNumMI - Returns the number of instructions required to materialize
140/// the specific add / sub r, c instruction.
141static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
142                          unsigned NumBits, unsigned Scale) {
143  unsigned NumMIs = 0;
144  unsigned Chunk = ((1 << NumBits) - 1) * Scale;
145
146  if (Opc == ARM::tADDrSPi) {
147    unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
148    Bytes -= ThisVal;
149    NumMIs++;
150    NumBits = 8;
151    Scale = 1;  // Followed by a number of tADDi8.
152    Chunk = ((1 << NumBits) - 1) * Scale;
153  }
154
155  NumMIs += Bytes / Chunk;
156  if ((Bytes % Chunk) != 0)
157    NumMIs++;
158  if (ExtraOpc)
159    NumMIs++;
160  return NumMIs;
161}
162
163/// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
164/// a destreg = basereg + immediate in Thumb code.
165static
166void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
167                               MachineBasicBlock::iterator &MBBI,
168                               unsigned DestReg, unsigned BaseReg,
169                               int NumBytes, const TargetInstrInfo &TII,
170                               const Thumb1RegisterInfo& MRI,
171                               DebugLoc dl) {
172  bool isSub = NumBytes < 0;
173  unsigned Bytes = (unsigned)NumBytes;
174  if (isSub) Bytes = -NumBytes;
175  bool isMul4 = (Bytes & 3) == 0;
176  bool isTwoAddr = false;
177  bool DstNotEqBase = false;
178  unsigned NumBits = 1;
179  unsigned Scale = 1;
180  int Opc = 0;
181  int ExtraOpc = 0;
182  bool NeedCC = false;
183  bool NeedPred = false;
184
185  if (DestReg == BaseReg && BaseReg == ARM::SP) {
186    assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
187    NumBits = 7;
188    Scale = 4;
189    Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
190    isTwoAddr = true;
191  } else if (!isSub && BaseReg == ARM::SP) {
192    // r1 = add sp, 403
193    // =>
194    // r1 = add sp, 100 * 4
195    // r1 = add r1, 3
196    if (!isMul4) {
197      Bytes &= ~3;
198      ExtraOpc = ARM::tADDi3;
199    }
200    NumBits = 8;
201    Scale = 4;
202    Opc = ARM::tADDrSPi;
203  } else {
204    // sp = sub sp, c
205    // r1 = sub sp, c
206    // r8 = sub sp, c
207    if (DestReg != BaseReg)
208      DstNotEqBase = true;
209    NumBits = 8;
210    if (DestReg == ARM::SP) {
211      Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
212      assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
213      NumBits = 7;
214      Scale = 4;
215    } else {
216      Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
217      NumBits = 8;
218      NeedPred = NeedCC = true;
219    }
220    isTwoAddr = true;
221  }
222
223  unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
224  unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
225  if (NumMIs > Threshold) {
226    // This will expand into too many instructions. Load the immediate from a
227    // constpool entry.
228    emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII,
229                             MRI, dl);
230    return;
231  }
232
233  if (DstNotEqBase) {
234    if (isARMLowRegister(DestReg) && isARMLowRegister(BaseReg)) {
235      // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
236      unsigned Chunk = (1 << 3) - 1;
237      unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
238      Bytes -= ThisVal;
239      const TargetInstrDesc &TID = TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3);
240      const MachineInstrBuilder MIB =
241        AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TID, DestReg));
242      AddDefaultPred(MIB.addReg(BaseReg, RegState::Kill).addImm(ThisVal));
243    } else {
244      BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), DestReg)
245        .addReg(BaseReg, RegState::Kill);
246    }
247    BaseReg = DestReg;
248  }
249
250  unsigned Chunk = ((1 << NumBits) - 1) * Scale;
251  while (Bytes) {
252    unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
253    Bytes -= ThisVal;
254    ThisVal /= Scale;
255    // Build the new tADD / tSUB.
256    if (isTwoAddr) {
257      MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
258      if (NeedCC)
259        MIB = AddDefaultT1CC(MIB);
260      MIB .addReg(DestReg).addImm(ThisVal);
261      if (NeedPred)
262        MIB = AddDefaultPred(MIB);
263    }
264    else {
265      bool isKill = BaseReg != ARM::SP;
266      MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
267      if (NeedCC)
268        MIB = AddDefaultT1CC(MIB);
269      MIB.addReg(BaseReg, getKillRegState(isKill)).addImm(ThisVal);
270      if (NeedPred)
271        MIB = AddDefaultPred(MIB);
272      BaseReg = DestReg;
273
274      if (Opc == ARM::tADDrSPi) {
275        // r4 = add sp, imm
276        // r4 = add r4, imm
277        // ...
278        NumBits = 8;
279        Scale = 1;
280        Chunk = ((1 << NumBits) - 1) * Scale;
281        Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
282        NeedPred = NeedCC = isTwoAddr = true;
283      }
284    }
285  }
286
287  if (ExtraOpc) {
288    const TargetInstrDesc &TID = TII.get(ExtraOpc);
289    AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TID, DestReg))
290                   .addReg(DestReg, RegState::Kill)
291                   .addImm(((unsigned)NumBytes) & 3));
292  }
293}
294
295static void emitSPUpdate(MachineBasicBlock &MBB,
296                         MachineBasicBlock::iterator &MBBI,
297                         const TargetInstrInfo &TII, DebugLoc dl,
298                         const Thumb1RegisterInfo &MRI,
299                         int NumBytes) {
300  emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII,
301                            MRI, dl);
302}
303
304void Thumb1RegisterInfo::
305eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
306                              MachineBasicBlock::iterator I) const {
307  if (!hasReservedCallFrame(MF)) {
308    // If we have alloca, convert as follows:
309    // ADJCALLSTACKDOWN -> sub, sp, sp, amount
310    // ADJCALLSTACKUP   -> add, sp, sp, amount
311    MachineInstr *Old = I;
312    DebugLoc dl = Old->getDebugLoc();
313    unsigned Amount = Old->getOperand(0).getImm();
314    if (Amount != 0) {
315      // We need to keep the stack aligned properly.  To do this, we round the
316      // amount of space needed for the outgoing arguments up to the next
317      // alignment boundary.
318      unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
319      Amount = (Amount+Align-1)/Align*Align;
320
321      // Replace the pseudo instruction with a new instruction...
322      unsigned Opc = Old->getOpcode();
323      if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
324        emitSPUpdate(MBB, I, TII, dl, *this, -Amount);
325      } else {
326        assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
327        emitSPUpdate(MBB, I, TII, dl, *this, Amount);
328      }
329    }
330  }
331  MBB.erase(I);
332}
333
334/// emitThumbConstant - Emit a series of instructions to materialize a
335/// constant.
336static void emitThumbConstant(MachineBasicBlock &MBB,
337                              MachineBasicBlock::iterator &MBBI,
338                              unsigned DestReg, int Imm,
339                              const TargetInstrInfo &TII,
340                              const Thumb1RegisterInfo& MRI,
341                              DebugLoc dl) {
342  bool isSub = Imm < 0;
343  if (isSub) Imm = -Imm;
344
345  int Chunk = (1 << 8) - 1;
346  int ThisVal = (Imm > Chunk) ? Chunk : Imm;
347  Imm -= ThisVal;
348  AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8),
349                                        DestReg))
350                 .addImm(ThisVal));
351  if (Imm > 0)
352    emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII, MRI, dl);
353  if (isSub) {
354    const TargetInstrDesc &TID = TII.get(ARM::tRSB);
355    AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TID, DestReg))
356                   .addReg(DestReg, RegState::Kill));
357  }
358}
359
360static void removeOperands(MachineInstr &MI, unsigned i) {
361  unsigned Op = i;
362  for (unsigned e = MI.getNumOperands(); i != e; ++i)
363    MI.RemoveOperand(Op);
364}
365
366int Thumb1RegisterInfo::
367rewriteFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
368                  unsigned FrameReg, int Offset,
369                  unsigned MOVOpc, unsigned ADDriOpc, unsigned SUBriOpc) const
370{
371  // if/when eliminateFrameIndex() conforms with ARMBaseRegisterInfo
372  // version then can pull out Thumb1 specific parts here
373  return 0;
374}
375
376/// saveScavengerRegister - Spill the register so it can be used by the
377/// register scavenger. Return true.
378bool
379Thumb1RegisterInfo::saveScavengerRegister(MachineBasicBlock &MBB,
380                                          MachineBasicBlock::iterator I,
381                                          MachineBasicBlock::iterator &UseMI,
382                                          const TargetRegisterClass *RC,
383                                          unsigned Reg) const {
384  // Thumb1 can't use the emergency spill slot on the stack because
385  // ldr/str immediate offsets must be positive, and if we're referencing
386  // off the frame pointer (if, for example, there are alloca() calls in
387  // the function, the offset will be negative. Use R12 instead since that's
388  // a call clobbered register that we know won't be used in Thumb1 mode.
389  DebugLoc DL;
390  BuildMI(MBB, I, DL, TII.get(ARM::tMOVtgpr2gpr)).
391    addReg(ARM::R12, RegState::Define).addReg(Reg, RegState::Kill);
392
393  // The UseMI is where we would like to restore the register. If there's
394  // interference with R12 before then, however, we'll need to restore it
395  // before that instead and adjust the UseMI.
396  bool done = false;
397  for (MachineBasicBlock::iterator II = I; !done && II != UseMI ; ++II) {
398    if (II->isDebugValue())
399      continue;
400    // If this instruction affects R12, adjust our restore point.
401    for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
402      const MachineOperand &MO = II->getOperand(i);
403      if (!MO.isReg() || MO.isUndef() || !MO.getReg() ||
404          TargetRegisterInfo::isVirtualRegister(MO.getReg()))
405        continue;
406      if (MO.getReg() == ARM::R12) {
407        UseMI = II;
408        done = true;
409        break;
410      }
411    }
412  }
413  // Restore the register from R12
414  BuildMI(MBB, UseMI, DL, TII.get(ARM::tMOVgpr2tgpr)).
415    addReg(Reg, RegState::Define).addReg(ARM::R12, RegState::Kill);
416
417  return true;
418}
419
420unsigned
421Thumb1RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
422                                        int SPAdj, FrameIndexValue *Value,
423                                        RegScavenger *RS) const{
424  unsigned VReg = 0;
425  unsigned i = 0;
426  MachineInstr &MI = *II;
427  MachineBasicBlock &MBB = *MI.getParent();
428  MachineFunction &MF = *MBB.getParent();
429  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
430  DebugLoc dl = MI.getDebugLoc();
431
432  while (!MI.getOperand(i).isFI()) {
433    ++i;
434    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
435  }
436
437  unsigned FrameReg = ARM::SP;
438  int FrameIndex = MI.getOperand(i).getIndex();
439  int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
440               MF.getFrameInfo()->getStackSize() + SPAdj;
441
442  if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
443    Offset -= AFI->getGPRCalleeSavedArea1Offset();
444  else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
445    Offset -= AFI->getGPRCalleeSavedArea2Offset();
446  else if (MF.getFrameInfo()->hasVarSizedObjects()) {
447    assert(SPAdj == 0 && hasFP(MF) && "Unexpected");
448    // There are alloca()'s in this function, must reference off the frame
449    // pointer instead.
450    FrameReg = getFrameRegister(MF);
451    Offset -= AFI->getFramePtrSpillOffset();
452  }
453
454  // Special handling of dbg_value instructions.
455  if (MI.isDebugValue()) {
456    MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
457    MI.getOperand(i+1).ChangeToImmediate(Offset);
458    return 0;
459  }
460
461  unsigned Opcode = MI.getOpcode();
462  const TargetInstrDesc &Desc = MI.getDesc();
463  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
464
465  if (Opcode == ARM::tADDrSPi) {
466    Offset += MI.getOperand(i+1).getImm();
467
468    // Can't use tADDrSPi if it's based off the frame pointer.
469    unsigned NumBits = 0;
470    unsigned Scale = 1;
471    if (FrameReg != ARM::SP) {
472      Opcode = ARM::tADDi3;
473      MI.setDesc(TII.get(Opcode));
474      NumBits = 3;
475    } else {
476      NumBits = 8;
477      Scale = 4;
478      assert((Offset & 3) == 0 &&
479             "Thumb add/sub sp, #imm immediate must be multiple of 4!");
480    }
481
482    unsigned PredReg;
483    if (Offset == 0 && getInstrPredicate(&MI, PredReg) == ARMCC::AL) {
484      // Turn it into a move.
485      MI.setDesc(TII.get(ARM::tMOVgpr2tgpr));
486      MI.getOperand(i).ChangeToRegister(FrameReg, false);
487      // Remove offset and remaining explicit predicate operands.
488      do MI.RemoveOperand(i+1);
489      while (MI.getNumOperands() > i+1 &&
490             (!MI.getOperand(i+1).isReg() || !MI.getOperand(i+1).isImm()));
491      return 0;
492    }
493
494    // Common case: small offset, fits into instruction.
495    unsigned Mask = (1 << NumBits) - 1;
496    if (((Offset / Scale) & ~Mask) == 0) {
497      // Replace the FrameIndex with sp / fp
498      if (Opcode == ARM::tADDi3) {
499        removeOperands(MI, i);
500        MachineInstrBuilder MIB(&MI);
501        AddDefaultPred(AddDefaultT1CC(MIB).addReg(FrameReg)
502                       .addImm(Offset / Scale));
503      } else {
504        MI.getOperand(i).ChangeToRegister(FrameReg, false);
505        MI.getOperand(i+1).ChangeToImmediate(Offset / Scale);
506      }
507      return 0;
508    }
509
510    unsigned DestReg = MI.getOperand(0).getReg();
511    unsigned Bytes = (Offset > 0) ? Offset : -Offset;
512    unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
513    // MI would expand into a large number of instructions. Don't try to
514    // simplify the immediate.
515    if (NumMIs > 2) {
516      emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII,
517                                *this, dl);
518      MBB.erase(II);
519      return 0;
520    }
521
522    if (Offset > 0) {
523      // Translate r0 = add sp, imm to
524      // r0 = add sp, 255*4
525      // r0 = add r0, (imm - 255*4)
526      if (Opcode == ARM::tADDi3) {
527        removeOperands(MI, i);
528        MachineInstrBuilder MIB(&MI);
529        AddDefaultPred(AddDefaultT1CC(MIB).addReg(FrameReg).addImm(Mask));
530      } else {
531        MI.getOperand(i).ChangeToRegister(FrameReg, false);
532        MI.getOperand(i+1).ChangeToImmediate(Mask);
533      }
534      Offset = (Offset - Mask * Scale);
535      MachineBasicBlock::iterator NII = llvm::next(II);
536      emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII,
537                                *this, dl);
538    } else {
539      // Translate r0 = add sp, -imm to
540      // r0 = -imm (this is then translated into a series of instructons)
541      // r0 = add r0, sp
542      emitThumbConstant(MBB, II, DestReg, Offset, TII, *this, dl);
543
544      MI.setDesc(TII.get(ARM::tADDhirr));
545      MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
546      MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
547      if (Opcode == ARM::tADDi3) {
548        MachineInstrBuilder MIB(&MI);
549        AddDefaultPred(MIB);
550      }
551    }
552    return 0;
553  } else {
554    unsigned ImmIdx = 0;
555    int InstrOffs = 0;
556    unsigned NumBits = 0;
557    unsigned Scale = 1;
558    switch (AddrMode) {
559    case ARMII::AddrModeT1_s: {
560      ImmIdx = i+1;
561      InstrOffs = MI.getOperand(ImmIdx).getImm();
562      NumBits = (FrameReg == ARM::SP) ? 8 : 5;
563      Scale = 4;
564      break;
565    }
566    default:
567      llvm_unreachable("Unsupported addressing mode!");
568      break;
569    }
570
571    Offset += InstrOffs * Scale;
572    assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
573
574    // Common case: small offset, fits into instruction.
575    MachineOperand &ImmOp = MI.getOperand(ImmIdx);
576    int ImmedOffset = Offset / Scale;
577    unsigned Mask = (1 << NumBits) - 1;
578    if ((unsigned)Offset <= Mask * Scale) {
579      // Replace the FrameIndex with sp
580      MI.getOperand(i).ChangeToRegister(FrameReg, false);
581      ImmOp.ChangeToImmediate(ImmedOffset);
582      return 0;
583    }
584
585    bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
586    if (AddrMode == ARMII::AddrModeT1_s) {
587      // Thumb tLDRspi, tSTRspi. These will change to instructions that use
588      // a different base register.
589      NumBits = 5;
590      Mask = (1 << NumBits) - 1;
591    }
592    // If this is a thumb spill / restore, we will be using a constpool load to
593    // materialize the offset.
594    if (AddrMode == ARMII::AddrModeT1_s && isThumSpillRestore)
595      ImmOp.ChangeToImmediate(0);
596    else {
597      // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
598      ImmedOffset = ImmedOffset & Mask;
599      ImmOp.ChangeToImmediate(ImmedOffset);
600      Offset &= ~(Mask*Scale);
601    }
602  }
603
604  // If we get here, the immediate doesn't fit into the instruction.  We folded
605  // as much as possible above, handle the rest, providing a register that is
606  // SP+LargeImm.
607  assert(Offset && "This code isn't needed if offset already handled!");
608
609  // Remove predicate first.
610  int PIdx = MI.findFirstPredOperandIdx();
611  if (PIdx != -1)
612    removeOperands(MI, PIdx);
613
614  if (Desc.mayLoad()) {
615    // Use the destination register to materialize sp + offset.
616    unsigned TmpReg = MI.getOperand(0).getReg();
617    bool UseRR = false;
618    if (Opcode == ARM::tRestore) {
619      if (FrameReg == ARM::SP)
620        emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,
621                                 Offset, false, TII, *this, dl);
622      else {
623        emitLoadConstPool(MBB, II, dl, TmpReg, 0, Offset);
624        UseRR = true;
625      }
626    } else {
627      emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII,
628                                *this, dl);
629    }
630
631    MI.setDesc(TII.get(ARM::tLDR));
632    MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
633    if (UseRR)
634      // Use [reg, reg] addrmode.
635      MI.addOperand(MachineOperand::CreateReg(FrameReg, false));
636    else  // tLDR has an extra register operand.
637      MI.addOperand(MachineOperand::CreateReg(0, false));
638  } else if (Desc.mayStore()) {
639      VReg = MF.getRegInfo().createVirtualRegister(ARM::tGPRRegisterClass);
640      assert (Value && "Frame index virtual allocated, but Value arg is NULL!");
641      bool UseRR = false;
642      bool TrackVReg = true;
643      Value->first = FrameReg; // use the frame register as a kind indicator
644      Value->second = Offset;
645
646      if (Opcode == ARM::tSpill) {
647        if (FrameReg == ARM::SP)
648          emitThumbRegPlusImmInReg(MBB, II, VReg, FrameReg,
649                                   Offset, false, TII, *this, dl);
650        else {
651          emitLoadConstPool(MBB, II, dl, VReg, 0, Offset);
652          UseRR = true;
653          TrackVReg = false;
654        }
655      } else
656        emitThumbRegPlusImmediate(MBB, II, VReg, FrameReg, Offset, TII,
657                                  *this, dl);
658      MI.setDesc(TII.get(ARM::tSTR));
659      MI.getOperand(i).ChangeToRegister(VReg, false, false, true);
660      if (UseRR)  // Use [reg, reg] addrmode.
661        MI.addOperand(MachineOperand::CreateReg(FrameReg, false));
662      else // tSTR has an extra register operand.
663        MI.addOperand(MachineOperand::CreateReg(0, false));
664      if (!ReuseFrameIndexVals || !TrackVReg)
665        VReg = 0;
666  } else
667    assert(false && "Unexpected opcode!");
668
669  // Add predicate back if it's needed.
670  if (MI.getDesc().isPredicable()) {
671    MachineInstrBuilder MIB(&MI);
672    AddDefaultPred(MIB);
673  }
674  return VReg;
675}
676
677void Thumb1RegisterInfo::emitPrologue(MachineFunction &MF) const {
678  MachineBasicBlock &MBB = MF.front();
679  MachineBasicBlock::iterator MBBI = MBB.begin();
680  MachineFrameInfo  *MFI = MF.getFrameInfo();
681  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
682  unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
683  unsigned NumBytes = MFI->getStackSize();
684  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
685  DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
686
687  // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
688  NumBytes = (NumBytes + 3) & ~3;
689  MFI->setStackSize(NumBytes);
690
691  // Determine the sizes of each callee-save spill areas and record which frame
692  // belongs to which callee-save spill areas.
693  unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
694  int FramePtrSpillFI = 0;
695
696  if (VARegSaveSize)
697    emitSPUpdate(MBB, MBBI, TII, dl, *this, -VARegSaveSize);
698
699  if (!AFI->hasStackFrame()) {
700    if (NumBytes != 0)
701      emitSPUpdate(MBB, MBBI, TII, dl, *this, -NumBytes);
702    return;
703  }
704
705  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
706    unsigned Reg = CSI[i].getReg();
707    int FI = CSI[i].getFrameIdx();
708    switch (Reg) {
709    case ARM::R4:
710    case ARM::R5:
711    case ARM::R6:
712    case ARM::R7:
713    case ARM::LR:
714      if (Reg == FramePtr)
715        FramePtrSpillFI = FI;
716      AFI->addGPRCalleeSavedArea1Frame(FI);
717      GPRCS1Size += 4;
718      break;
719    case ARM::R8:
720    case ARM::R9:
721    case ARM::R10:
722    case ARM::R11:
723      if (Reg == FramePtr)
724        FramePtrSpillFI = FI;
725      if (STI.isTargetDarwin()) {
726        AFI->addGPRCalleeSavedArea2Frame(FI);
727        GPRCS2Size += 4;
728      } else {
729        AFI->addGPRCalleeSavedArea1Frame(FI);
730        GPRCS1Size += 4;
731      }
732      break;
733    default:
734      AFI->addDPRCalleeSavedAreaFrame(FI);
735      DPRCSSize += 8;
736    }
737  }
738
739  if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
740    ++MBBI;
741    if (MBBI != MBB.end())
742      dl = MBBI->getDebugLoc();
743  }
744
745  // Adjust FP so it point to the stack slot that contains the previous FP.
746  if (hasFP(MF)) {
747    BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
748      .addFrameIndex(FramePtrSpillFI).addImm(0);
749    AFI->setShouldRestoreSPFromFP(true);
750  }
751
752  // Determine starting offsets of spill areas.
753  unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
754  unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
755  unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
756  AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
757  AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
758  AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
759  AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
760
761  NumBytes = DPRCSOffset;
762  if (NumBytes) {
763    // Insert it after all the callee-save spills.
764    emitSPUpdate(MBB, MBBI, TII, dl, *this, -NumBytes);
765  }
766
767  if (STI.isTargetELF() && hasFP(MF))
768    MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
769                             AFI->getFramePtrSpillOffset());
770
771  AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
772  AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
773  AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
774}
775
776static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
777  for (unsigned i = 0; CSRegs[i]; ++i)
778    if (Reg == CSRegs[i])
779      return true;
780  return false;
781}
782
783static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
784  if (MI->getOpcode() == ARM::tRestore &&
785      MI->getOperand(1).isFI() &&
786      isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
787    return true;
788  else if (MI->getOpcode() == ARM::tPOP) {
789    // The first two operands are predicates. The last two are
790    // imp-def and imp-use of SP. Check everything in between.
791    for (int i = 2, e = MI->getNumOperands() - 2; i != e; ++i)
792      if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
793        return false;
794    return true;
795  }
796  return false;
797}
798
799void Thumb1RegisterInfo::emitEpilogue(MachineFunction &MF,
800                                      MachineBasicBlock &MBB) const {
801  MachineBasicBlock::iterator MBBI = prior(MBB.end());
802  assert((MBBI->getOpcode() == ARM::tBX_RET ||
803          MBBI->getOpcode() == ARM::tPOP_RET) &&
804         "Can only insert epilog into returning blocks");
805  DebugLoc dl = MBBI->getDebugLoc();
806  MachineFrameInfo *MFI = MF.getFrameInfo();
807  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
808  unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
809  int NumBytes = (int)MFI->getStackSize();
810  const unsigned *CSRegs = getCalleeSavedRegs();
811
812  if (!AFI->hasStackFrame()) {
813    if (NumBytes != 0)
814      emitSPUpdate(MBB, MBBI, TII, dl, *this, NumBytes);
815  } else {
816    // Unwind MBBI to point to first LDR / VLDRD.
817    if (MBBI != MBB.begin()) {
818      do
819        --MBBI;
820      while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
821      if (!isCSRestore(MBBI, CSRegs))
822        ++MBBI;
823    }
824
825    // Move SP to start of FP callee save spill area.
826    NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
827                 AFI->getGPRCalleeSavedArea2Size() +
828                 AFI->getDPRCalleeSavedAreaSize());
829
830    if (AFI->shouldRestoreSPFromFP()) {
831      NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
832      // Reset SP based on frame pointer only if the stack frame extends beyond
833      // frame pointer stack slot or target is ELF and the function has FP.
834      if (NumBytes)
835        emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes,
836                                  TII, *this, dl);
837      else
838        BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
839          .addReg(FramePtr);
840    } else {
841      if (MBBI->getOpcode() == ARM::tBX_RET &&
842          &MBB.front() != MBBI &&
843          prior(MBBI)->getOpcode() == ARM::tPOP) {
844        MachineBasicBlock::iterator PMBBI = prior(MBBI);
845        emitSPUpdate(MBB, PMBBI, TII, dl, *this, NumBytes);
846      } else
847        emitSPUpdate(MBB, MBBI, TII, dl, *this, NumBytes);
848    }
849  }
850
851  if (VARegSaveSize) {
852    // Unlike T2 and ARM mode, the T1 pop instruction cannot restore
853    // to LR, and we can't pop the value directly to the PC since
854    // we need to update the SP after popping the value. Therefore, we
855    // pop the old LR into R3 as a temporary.
856
857    // Move back past the callee-saved register restoration
858    while (MBBI != MBB.end() && isCSRestore(MBBI, CSRegs))
859      ++MBBI;
860    // Epilogue for vararg functions: pop LR to R3 and branch off it.
861    AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
862      .addReg(ARM::R3, RegState::Define);
863
864    emitSPUpdate(MBB, MBBI, TII, dl, *this, VARegSaveSize);
865
866    BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX_RET_vararg))
867      .addReg(ARM::R3, RegState::Kill);
868    // erase the old tBX_RET instruction
869    MBB.erase(MBBI);
870  }
871}
872