Refactor code. Fix a potential missing check. Teach isIdentical() about tLDRpci_pic.
[oota-llvm.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
1 //===- ARMBaseInstrInfo.cpp - ARM Instruction 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 Base ARM implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMBaseInstrInfo.h"
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMGenInstrInfo.inc"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMRegisterInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 using namespace llvm;
34
35 static cl::opt<bool>
36 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
37                cl::desc("Enable ARM 2-addr to 3-addr conv"));
38
39 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
40   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
41     Subtarget(STI) {
42 }
43
44 MachineInstr *
45 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
46                                         MachineBasicBlock::iterator &MBBI,
47                                         LiveVariables *LV) const {
48   // FIXME: Thumb2 support.
49
50   if (!EnableARM3Addr)
51     return NULL;
52
53   MachineInstr *MI = MBBI;
54   MachineFunction &MF = *MI->getParent()->getParent();
55   unsigned TSFlags = MI->getDesc().TSFlags;
56   bool isPre = false;
57   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
58   default: return NULL;
59   case ARMII::IndexModePre:
60     isPre = true;
61     break;
62   case ARMII::IndexModePost:
63     break;
64   }
65
66   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
67   // operation.
68   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
69   if (MemOpc == 0)
70     return NULL;
71
72   MachineInstr *UpdateMI = NULL;
73   MachineInstr *MemMI = NULL;
74   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
75   const TargetInstrDesc &TID = MI->getDesc();
76   unsigned NumOps = TID.getNumOperands();
77   bool isLoad = !TID.mayStore();
78   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
79   const MachineOperand &Base = MI->getOperand(2);
80   const MachineOperand &Offset = MI->getOperand(NumOps-3);
81   unsigned WBReg = WB.getReg();
82   unsigned BaseReg = Base.getReg();
83   unsigned OffReg = Offset.getReg();
84   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
85   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
86   switch (AddrMode) {
87   default:
88     assert(false && "Unknown indexed op!");
89     return NULL;
90   case ARMII::AddrMode2: {
91     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
92     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
93     if (OffReg == 0) {
94       if (ARM_AM::getSOImmVal(Amt) == -1)
95         // Can't encode it in a so_imm operand. This transformation will
96         // add more than 1 instruction. Abandon!
97         return NULL;
98       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
99                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
100         .addReg(BaseReg).addImm(Amt)
101         .addImm(Pred).addReg(0).addReg(0);
102     } else if (Amt != 0) {
103       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
104       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
105       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
106                          get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
107         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
108         .addImm(Pred).addReg(0).addReg(0);
109     } else
110       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
111                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
112         .addReg(BaseReg).addReg(OffReg)
113         .addImm(Pred).addReg(0).addReg(0);
114     break;
115   }
116   case ARMII::AddrMode3 : {
117     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
118     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
119     if (OffReg == 0)
120       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
121       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
122                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
123         .addReg(BaseReg).addImm(Amt)
124         .addImm(Pred).addReg(0).addReg(0);
125     else
126       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
127                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
128         .addReg(BaseReg).addReg(OffReg)
129         .addImm(Pred).addReg(0).addReg(0);
130     break;
131   }
132   }
133
134   std::vector<MachineInstr*> NewMIs;
135   if (isPre) {
136     if (isLoad)
137       MemMI = BuildMI(MF, MI->getDebugLoc(),
138                       get(MemOpc), MI->getOperand(0).getReg())
139         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
140     else
141       MemMI = BuildMI(MF, MI->getDebugLoc(),
142                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
143         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
144     NewMIs.push_back(MemMI);
145     NewMIs.push_back(UpdateMI);
146   } else {
147     if (isLoad)
148       MemMI = BuildMI(MF, MI->getDebugLoc(),
149                       get(MemOpc), MI->getOperand(0).getReg())
150         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
151     else
152       MemMI = BuildMI(MF, MI->getDebugLoc(),
153                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
154         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
155     if (WB.isDead())
156       UpdateMI->getOperand(0).setIsDead();
157     NewMIs.push_back(UpdateMI);
158     NewMIs.push_back(MemMI);
159   }
160
161   // Transfer LiveVariables states, kill / dead info.
162   if (LV) {
163     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
164       MachineOperand &MO = MI->getOperand(i);
165       if (MO.isReg() && MO.getReg() &&
166           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
167         unsigned Reg = MO.getReg();
168
169         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
170         if (MO.isDef()) {
171           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
172           if (MO.isDead())
173             LV->addVirtualRegisterDead(Reg, NewMI);
174         }
175         if (MO.isUse() && MO.isKill()) {
176           for (unsigned j = 0; j < 2; ++j) {
177             // Look at the two new MI's in reverse order.
178             MachineInstr *NewMI = NewMIs[j];
179             if (!NewMI->readsRegister(Reg))
180               continue;
181             LV->addVirtualRegisterKilled(Reg, NewMI);
182             if (VI.removeKill(MI))
183               VI.Kills.push_back(NewMI);
184             break;
185           }
186         }
187       }
188     }
189   }
190
191   MFI->insert(MBBI, NewMIs[1]);
192   MFI->insert(MBBI, NewMIs[0]);
193   return NewMIs[0];
194 }
195
196 // Branch analysis.
197 bool
198 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
199                                 MachineBasicBlock *&FBB,
200                                 SmallVectorImpl<MachineOperand> &Cond,
201                                 bool AllowModify) const {
202   // If the block has no terminators, it just falls into the block after it.
203   MachineBasicBlock::iterator I = MBB.end();
204   if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
205     return false;
206
207   // Get the last instruction in the block.
208   MachineInstr *LastInst = I;
209
210   // If there is only one terminator instruction, process it.
211   unsigned LastOpc = LastInst->getOpcode();
212   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
213     if (isUncondBranchOpcode(LastOpc)) {
214       TBB = LastInst->getOperand(0).getMBB();
215       return false;
216     }
217     if (isCondBranchOpcode(LastOpc)) {
218       // Block ends with fall-through condbranch.
219       TBB = LastInst->getOperand(0).getMBB();
220       Cond.push_back(LastInst->getOperand(1));
221       Cond.push_back(LastInst->getOperand(2));
222       return false;
223     }
224     return true;  // Can't handle indirect branch.
225   }
226
227   // Get the instruction before it if it is a terminator.
228   MachineInstr *SecondLastInst = I;
229
230   // If there are three terminators, we don't know what sort of block this is.
231   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
232     return true;
233
234   // If the block ends with a B and a Bcc, handle it.
235   unsigned SecondLastOpc = SecondLastInst->getOpcode();
236   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
237     TBB =  SecondLastInst->getOperand(0).getMBB();
238     Cond.push_back(SecondLastInst->getOperand(1));
239     Cond.push_back(SecondLastInst->getOperand(2));
240     FBB = LastInst->getOperand(0).getMBB();
241     return false;
242   }
243
244   // If the block ends with two unconditional branches, handle it.  The second
245   // one is not executed, so remove it.
246   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
247     TBB = SecondLastInst->getOperand(0).getMBB();
248     I = LastInst;
249     if (AllowModify)
250       I->eraseFromParent();
251     return false;
252   }
253
254   // ...likewise if it ends with a branch table followed by an unconditional
255   // branch. The branch folder can create these, and we must get rid of them for
256   // correctness of Thumb constant islands.
257   if ((isJumpTableBranchOpcode(SecondLastOpc) ||
258        isIndirectBranchOpcode(SecondLastOpc)) &&
259       isUncondBranchOpcode(LastOpc)) {
260     I = LastInst;
261     if (AllowModify)
262       I->eraseFromParent();
263     return true;
264   }
265
266   // Otherwise, can't handle this.
267   return true;
268 }
269
270
271 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
272   MachineBasicBlock::iterator I = MBB.end();
273   if (I == MBB.begin()) return 0;
274   --I;
275   if (!isUncondBranchOpcode(I->getOpcode()) &&
276       !isCondBranchOpcode(I->getOpcode()))
277     return 0;
278
279   // Remove the branch.
280   I->eraseFromParent();
281
282   I = MBB.end();
283
284   if (I == MBB.begin()) return 1;
285   --I;
286   if (!isCondBranchOpcode(I->getOpcode()))
287     return 1;
288
289   // Remove the branch.
290   I->eraseFromParent();
291   return 2;
292 }
293
294 unsigned
295 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
296                                MachineBasicBlock *FBB,
297                              const SmallVectorImpl<MachineOperand> &Cond) const {
298   // FIXME this should probably have a DebugLoc argument
299   DebugLoc dl = DebugLoc::getUnknownLoc();
300
301   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
302   int BOpc   = !AFI->isThumbFunction()
303     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
304   int BccOpc = !AFI->isThumbFunction()
305     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
306
307   // Shouldn't be a fall through.
308   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
309   assert((Cond.size() == 2 || Cond.size() == 0) &&
310          "ARM branch conditions have two components!");
311
312   if (FBB == 0) {
313     if (Cond.empty()) // Unconditional branch?
314       BuildMI(&MBB, dl, get(BOpc)).addMBB(TBB);
315     else
316       BuildMI(&MBB, dl, get(BccOpc)).addMBB(TBB)
317         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
318     return 1;
319   }
320
321   // Two-way conditional branch.
322   BuildMI(&MBB, dl, get(BccOpc)).addMBB(TBB)
323     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
324   BuildMI(&MBB, dl, get(BOpc)).addMBB(FBB);
325   return 2;
326 }
327
328 bool ARMBaseInstrInfo::
329 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
330   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
331   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
332   return false;
333 }
334
335 bool ARMBaseInstrInfo::
336 PredicateInstruction(MachineInstr *MI,
337                      const SmallVectorImpl<MachineOperand> &Pred) const {
338   unsigned Opc = MI->getOpcode();
339   if (isUncondBranchOpcode(Opc)) {
340     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
341     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
342     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
343     return true;
344   }
345
346   int PIdx = MI->findFirstPredOperandIdx();
347   if (PIdx != -1) {
348     MachineOperand &PMO = MI->getOperand(PIdx);
349     PMO.setImm(Pred[0].getImm());
350     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
351     return true;
352   }
353   return false;
354 }
355
356 bool ARMBaseInstrInfo::
357 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
358                   const SmallVectorImpl<MachineOperand> &Pred2) const {
359   if (Pred1.size() > 2 || Pred2.size() > 2)
360     return false;
361
362   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
363   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
364   if (CC1 == CC2)
365     return true;
366
367   switch (CC1) {
368   default:
369     return false;
370   case ARMCC::AL:
371     return true;
372   case ARMCC::HS:
373     return CC2 == ARMCC::HI;
374   case ARMCC::LS:
375     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
376   case ARMCC::GE:
377     return CC2 == ARMCC::GT;
378   case ARMCC::LE:
379     return CC2 == ARMCC::LT;
380   }
381 }
382
383 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
384                                     std::vector<MachineOperand> &Pred) const {
385   // FIXME: This confuses implicit_def with optional CPSR def.
386   const TargetInstrDesc &TID = MI->getDesc();
387   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
388     return false;
389
390   bool Found = false;
391   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
392     const MachineOperand &MO = MI->getOperand(i);
393     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
394       Pred.push_back(MO);
395       Found = true;
396     }
397   }
398
399   return Found;
400 }
401
402
403 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
404 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
405                                 unsigned JTI) DISABLE_INLINE;
406 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
407                                 unsigned JTI) {
408   return JT[JTI].MBBs.size();
409 }
410
411 /// GetInstSize - Return the size of the specified MachineInstr.
412 ///
413 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
414   const MachineBasicBlock &MBB = *MI->getParent();
415   const MachineFunction *MF = MBB.getParent();
416   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
417
418   // Basic size info comes from the TSFlags field.
419   const TargetInstrDesc &TID = MI->getDesc();
420   unsigned TSFlags = TID.TSFlags;
421
422   unsigned Opc = MI->getOpcode();
423   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
424   default: {
425     // If this machine instr is an inline asm, measure it.
426     if (MI->getOpcode() == ARM::INLINEASM)
427       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
428     if (MI->isLabel())
429       return 0;
430     switch (Opc) {
431     default:
432       llvm_unreachable("Unknown or unset size field for instr!");
433     case TargetInstrInfo::IMPLICIT_DEF:
434     case TargetInstrInfo::KILL:
435     case TargetInstrInfo::DBG_LABEL:
436     case TargetInstrInfo::EH_LABEL:
437       return 0;
438     }
439     break;
440   }
441   case ARMII::Size8Bytes: return 8;          // ARM instruction x 2.
442   case ARMII::Size4Bytes: return 4;          // ARM / Thumb2 instruction.
443   case ARMII::Size2Bytes: return 2;          // Thumb1 instruction.
444   case ARMII::SizeSpecial: {
445     switch (Opc) {
446     case ARM::CONSTPOOL_ENTRY:
447       // If this machine instr is a constant pool entry, its size is recorded as
448       // operand #2.
449       return MI->getOperand(2).getImm();
450     case ARM::Int_eh_sjlj_setjmp:
451       return 24;
452     case ARM::t2Int_eh_sjlj_setjmp:
453       return 22;
454     case ARM::BR_JTr:
455     case ARM::BR_JTm:
456     case ARM::BR_JTadd:
457     case ARM::tBR_JTr:
458     case ARM::t2BR_JT:
459     case ARM::t2TBB:
460     case ARM::t2TBH: {
461       // These are jumptable branches, i.e. a branch followed by an inlined
462       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
463       // entry is one byte; TBH two byte each.
464       unsigned EntrySize = (Opc == ARM::t2TBB)
465         ? 1 : ((Opc == ARM::t2TBH) ? 2 : 4);
466       unsigned NumOps = TID.getNumOperands();
467       MachineOperand JTOP =
468         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
469       unsigned JTI = JTOP.getIndex();
470       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
471       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
472       assert(JTI < JT.size());
473       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
474       // 4 aligned. The assembler / linker may add 2 byte padding just before
475       // the JT entries.  The size does not include this padding; the
476       // constant islands pass does separate bookkeeping for it.
477       // FIXME: If we know the size of the function is less than (1 << 16) *2
478       // bytes, we can use 16-bit entries instead. Then there won't be an
479       // alignment issue.
480       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
481       unsigned NumEntries = getNumJTEntries(JT, JTI);
482       if (Opc == ARM::t2TBB && (NumEntries & 1))
483         // Make sure the instruction that follows TBB is 2-byte aligned.
484         // FIXME: Constant island pass should insert an "ALIGN" instruction
485         // instead.
486         ++NumEntries;
487       return NumEntries * EntrySize + InstSize;
488     }
489     default:
490       // Otherwise, pseudo-instruction sizes are zero.
491       return 0;
492     }
493   }
494   }
495   return 0; // Not reached
496 }
497
498 /// Return true if the instruction is a register to register move and
499 /// leave the source and dest operands in the passed parameters.
500 ///
501 bool
502 ARMBaseInstrInfo::isMoveInstr(const MachineInstr &MI,
503                               unsigned &SrcReg, unsigned &DstReg,
504                               unsigned& SrcSubIdx, unsigned& DstSubIdx) const {
505   SrcSubIdx = DstSubIdx = 0; // No sub-registers.
506
507   switch (MI.getOpcode()) {
508   default: break;
509   case ARM::FCPYS:
510   case ARM::FCPYD:
511   case ARM::VMOVD:
512   case ARM::VMOVQ: {
513     SrcReg = MI.getOperand(1).getReg();
514     DstReg = MI.getOperand(0).getReg();
515     return true;
516   }
517   case ARM::MOVr:
518   case ARM::tMOVr:
519   case ARM::tMOVgpr2tgpr:
520   case ARM::tMOVtgpr2gpr:
521   case ARM::tMOVgpr2gpr:
522   case ARM::t2MOVr: {
523     assert(MI.getDesc().getNumOperands() >= 2 &&
524            MI.getOperand(0).isReg() &&
525            MI.getOperand(1).isReg() &&
526            "Invalid ARM MOV instruction");
527     SrcReg = MI.getOperand(1).getReg();
528     DstReg = MI.getOperand(0).getReg();
529     return true;
530   }
531   }
532
533   return false;
534 }
535
536 unsigned
537 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
538                                       int &FrameIndex) const {
539   switch (MI->getOpcode()) {
540   default: break;
541   case ARM::LDR:
542   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
543     if (MI->getOperand(1).isFI() &&
544         MI->getOperand(2).isReg() &&
545         MI->getOperand(3).isImm() &&
546         MI->getOperand(2).getReg() == 0 &&
547         MI->getOperand(3).getImm() == 0) {
548       FrameIndex = MI->getOperand(1).getIndex();
549       return MI->getOperand(0).getReg();
550     }
551     break;
552   case ARM::t2LDRi12:
553   case ARM::tRestore:
554     if (MI->getOperand(1).isFI() &&
555         MI->getOperand(2).isImm() &&
556         MI->getOperand(2).getImm() == 0) {
557       FrameIndex = MI->getOperand(1).getIndex();
558       return MI->getOperand(0).getReg();
559     }
560     break;
561   case ARM::FLDD:
562   case ARM::FLDS:
563     if (MI->getOperand(1).isFI() &&
564         MI->getOperand(2).isImm() &&
565         MI->getOperand(2).getImm() == 0) {
566       FrameIndex = MI->getOperand(1).getIndex();
567       return MI->getOperand(0).getReg();
568     }
569     break;
570   }
571
572   return 0;
573 }
574
575 unsigned
576 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
577                                      int &FrameIndex) const {
578   switch (MI->getOpcode()) {
579   default: break;
580   case ARM::STR:
581   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
582     if (MI->getOperand(1).isFI() &&
583         MI->getOperand(2).isReg() &&
584         MI->getOperand(3).isImm() &&
585         MI->getOperand(2).getReg() == 0 &&
586         MI->getOperand(3).getImm() == 0) {
587       FrameIndex = MI->getOperand(1).getIndex();
588       return MI->getOperand(0).getReg();
589     }
590     break;
591   case ARM::t2STRi12:
592   case ARM::tSpill:
593     if (MI->getOperand(1).isFI() &&
594         MI->getOperand(2).isImm() &&
595         MI->getOperand(2).getImm() == 0) {
596       FrameIndex = MI->getOperand(1).getIndex();
597       return MI->getOperand(0).getReg();
598     }
599     break;
600   case ARM::FSTD:
601   case ARM::FSTS:
602     if (MI->getOperand(1).isFI() &&
603         MI->getOperand(2).isImm() &&
604         MI->getOperand(2).getImm() == 0) {
605       FrameIndex = MI->getOperand(1).getIndex();
606       return MI->getOperand(0).getReg();
607     }
608     break;
609   }
610
611   return 0;
612 }
613
614 bool
615 ARMBaseInstrInfo::copyRegToReg(MachineBasicBlock &MBB,
616                                MachineBasicBlock::iterator I,
617                                unsigned DestReg, unsigned SrcReg,
618                                const TargetRegisterClass *DestRC,
619                                const TargetRegisterClass *SrcRC) const {
620   DebugLoc DL = DebugLoc::getUnknownLoc();
621   if (I != MBB.end()) DL = I->getDebugLoc();
622
623   if (DestRC != SrcRC) {
624     if (DestRC->getSize() != SrcRC->getSize())
625       return false;
626
627     // Allow DPR / DPR_VFP2 / DPR_8 cross-class copies.
628     // Allow QPR / QPR_VFP2 / QPR_8 cross-class copies.
629     if (DestRC->getSize() != 8 && DestRC->getSize() != 16)
630       return false;
631   }
632
633   if (DestRC == ARM::GPRRegisterClass) {
634     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr),
635                                         DestReg).addReg(SrcReg)));
636   } else if (DestRC == ARM::SPRRegisterClass) {
637     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FCPYS), DestReg)
638                    .addReg(SrcReg));
639   } else if (DestRC == ARM::DPRRegisterClass) {
640     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FCPYD), DestReg)
641                    .addReg(SrcReg));
642   } else if (DestRC == ARM::DPR_VFP2RegisterClass ||
643              DestRC == ARM::DPR_8RegisterClass ||
644              SrcRC == ARM::DPR_VFP2RegisterClass ||
645              SrcRC == ARM::DPR_8RegisterClass) {
646     // Always use neon reg-reg move if source or dest is NEON-only regclass.
647     BuildMI(MBB, I, DL, get(ARM::VMOVD), DestReg).addReg(SrcReg);
648   } else if (DestRC == ARM::QPRRegisterClass ||
649              DestRC == ARM::QPR_VFP2RegisterClass ||
650              DestRC == ARM::QPR_8RegisterClass) {
651     BuildMI(MBB, I, DL, get(ARM::VMOVQ), DestReg).addReg(SrcReg);
652   } else {
653     return false;
654   }
655
656   return true;
657 }
658
659 void ARMBaseInstrInfo::
660 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
661                     unsigned SrcReg, bool isKill, int FI,
662                     const TargetRegisterClass *RC) const {
663   DebugLoc DL = DebugLoc::getUnknownLoc();
664   if (I != MBB.end()) DL = I->getDebugLoc();
665   MachineFunction &MF = *MBB.getParent();
666   MachineFrameInfo &MFI = *MF.getFrameInfo();
667
668   MachineMemOperand *MMO =
669     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FI),
670                             MachineMemOperand::MOStore, 0,
671                             MFI.getObjectSize(FI),
672                             MFI.getObjectAlignment(FI));
673
674   if (RC == ARM::GPRRegisterClass) {
675     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STR))
676                    .addReg(SrcReg, getKillRegState(isKill))
677                    .addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO));
678   } else if (RC == ARM::DPRRegisterClass ||
679              RC == ARM::DPR_VFP2RegisterClass ||
680              RC == ARM::DPR_8RegisterClass) {
681     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FSTD))
682                    .addReg(SrcReg, getKillRegState(isKill))
683                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
684   } else if (RC == ARM::SPRRegisterClass) {
685     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FSTS))
686                    .addReg(SrcReg, getKillRegState(isKill))
687                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
688   } else {
689     assert((RC == ARM::QPRRegisterClass ||
690             RC == ARM::QPR_VFP2RegisterClass) && "Unknown regclass!");
691     // FIXME: Neon instructions should support predicates
692     BuildMI(MBB, I, DL, get(ARM::VSTRQ)).addReg(SrcReg, getKillRegState(isKill))
693       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
694   }
695 }
696
697 void ARMBaseInstrInfo::
698 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
699                      unsigned DestReg, int FI,
700                      const TargetRegisterClass *RC) const {
701   DebugLoc DL = DebugLoc::getUnknownLoc();
702   if (I != MBB.end()) DL = I->getDebugLoc();
703   MachineFunction &MF = *MBB.getParent();
704   MachineFrameInfo &MFI = *MF.getFrameInfo();
705
706   MachineMemOperand *MMO =
707     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FI),
708                             MachineMemOperand::MOLoad, 0,
709                             MFI.getObjectSize(FI),
710                             MFI.getObjectAlignment(FI));
711
712   if (RC == ARM::GPRRegisterClass) {
713     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDR), DestReg)
714                    .addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO));
715   } else if (RC == ARM::DPRRegisterClass ||
716              RC == ARM::DPR_VFP2RegisterClass ||
717              RC == ARM::DPR_8RegisterClass) {
718     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FLDD), DestReg)
719                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
720   } else if (RC == ARM::SPRRegisterClass) {
721     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FLDS), DestReg)
722                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
723   } else {
724     assert((RC == ARM::QPRRegisterClass ||
725             RC == ARM::QPR_VFP2RegisterClass ||
726             RC == ARM::QPR_8RegisterClass) && "Unknown regclass!");
727     // FIXME: Neon instructions should support predicates
728     BuildMI(MBB, I, DL, get(ARM::VLDRQ), DestReg).addFrameIndex(FI).addImm(0).
729       addMemOperand(MMO);
730   }
731 }
732
733 MachineInstr *ARMBaseInstrInfo::
734 foldMemoryOperandImpl(MachineFunction &MF, MachineInstr *MI,
735                       const SmallVectorImpl<unsigned> &Ops, int FI) const {
736   if (Ops.size() != 1) return NULL;
737
738   unsigned OpNum = Ops[0];
739   unsigned Opc = MI->getOpcode();
740   MachineInstr *NewMI = NULL;
741   if (Opc == ARM::MOVr || Opc == ARM::t2MOVr) {
742     // If it is updating CPSR, then it cannot be folded.
743     if (MI->getOperand(4).getReg() == ARM::CPSR && !MI->getOperand(4).isDead())
744       return NULL;
745     unsigned Pred = MI->getOperand(2).getImm();
746     unsigned PredReg = MI->getOperand(3).getReg();
747     if (OpNum == 0) { // move -> store
748       unsigned SrcReg = MI->getOperand(1).getReg();
749       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
750       bool isKill = MI->getOperand(1).isKill();
751       bool isUndef = MI->getOperand(1).isUndef();
752       if (Opc == ARM::MOVr)
753         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::STR))
754           .addReg(SrcReg,
755                   getKillRegState(isKill) | getUndefRegState(isUndef),
756                   SrcSubReg)
757           .addFrameIndex(FI).addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
758       else // ARM::t2MOVr
759         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2STRi12))
760           .addReg(SrcReg,
761                   getKillRegState(isKill) | getUndefRegState(isUndef),
762                   SrcSubReg)
763           .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
764     } else {          // move -> load
765       unsigned DstReg = MI->getOperand(0).getReg();
766       unsigned DstSubReg = MI->getOperand(0).getSubReg();
767       bool isDead = MI->getOperand(0).isDead();
768       bool isUndef = MI->getOperand(0).isUndef();
769       if (Opc == ARM::MOVr)
770         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::LDR))
771           .addReg(DstReg,
772                   RegState::Define |
773                   getDeadRegState(isDead) |
774                   getUndefRegState(isUndef), DstSubReg)
775           .addFrameIndex(FI).addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
776       else // ARM::t2MOVr
777         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2LDRi12))
778           .addReg(DstReg,
779                   RegState::Define |
780                   getDeadRegState(isDead) |
781                   getUndefRegState(isUndef), DstSubReg)
782           .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
783     }
784   } else if (Opc == ARM::tMOVgpr2gpr ||
785              Opc == ARM::tMOVtgpr2gpr ||
786              Opc == ARM::tMOVgpr2tgpr) {
787     if (OpNum == 0) { // move -> store
788       unsigned SrcReg = MI->getOperand(1).getReg();
789       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
790       bool isKill = MI->getOperand(1).isKill();
791       bool isUndef = MI->getOperand(1).isUndef();
792       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2STRi12))
793         .addReg(SrcReg,
794                 getKillRegState(isKill) | getUndefRegState(isUndef),
795                 SrcSubReg)
796         .addFrameIndex(FI).addImm(0).addImm(ARMCC::AL).addReg(0);
797     } else {          // move -> load
798       unsigned DstReg = MI->getOperand(0).getReg();
799       unsigned DstSubReg = MI->getOperand(0).getSubReg();
800       bool isDead = MI->getOperand(0).isDead();
801       bool isUndef = MI->getOperand(0).isUndef();
802       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2LDRi12))
803         .addReg(DstReg,
804                 RegState::Define |
805                 getDeadRegState(isDead) |
806                 getUndefRegState(isUndef),
807                 DstSubReg)
808         .addFrameIndex(FI).addImm(0).addImm(ARMCC::AL).addReg(0);
809     }
810   } else if (Opc == ARM::FCPYS) {
811     unsigned Pred = MI->getOperand(2).getImm();
812     unsigned PredReg = MI->getOperand(3).getReg();
813     if (OpNum == 0) { // move -> store
814       unsigned SrcReg = MI->getOperand(1).getReg();
815       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
816       bool isKill = MI->getOperand(1).isKill();
817       bool isUndef = MI->getOperand(1).isUndef();
818       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FSTS))
819         .addReg(SrcReg, getKillRegState(isKill) | getUndefRegState(isUndef),
820                 SrcSubReg)
821         .addFrameIndex(FI)
822         .addImm(0).addImm(Pred).addReg(PredReg);
823     } else {          // move -> load
824       unsigned DstReg = MI->getOperand(0).getReg();
825       unsigned DstSubReg = MI->getOperand(0).getSubReg();
826       bool isDead = MI->getOperand(0).isDead();
827       bool isUndef = MI->getOperand(0).isUndef();
828       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FLDS))
829         .addReg(DstReg,
830                 RegState::Define |
831                 getDeadRegState(isDead) |
832                 getUndefRegState(isUndef),
833                 DstSubReg)
834         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
835     }
836   }
837   else if (Opc == ARM::FCPYD) {
838     unsigned Pred = MI->getOperand(2).getImm();
839     unsigned PredReg = MI->getOperand(3).getReg();
840     if (OpNum == 0) { // move -> store
841       unsigned SrcReg = MI->getOperand(1).getReg();
842       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
843       bool isKill = MI->getOperand(1).isKill();
844       bool isUndef = MI->getOperand(1).isUndef();
845       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FSTD))
846         .addReg(SrcReg,
847                 getKillRegState(isKill) | getUndefRegState(isUndef),
848                 SrcSubReg)
849         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
850     } else {          // move -> load
851       unsigned DstReg = MI->getOperand(0).getReg();
852       unsigned DstSubReg = MI->getOperand(0).getSubReg();
853       bool isDead = MI->getOperand(0).isDead();
854       bool isUndef = MI->getOperand(0).isUndef();
855       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FLDD))
856         .addReg(DstReg,
857                 RegState::Define |
858                 getDeadRegState(isDead) |
859                 getUndefRegState(isUndef),
860                 DstSubReg)
861         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
862     }
863   }
864
865   return NewMI;
866 }
867
868 MachineInstr*
869 ARMBaseInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
870                                         MachineInstr* MI,
871                                         const SmallVectorImpl<unsigned> &Ops,
872                                         MachineInstr* LoadMI) const {
873   // FIXME
874   return 0;
875 }
876
877 bool
878 ARMBaseInstrInfo::canFoldMemoryOperand(const MachineInstr *MI,
879                                    const SmallVectorImpl<unsigned> &Ops) const {
880   if (Ops.size() != 1) return false;
881
882   unsigned Opc = MI->getOpcode();
883   if (Opc == ARM::MOVr || Opc == ARM::t2MOVr) {
884     // If it is updating CPSR, then it cannot be folded.
885     return MI->getOperand(4).getReg() != ARM::CPSR ||
886       MI->getOperand(4).isDead();
887   } else if (Opc == ARM::tMOVgpr2gpr ||
888              Opc == ARM::tMOVtgpr2gpr ||
889              Opc == ARM::tMOVgpr2tgpr) {
890     return true;
891   } else if (Opc == ARM::FCPYS || Opc == ARM::FCPYD) {
892     return true;
893   } else if (Opc == ARM::VMOVD || Opc == ARM::VMOVQ) {
894     return false; // FIXME
895   }
896
897   return false;
898 }
899
900 bool ARMBaseInstrInfo::isIdentical(const MachineInstr *MI0,
901                                   const MachineInstr *MI1,
902                                   const MachineRegisterInfo *MRI) const {
903   int Opcode = MI0->getOpcode();
904   if (Opcode == ARM::t2LDRpci_pic || Opcode == ARM::tLDRpci_pic) {
905     if (MI1->getOpcode() != Opcode)
906       return false;
907     if (MI0->getNumOperands() != MI1->getNumOperands())
908       return false;
909
910     const MachineOperand &MO0 = MI0->getOperand(1);
911     const MachineOperand &MO1 = MI1->getOperand(1);
912     if (MO0.getOffset() != MO1.getOffset())
913       return false;
914
915     const MachineFunction *MF = MI0->getParent()->getParent();
916     const MachineConstantPool *MCP = MF->getConstantPool();
917     int CPI0 = MO0.getIndex();
918     int CPI1 = MO1.getIndex();
919     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
920     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
921     ARMConstantPoolValue *ACPV0 =
922       static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
923     ARMConstantPoolValue *ACPV1 =
924       static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
925     return ACPV0->hasSameValue(ACPV1);
926   }
927
928   return TargetInstrInfoImpl::isIdentical(MI0, MI1, MRI);
929 }
930
931 /// getInstrPredicate - If instruction is predicated, returns its predicate
932 /// condition, otherwise returns AL. It also returns the condition code
933 /// register by reference.
934 ARMCC::CondCodes
935 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
936   int PIdx = MI->findFirstPredOperandIdx();
937   if (PIdx == -1) {
938     PredReg = 0;
939     return ARMCC::AL;
940   }
941
942   PredReg = MI->getOperand(PIdx+1).getReg();
943   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
944 }
945
946
947 int llvm::getMatchingCondBranchOpcode(int Opc) {
948   if (Opc == ARM::B)
949     return ARM::Bcc;
950   else if (Opc == ARM::tB)
951     return ARM::tBcc;
952   else if (Opc == ARM::t2B)
953       return ARM::t2Bcc;
954
955   llvm_unreachable("Unknown unconditional branch opcode!");
956   return 0;
957 }
958
959
960 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
961                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
962                                unsigned DestReg, unsigned BaseReg, int NumBytes,
963                                ARMCC::CondCodes Pred, unsigned PredReg,
964                                const ARMBaseInstrInfo &TII) {
965   bool isSub = NumBytes < 0;
966   if (isSub) NumBytes = -NumBytes;
967
968   while (NumBytes) {
969     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
970     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
971     assert(ThisVal && "Didn't extract field correctly");
972
973     // We will handle these bits from offset, clear them.
974     NumBytes &= ~ThisVal;
975
976     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
977
978     // Build the new ADD / SUB.
979     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
980     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
981       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
982       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
983     BaseReg = DestReg;
984   }
985 }
986
987 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
988                                 unsigned FrameReg, int &Offset,
989                                 const ARMBaseInstrInfo &TII) {
990   unsigned Opcode = MI.getOpcode();
991   const TargetInstrDesc &Desc = MI.getDesc();
992   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
993   bool isSub = false;
994
995   // Memory operands in inline assembly always use AddrMode2.
996   if (Opcode == ARM::INLINEASM)
997     AddrMode = ARMII::AddrMode2;
998
999   if (Opcode == ARM::ADDri) {
1000     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1001     if (Offset == 0) {
1002       // Turn it into a move.
1003       MI.setDesc(TII.get(ARM::MOVr));
1004       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1005       MI.RemoveOperand(FrameRegIdx+1);
1006       Offset = 0;
1007       return true;
1008     } else if (Offset < 0) {
1009       Offset = -Offset;
1010       isSub = true;
1011       MI.setDesc(TII.get(ARM::SUBri));
1012     }
1013
1014     // Common case: small offset, fits into instruction.
1015     if (ARM_AM::getSOImmVal(Offset) != -1) {
1016       // Replace the FrameIndex with sp / fp
1017       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1018       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1019       Offset = 0;
1020       return true;
1021     }
1022
1023     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1024     // as possible.
1025     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1026     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1027
1028     // We will handle these bits from offset, clear them.
1029     Offset &= ~ThisImmVal;
1030
1031     // Get the properly encoded SOImmVal field.
1032     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1033            "Bit extraction didn't work?");
1034     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1035  } else {
1036     unsigned ImmIdx = 0;
1037     int InstrOffs = 0;
1038     unsigned NumBits = 0;
1039     unsigned Scale = 1;
1040     switch (AddrMode) {
1041     case ARMII::AddrMode2: {
1042       ImmIdx = FrameRegIdx+2;
1043       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1044       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1045         InstrOffs *= -1;
1046       NumBits = 12;
1047       break;
1048     }
1049     case ARMII::AddrMode3: {
1050       ImmIdx = FrameRegIdx+2;
1051       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1052       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1053         InstrOffs *= -1;
1054       NumBits = 8;
1055       break;
1056     }
1057     case ARMII::AddrMode4:
1058       // Can't fold any offset even if it's zero.
1059       return false;
1060     case ARMII::AddrMode5: {
1061       ImmIdx = FrameRegIdx+1;
1062       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1063       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1064         InstrOffs *= -1;
1065       NumBits = 8;
1066       Scale = 4;
1067       break;
1068     }
1069     default:
1070       llvm_unreachable("Unsupported addressing mode!");
1071       break;
1072     }
1073
1074     Offset += InstrOffs * Scale;
1075     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1076     if (Offset < 0) {
1077       Offset = -Offset;
1078       isSub = true;
1079     }
1080
1081     // Attempt to fold address comp. if opcode has offset bits
1082     if (NumBits > 0) {
1083       // Common case: small offset, fits into instruction.
1084       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1085       int ImmedOffset = Offset / Scale;
1086       unsigned Mask = (1 << NumBits) - 1;
1087       if ((unsigned)Offset <= Mask * Scale) {
1088         // Replace the FrameIndex with sp
1089         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1090         if (isSub)
1091           ImmedOffset |= 1 << NumBits;
1092         ImmOp.ChangeToImmediate(ImmedOffset);
1093         Offset = 0;
1094         return true;
1095       }
1096
1097       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1098       ImmedOffset = ImmedOffset & Mask;
1099       if (isSub)
1100         ImmedOffset |= 1 << NumBits;
1101       ImmOp.ChangeToImmediate(ImmedOffset);
1102       Offset &= ~(Mask*Scale);
1103     }
1104   }
1105
1106   Offset = (isSub) ? -Offset : Offset;
1107   return Offset == 0;
1108 }