Modify the comparison optimizations in the peephole optimizer to update the
[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 "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMGenInstrInfo.inc"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/PseudoSourceValue.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 using namespace llvm;
38
39 static cl::opt<bool>
40 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
41                cl::desc("Enable ARM 2-addr to 3-addr conv"));
42
43 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
44   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
45     Subtarget(STI) {
46 }
47
48 MachineInstr *
49 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
50                                         MachineBasicBlock::iterator &MBBI,
51                                         LiveVariables *LV) const {
52   // FIXME: Thumb2 support.
53
54   if (!EnableARM3Addr)
55     return NULL;
56
57   MachineInstr *MI = MBBI;
58   MachineFunction &MF = *MI->getParent()->getParent();
59   uint64_t TSFlags = MI->getDesc().TSFlags;
60   bool isPre = false;
61   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
62   default: return NULL;
63   case ARMII::IndexModePre:
64     isPre = true;
65     break;
66   case ARMII::IndexModePost:
67     break;
68   }
69
70   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
71   // operation.
72   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
73   if (MemOpc == 0)
74     return NULL;
75
76   MachineInstr *UpdateMI = NULL;
77   MachineInstr *MemMI = NULL;
78   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
79   const TargetInstrDesc &TID = MI->getDesc();
80   unsigned NumOps = TID.getNumOperands();
81   bool isLoad = !TID.mayStore();
82   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
83   const MachineOperand &Base = MI->getOperand(2);
84   const MachineOperand &Offset = MI->getOperand(NumOps-3);
85   unsigned WBReg = WB.getReg();
86   unsigned BaseReg = Base.getReg();
87   unsigned OffReg = Offset.getReg();
88   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
89   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
90   switch (AddrMode) {
91   default:
92     assert(false && "Unknown indexed op!");
93     return NULL;
94   case ARMII::AddrMode2: {
95     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
96     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
97     if (OffReg == 0) {
98       if (ARM_AM::getSOImmVal(Amt) == -1)
99         // Can't encode it in a so_imm operand. This transformation will
100         // add more than 1 instruction. Abandon!
101         return NULL;
102       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
103                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
104         .addReg(BaseReg).addImm(Amt)
105         .addImm(Pred).addReg(0).addReg(0);
106     } else if (Amt != 0) {
107       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
108       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
109       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
110                          get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
111         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
112         .addImm(Pred).addReg(0).addReg(0);
113     } else
114       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
115                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
116         .addReg(BaseReg).addReg(OffReg)
117         .addImm(Pred).addReg(0).addReg(0);
118     break;
119   }
120   case ARMII::AddrMode3 : {
121     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
122     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
123     if (OffReg == 0)
124       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
125       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
126                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
127         .addReg(BaseReg).addImm(Amt)
128         .addImm(Pred).addReg(0).addReg(0);
129     else
130       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
131                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
132         .addReg(BaseReg).addReg(OffReg)
133         .addImm(Pred).addReg(0).addReg(0);
134     break;
135   }
136   }
137
138   std::vector<MachineInstr*> NewMIs;
139   if (isPre) {
140     if (isLoad)
141       MemMI = BuildMI(MF, MI->getDebugLoc(),
142                       get(MemOpc), MI->getOperand(0).getReg())
143         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
144     else
145       MemMI = BuildMI(MF, MI->getDebugLoc(),
146                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
147         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
148     NewMIs.push_back(MemMI);
149     NewMIs.push_back(UpdateMI);
150   } else {
151     if (isLoad)
152       MemMI = BuildMI(MF, MI->getDebugLoc(),
153                       get(MemOpc), MI->getOperand(0).getReg())
154         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
155     else
156       MemMI = BuildMI(MF, MI->getDebugLoc(),
157                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
158         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
159     if (WB.isDead())
160       UpdateMI->getOperand(0).setIsDead();
161     NewMIs.push_back(UpdateMI);
162     NewMIs.push_back(MemMI);
163   }
164
165   // Transfer LiveVariables states, kill / dead info.
166   if (LV) {
167     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
168       MachineOperand &MO = MI->getOperand(i);
169       if (MO.isReg() && MO.getReg() &&
170           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
171         unsigned Reg = MO.getReg();
172
173         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
174         if (MO.isDef()) {
175           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
176           if (MO.isDead())
177             LV->addVirtualRegisterDead(Reg, NewMI);
178         }
179         if (MO.isUse() && MO.isKill()) {
180           for (unsigned j = 0; j < 2; ++j) {
181             // Look at the two new MI's in reverse order.
182             MachineInstr *NewMI = NewMIs[j];
183             if (!NewMI->readsRegister(Reg))
184               continue;
185             LV->addVirtualRegisterKilled(Reg, NewMI);
186             if (VI.removeKill(MI))
187               VI.Kills.push_back(NewMI);
188             break;
189           }
190         }
191       }
192     }
193   }
194
195   MFI->insert(MBBI, NewMIs[1]);
196   MFI->insert(MBBI, NewMIs[0]);
197   return NewMIs[0];
198 }
199
200 bool
201 ARMBaseInstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
202                                         MachineBasicBlock::iterator MI,
203                                         const std::vector<CalleeSavedInfo> &CSI,
204                                         const TargetRegisterInfo *TRI) const {
205   if (CSI.empty())
206     return false;
207
208   DebugLoc DL;
209   if (MI != MBB.end()) DL = MI->getDebugLoc();
210
211   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
212     unsigned Reg = CSI[i].getReg();
213     bool isKill = true;
214
215     // Add the callee-saved register as live-in unless it's LR and
216     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
217     // then it's already added to the function and entry block live-in sets.
218     if (Reg == ARM::LR) {
219       MachineFunction &MF = *MBB.getParent();
220       if (MF.getFrameInfo()->isReturnAddressTaken() &&
221           MF.getRegInfo().isLiveIn(Reg))
222         isKill = false;
223     }
224
225     if (isKill)
226       MBB.addLiveIn(Reg);
227
228     // Insert the spill to the stack frame. The register is killed at the spill
229     // 
230     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
231     storeRegToStackSlot(MBB, MI, Reg, isKill,
232                         CSI[i].getFrameIdx(), RC, TRI);
233   }
234   return true;
235 }
236
237 // Branch analysis.
238 bool
239 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
240                                 MachineBasicBlock *&FBB,
241                                 SmallVectorImpl<MachineOperand> &Cond,
242                                 bool AllowModify) const {
243   // If the block has no terminators, it just falls into the block after it.
244   MachineBasicBlock::iterator I = MBB.end();
245   if (I == MBB.begin())
246     return false;
247   --I;
248   while (I->isDebugValue()) {
249     if (I == MBB.begin())
250       return false;
251     --I;
252   }
253   if (!isUnpredicatedTerminator(I))
254     return false;
255
256   // Get the last instruction in the block.
257   MachineInstr *LastInst = I;
258
259   // If there is only one terminator instruction, process it.
260   unsigned LastOpc = LastInst->getOpcode();
261   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
262     if (isUncondBranchOpcode(LastOpc)) {
263       TBB = LastInst->getOperand(0).getMBB();
264       return false;
265     }
266     if (isCondBranchOpcode(LastOpc)) {
267       // Block ends with fall-through condbranch.
268       TBB = LastInst->getOperand(0).getMBB();
269       Cond.push_back(LastInst->getOperand(1));
270       Cond.push_back(LastInst->getOperand(2));
271       return false;
272     }
273     return true;  // Can't handle indirect branch.
274   }
275
276   // Get the instruction before it if it is a terminator.
277   MachineInstr *SecondLastInst = I;
278
279   // If there are three terminators, we don't know what sort of block this is.
280   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
281     return true;
282
283   // If the block ends with a B and a Bcc, handle it.
284   unsigned SecondLastOpc = SecondLastInst->getOpcode();
285   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
286     TBB =  SecondLastInst->getOperand(0).getMBB();
287     Cond.push_back(SecondLastInst->getOperand(1));
288     Cond.push_back(SecondLastInst->getOperand(2));
289     FBB = LastInst->getOperand(0).getMBB();
290     return false;
291   }
292
293   // If the block ends with two unconditional branches, handle it.  The second
294   // one is not executed, so remove it.
295   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
296     TBB = SecondLastInst->getOperand(0).getMBB();
297     I = LastInst;
298     if (AllowModify)
299       I->eraseFromParent();
300     return false;
301   }
302
303   // ...likewise if it ends with a branch table followed by an unconditional
304   // branch. The branch folder can create these, and we must get rid of them for
305   // correctness of Thumb constant islands.
306   if ((isJumpTableBranchOpcode(SecondLastOpc) ||
307        isIndirectBranchOpcode(SecondLastOpc)) &&
308       isUncondBranchOpcode(LastOpc)) {
309     I = LastInst;
310     if (AllowModify)
311       I->eraseFromParent();
312     return true;
313   }
314
315   // Otherwise, can't handle this.
316   return true;
317 }
318
319
320 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
321   MachineBasicBlock::iterator I = MBB.end();
322   if (I == MBB.begin()) return 0;
323   --I;
324   while (I->isDebugValue()) {
325     if (I == MBB.begin())
326       return 0;
327     --I;
328   }
329   if (!isUncondBranchOpcode(I->getOpcode()) &&
330       !isCondBranchOpcode(I->getOpcode()))
331     return 0;
332
333   // Remove the branch.
334   I->eraseFromParent();
335
336   I = MBB.end();
337
338   if (I == MBB.begin()) return 1;
339   --I;
340   if (!isCondBranchOpcode(I->getOpcode()))
341     return 1;
342
343   // Remove the branch.
344   I->eraseFromParent();
345   return 2;
346 }
347
348 unsigned
349 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
350                                MachineBasicBlock *FBB,
351                                const SmallVectorImpl<MachineOperand> &Cond,
352                                DebugLoc DL) const {
353   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
354   int BOpc   = !AFI->isThumbFunction()
355     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
356   int BccOpc = !AFI->isThumbFunction()
357     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
358
359   // Shouldn't be a fall through.
360   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
361   assert((Cond.size() == 2 || Cond.size() == 0) &&
362          "ARM branch conditions have two components!");
363
364   if (FBB == 0) {
365     if (Cond.empty()) // Unconditional branch?
366       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
367     else
368       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
369         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
370     return 1;
371   }
372
373   // Two-way conditional branch.
374   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
375     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
376   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
377   return 2;
378 }
379
380 bool ARMBaseInstrInfo::
381 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
382   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
383   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
384   return false;
385 }
386
387 bool ARMBaseInstrInfo::
388 PredicateInstruction(MachineInstr *MI,
389                      const SmallVectorImpl<MachineOperand> &Pred) const {
390   unsigned Opc = MI->getOpcode();
391   if (isUncondBranchOpcode(Opc)) {
392     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
393     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
394     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
395     return true;
396   }
397
398   int PIdx = MI->findFirstPredOperandIdx();
399   if (PIdx != -1) {
400     MachineOperand &PMO = MI->getOperand(PIdx);
401     PMO.setImm(Pred[0].getImm());
402     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
403     return true;
404   }
405   return false;
406 }
407
408 bool ARMBaseInstrInfo::
409 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
410                   const SmallVectorImpl<MachineOperand> &Pred2) const {
411   if (Pred1.size() > 2 || Pred2.size() > 2)
412     return false;
413
414   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
415   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
416   if (CC1 == CC2)
417     return true;
418
419   switch (CC1) {
420   default:
421     return false;
422   case ARMCC::AL:
423     return true;
424   case ARMCC::HS:
425     return CC2 == ARMCC::HI;
426   case ARMCC::LS:
427     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
428   case ARMCC::GE:
429     return CC2 == ARMCC::GT;
430   case ARMCC::LE:
431     return CC2 == ARMCC::LT;
432   }
433 }
434
435 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
436                                     std::vector<MachineOperand> &Pred) const {
437   // FIXME: This confuses implicit_def with optional CPSR def.
438   const TargetInstrDesc &TID = MI->getDesc();
439   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
440     return false;
441
442   bool Found = false;
443   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
444     const MachineOperand &MO = MI->getOperand(i);
445     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
446       Pred.push_back(MO);
447       Found = true;
448     }
449   }
450
451   return Found;
452 }
453
454 /// isPredicable - Return true if the specified instruction can be predicated.
455 /// By default, this returns true for every instruction with a
456 /// PredicateOperand.
457 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
458   const TargetInstrDesc &TID = MI->getDesc();
459   if (!TID.isPredicable())
460     return false;
461
462   if ((TID.TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) {
463     ARMFunctionInfo *AFI =
464       MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
465     return AFI->isThumb2Function();
466   }
467   return true;
468 }
469
470 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
471 DISABLE_INLINE
472 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
473                                 unsigned JTI);
474 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
475                                 unsigned JTI) {
476   assert(JTI < JT.size());
477   return JT[JTI].MBBs.size();
478 }
479
480 /// GetInstSize - Return the size of the specified MachineInstr.
481 ///
482 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
483   const MachineBasicBlock &MBB = *MI->getParent();
484   const MachineFunction *MF = MBB.getParent();
485   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
486
487   // Basic size info comes from the TSFlags field.
488   const TargetInstrDesc &TID = MI->getDesc();
489   uint64_t TSFlags = TID.TSFlags;
490
491   unsigned Opc = MI->getOpcode();
492   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
493   default: {
494     // If this machine instr is an inline asm, measure it.
495     if (MI->getOpcode() == ARM::INLINEASM)
496       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
497     if (MI->isLabel())
498       return 0;
499     switch (Opc) {
500     default:
501       llvm_unreachable("Unknown or unset size field for instr!");
502     case TargetOpcode::IMPLICIT_DEF:
503     case TargetOpcode::KILL:
504     case TargetOpcode::PROLOG_LABEL:
505     case TargetOpcode::EH_LABEL:
506     case TargetOpcode::DBG_VALUE:
507       return 0;
508     }
509     break;
510   }
511   case ARMII::Size8Bytes: return 8;          // ARM instruction x 2.
512   case ARMII::Size4Bytes: return 4;          // ARM / Thumb2 instruction.
513   case ARMII::Size2Bytes: return 2;          // Thumb1 instruction.
514   case ARMII::SizeSpecial: {
515     switch (Opc) {
516     case ARM::CONSTPOOL_ENTRY:
517       // If this machine instr is a constant pool entry, its size is recorded as
518       // operand #2.
519       return MI->getOperand(2).getImm();
520     case ARM::Int_eh_sjlj_longjmp:
521       return 16;
522     case ARM::tInt_eh_sjlj_longjmp:
523       return 10;
524     case ARM::Int_eh_sjlj_setjmp:
525     case ARM::Int_eh_sjlj_setjmp_nofp:
526       return 20;
527     case ARM::tInt_eh_sjlj_setjmp:
528     case ARM::t2Int_eh_sjlj_setjmp:
529     case ARM::t2Int_eh_sjlj_setjmp_nofp:
530       return 12;
531     case ARM::BR_JTr:
532     case ARM::BR_JTm:
533     case ARM::BR_JTadd:
534     case ARM::tBR_JTr:
535     case ARM::t2BR_JT:
536     case ARM::t2TBB:
537     case ARM::t2TBH: {
538       // These are jumptable branches, i.e. a branch followed by an inlined
539       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
540       // entry is one byte; TBH two byte each.
541       unsigned EntrySize = (Opc == ARM::t2TBB)
542         ? 1 : ((Opc == ARM::t2TBH) ? 2 : 4);
543       unsigned NumOps = TID.getNumOperands();
544       MachineOperand JTOP =
545         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
546       unsigned JTI = JTOP.getIndex();
547       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
548       assert(MJTI != 0);
549       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
550       assert(JTI < JT.size());
551       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
552       // 4 aligned. The assembler / linker may add 2 byte padding just before
553       // the JT entries.  The size does not include this padding; the
554       // constant islands pass does separate bookkeeping for it.
555       // FIXME: If we know the size of the function is less than (1 << 16) *2
556       // bytes, we can use 16-bit entries instead. Then there won't be an
557       // alignment issue.
558       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
559       unsigned NumEntries = getNumJTEntries(JT, JTI);
560       if (Opc == ARM::t2TBB && (NumEntries & 1))
561         // Make sure the instruction that follows TBB is 2-byte aligned.
562         // FIXME: Constant island pass should insert an "ALIGN" instruction
563         // instead.
564         ++NumEntries;
565       return NumEntries * EntrySize + InstSize;
566     }
567     default:
568       // Otherwise, pseudo-instruction sizes are zero.
569       return 0;
570     }
571   }
572   }
573   return 0; // Not reached
574 }
575
576 unsigned
577 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
578                                       int &FrameIndex) const {
579   switch (MI->getOpcode()) {
580   default: break;
581   case ARM::LDR:
582   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
583     if (MI->getOperand(1).isFI() &&
584         MI->getOperand(2).isReg() &&
585         MI->getOperand(3).isImm() &&
586         MI->getOperand(2).getReg() == 0 &&
587         MI->getOperand(3).getImm() == 0) {
588       FrameIndex = MI->getOperand(1).getIndex();
589       return MI->getOperand(0).getReg();
590     }
591     break;
592   case ARM::t2LDRi12:
593   case ARM::tRestore:
594     if (MI->getOperand(1).isFI() &&
595         MI->getOperand(2).isImm() &&
596         MI->getOperand(2).getImm() == 0) {
597       FrameIndex = MI->getOperand(1).getIndex();
598       return MI->getOperand(0).getReg();
599     }
600     break;
601   case ARM::VLDRD:
602   case ARM::VLDRS:
603     if (MI->getOperand(1).isFI() &&
604         MI->getOperand(2).isImm() &&
605         MI->getOperand(2).getImm() == 0) {
606       FrameIndex = MI->getOperand(1).getIndex();
607       return MI->getOperand(0).getReg();
608     }
609     break;
610   }
611
612   return 0;
613 }
614
615 unsigned
616 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
617                                      int &FrameIndex) const {
618   switch (MI->getOpcode()) {
619   default: break;
620   case ARM::STR:
621   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
622     if (MI->getOperand(1).isFI() &&
623         MI->getOperand(2).isReg() &&
624         MI->getOperand(3).isImm() &&
625         MI->getOperand(2).getReg() == 0 &&
626         MI->getOperand(3).getImm() == 0) {
627       FrameIndex = MI->getOperand(1).getIndex();
628       return MI->getOperand(0).getReg();
629     }
630     break;
631   case ARM::t2STRi12:
632   case ARM::tSpill:
633     if (MI->getOperand(1).isFI() &&
634         MI->getOperand(2).isImm() &&
635         MI->getOperand(2).getImm() == 0) {
636       FrameIndex = MI->getOperand(1).getIndex();
637       return MI->getOperand(0).getReg();
638     }
639     break;
640   case ARM::VSTRD:
641   case ARM::VSTRS:
642     if (MI->getOperand(1).isFI() &&
643         MI->getOperand(2).isImm() &&
644         MI->getOperand(2).getImm() == 0) {
645       FrameIndex = MI->getOperand(1).getIndex();
646       return MI->getOperand(0).getReg();
647     }
648     break;
649   }
650
651   return 0;
652 }
653
654 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
655                                    MachineBasicBlock::iterator I, DebugLoc DL,
656                                    unsigned DestReg, unsigned SrcReg,
657                                    bool KillSrc) const {
658   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
659   bool GPRSrc  = ARM::GPRRegClass.contains(SrcReg);
660
661   if (GPRDest && GPRSrc) {
662     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
663                                   .addReg(SrcReg, getKillRegState(KillSrc))));
664     return;
665   }
666
667   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
668   bool SPRSrc  = ARM::SPRRegClass.contains(SrcReg);
669
670   unsigned Opc;
671   if (SPRDest && SPRSrc)
672     Opc = ARM::VMOVS;
673   else if (GPRDest && SPRSrc)
674     Opc = ARM::VMOVRS;
675   else if (SPRDest && GPRSrc)
676     Opc = ARM::VMOVSR;
677   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
678     Opc = ARM::VMOVD;
679   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
680     Opc = ARM::VMOVQ;
681   else if (ARM::QQPRRegClass.contains(DestReg, SrcReg))
682     Opc = ARM::VMOVQQ;
683   else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg))
684     Opc = ARM::VMOVQQQQ;
685   else
686     llvm_unreachable("Impossible reg-to-reg copy");
687
688   MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
689   MIB.addReg(SrcReg, getKillRegState(KillSrc));
690   if (Opc != ARM::VMOVQQ && Opc != ARM::VMOVQQQQ)
691     AddDefaultPred(MIB);
692 }
693
694 static const
695 MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
696                              unsigned Reg, unsigned SubIdx, unsigned State,
697                              const TargetRegisterInfo *TRI) {
698   if (!SubIdx)
699     return MIB.addReg(Reg, State);
700
701   if (TargetRegisterInfo::isPhysicalRegister(Reg))
702     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
703   return MIB.addReg(Reg, State, SubIdx);
704 }
705
706 void ARMBaseInstrInfo::
707 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
708                     unsigned SrcReg, bool isKill, int FI,
709                     const TargetRegisterClass *RC,
710                     const TargetRegisterInfo *TRI) const {
711   DebugLoc DL;
712   if (I != MBB.end()) DL = I->getDebugLoc();
713   MachineFunction &MF = *MBB.getParent();
714   MachineFrameInfo &MFI = *MF.getFrameInfo();
715   unsigned Align = MFI.getObjectAlignment(FI);
716
717   MachineMemOperand *MMO =
718     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FI),
719                             MachineMemOperand::MOStore, 0,
720                             MFI.getObjectSize(FI),
721                             Align);
722
723   // tGPR is used sometimes in ARM instructions that need to avoid using
724   // certain registers.  Just treat it as GPR here. Likewise, rGPR.
725   if (RC == ARM::tGPRRegisterClass || RC == ARM::tcGPRRegisterClass
726       || RC == ARM::rGPRRegisterClass)
727     RC = ARM::GPRRegisterClass;
728
729   switch (RC->getID()) {
730   case ARM::GPRRegClassID:
731     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STR))
732                    .addReg(SrcReg, getKillRegState(isKill))
733                    .addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO));
734     break;
735   case ARM::SPRRegClassID:
736     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
737                    .addReg(SrcReg, getKillRegState(isKill))
738                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
739     break;
740   case ARM::DPRRegClassID:
741   case ARM::DPR_VFP2RegClassID:
742   case ARM::DPR_8RegClassID:
743     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
744                    .addReg(SrcReg, getKillRegState(isKill))
745                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
746     break;
747   case ARM::QPRRegClassID:
748   case ARM::QPR_VFP2RegClassID:
749   case ARM::QPR_8RegClassID:
750     if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
751       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q))
752                      .addFrameIndex(FI).addImm(16)
753                      .addReg(SrcReg, getKillRegState(isKill))
754                      .addMemOperand(MMO));
755     } else {
756       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQ))
757                      .addReg(SrcReg, getKillRegState(isKill))
758                      .addFrameIndex(FI)
759                      .addImm(ARM_AM::getAM4ModeImm(ARM_AM::ia))
760                      .addMemOperand(MMO));
761     }
762     break;
763   case ARM::QQPRRegClassID:
764   case ARM::QQPR_VFP2RegClassID:
765     if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
766       // FIXME: It's possible to only store part of the QQ register if the
767       // spilled def has a sub-register index.
768       MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VST1d64Q))
769         .addFrameIndex(FI).addImm(16);
770       MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
771       MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
772       MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
773       MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
774       AddDefaultPred(MIB.addMemOperand(MMO));
775     } else {
776       MachineInstrBuilder MIB =
777         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMD))
778                        .addFrameIndex(FI)
779                        .addImm(ARM_AM::getAM4ModeImm(ARM_AM::ia)))
780         .addMemOperand(MMO);
781       MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
782       MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
783       MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
784             AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
785     }
786     break;
787   case ARM::QQQQPRRegClassID: {
788     MachineInstrBuilder MIB =
789       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMD))
790                      .addFrameIndex(FI)
791                      .addImm(ARM_AM::getAM4ModeImm(ARM_AM::ia)))
792       .addMemOperand(MMO);
793     MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
794     MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
795     MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
796     MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
797     MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
798     MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
799     MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
800           AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
801     break;
802   }
803   default:
804     llvm_unreachable("Unknown regclass!");
805   }
806 }
807
808 void ARMBaseInstrInfo::
809 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
810                      unsigned DestReg, int FI,
811                      const TargetRegisterClass *RC,
812                      const TargetRegisterInfo *TRI) const {
813   DebugLoc DL;
814   if (I != MBB.end()) DL = I->getDebugLoc();
815   MachineFunction &MF = *MBB.getParent();
816   MachineFrameInfo &MFI = *MF.getFrameInfo();
817   unsigned Align = MFI.getObjectAlignment(FI);
818   MachineMemOperand *MMO =
819     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FI),
820                             MachineMemOperand::MOLoad, 0,
821                             MFI.getObjectSize(FI),
822                             Align);
823
824   // tGPR is used sometimes in ARM instructions that need to avoid using
825   // certain registers.  Just treat it as GPR here.
826   if (RC == ARM::tGPRRegisterClass || RC == ARM::tcGPRRegisterClass
827       || RC == ARM::rGPRRegisterClass)
828     RC = ARM::GPRRegisterClass;
829
830   switch (RC->getID()) {
831   case ARM::GPRRegClassID:
832     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDR), DestReg)
833                    .addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO));
834     break;
835   case ARM::SPRRegClassID:
836     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
837                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
838     break;
839   case ARM::DPRRegClassID:
840   case ARM::DPR_VFP2RegClassID:
841   case ARM::DPR_8RegClassID:
842     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
843                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
844     break;
845   case ARM::QPRRegClassID:
846   case ARM::QPR_VFP2RegClassID:
847   case ARM::QPR_8RegClassID:
848     if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
849       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q), DestReg)
850                      .addFrameIndex(FI).addImm(16)
851                      .addMemOperand(MMO));
852     } else {
853       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQ), DestReg)
854                      .addFrameIndex(FI)
855                      .addImm(ARM_AM::getAM4ModeImm(ARM_AM::ia))
856                      .addMemOperand(MMO));
857     }
858     break;
859   case ARM::QQPRRegClassID:
860   case ARM::QQPR_VFP2RegClassID:
861     if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
862       MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLD1d64Q));
863       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
864       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
865       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
866       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
867       AddDefaultPred(MIB.addFrameIndex(FI).addImm(16).addMemOperand(MMO));
868     } else {
869       MachineInstrBuilder MIB =
870         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMD))
871                        .addFrameIndex(FI)
872                        .addImm(ARM_AM::getAM4ModeImm(ARM_AM::ia)))
873         .addMemOperand(MMO);
874       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
875       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
876       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
877             AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
878     }
879     break;
880   case ARM::QQQQPRRegClassID: {
881     MachineInstrBuilder MIB =
882       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMD))
883                      .addFrameIndex(FI)
884                      .addImm(ARM_AM::getAM4ModeImm(ARM_AM::ia)))
885       .addMemOperand(MMO);
886     MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
887     MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
888     MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
889     MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
890     MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
891     MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
892     MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
893     AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
894     break;
895   }
896   default:
897     llvm_unreachable("Unknown regclass!");
898   }
899 }
900
901 MachineInstr*
902 ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
903                                            int FrameIx, uint64_t Offset,
904                                            const MDNode *MDPtr,
905                                            DebugLoc DL) const {
906   MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
907     .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
908   return &*MIB;
909 }
910
911 /// Create a copy of a const pool value. Update CPI to the new index and return
912 /// the label UID.
913 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
914   MachineConstantPool *MCP = MF.getConstantPool();
915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
916
917   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
918   assert(MCPE.isMachineConstantPoolEntry() &&
919          "Expecting a machine constantpool entry!");
920   ARMConstantPoolValue *ACPV =
921     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
922
923   unsigned PCLabelId = AFI->createConstPoolEntryUId();
924   ARMConstantPoolValue *NewCPV = 0;
925   // FIXME: The below assumes PIC relocation model and that the function
926   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
927   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
928   // instructions, so that's probably OK, but is PIC always correct when
929   // we get here?
930   if (ACPV->isGlobalValue())
931     NewCPV = new ARMConstantPoolValue(ACPV->getGV(), PCLabelId,
932                                       ARMCP::CPValue, 4);
933   else if (ACPV->isExtSymbol())
934     NewCPV = new ARMConstantPoolValue(MF.getFunction()->getContext(),
935                                       ACPV->getSymbol(), PCLabelId, 4);
936   else if (ACPV->isBlockAddress())
937     NewCPV = new ARMConstantPoolValue(ACPV->getBlockAddress(), PCLabelId,
938                                       ARMCP::CPBlockAddress, 4);
939   else if (ACPV->isLSDA())
940     NewCPV = new ARMConstantPoolValue(MF.getFunction(), PCLabelId,
941                                       ARMCP::CPLSDA, 4);
942   else
943     llvm_unreachable("Unexpected ARM constantpool value type!!");
944   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
945   return PCLabelId;
946 }
947
948 void ARMBaseInstrInfo::
949 reMaterialize(MachineBasicBlock &MBB,
950               MachineBasicBlock::iterator I,
951               unsigned DestReg, unsigned SubIdx,
952               const MachineInstr *Orig,
953               const TargetRegisterInfo &TRI) const {
954   unsigned Opcode = Orig->getOpcode();
955   switch (Opcode) {
956   default: {
957     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
958     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
959     MBB.insert(I, MI);
960     break;
961   }
962   case ARM::tLDRpci_pic:
963   case ARM::t2LDRpci_pic: {
964     MachineFunction &MF = *MBB.getParent();
965     unsigned CPI = Orig->getOperand(1).getIndex();
966     unsigned PCLabelId = duplicateCPV(MF, CPI);
967     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
968                                       DestReg)
969       .addConstantPoolIndex(CPI).addImm(PCLabelId);
970     (*MIB).setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
971     break;
972   }
973   }
974 }
975
976 MachineInstr *
977 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
978   MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
979   switch(Orig->getOpcode()) {
980   case ARM::tLDRpci_pic:
981   case ARM::t2LDRpci_pic: {
982     unsigned CPI = Orig->getOperand(1).getIndex();
983     unsigned PCLabelId = duplicateCPV(MF, CPI);
984     Orig->getOperand(1).setIndex(CPI);
985     Orig->getOperand(2).setImm(PCLabelId);
986     break;
987   }
988   }
989   return MI;
990 }
991
992 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
993                                         const MachineInstr *MI1) const {
994   int Opcode = MI0->getOpcode();
995   if (Opcode == ARM::t2LDRpci ||
996       Opcode == ARM::t2LDRpci_pic ||
997       Opcode == ARM::tLDRpci ||
998       Opcode == ARM::tLDRpci_pic) {
999     if (MI1->getOpcode() != Opcode)
1000       return false;
1001     if (MI0->getNumOperands() != MI1->getNumOperands())
1002       return false;
1003
1004     const MachineOperand &MO0 = MI0->getOperand(1);
1005     const MachineOperand &MO1 = MI1->getOperand(1);
1006     if (MO0.getOffset() != MO1.getOffset())
1007       return false;
1008
1009     const MachineFunction *MF = MI0->getParent()->getParent();
1010     const MachineConstantPool *MCP = MF->getConstantPool();
1011     int CPI0 = MO0.getIndex();
1012     int CPI1 = MO1.getIndex();
1013     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1014     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1015     ARMConstantPoolValue *ACPV0 =
1016       static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1017     ARMConstantPoolValue *ACPV1 =
1018       static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1019     return ACPV0->hasSameValue(ACPV1);
1020   }
1021
1022   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1023 }
1024
1025 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1026 /// determine if two loads are loading from the same base address. It should
1027 /// only return true if the base pointers are the same and the only differences
1028 /// between the two addresses is the offset. It also returns the offsets by
1029 /// reference.
1030 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1031                                                int64_t &Offset1,
1032                                                int64_t &Offset2) const {
1033   // Don't worry about Thumb: just ARM and Thumb2.
1034   if (Subtarget.isThumb1Only()) return false;
1035
1036   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1037     return false;
1038
1039   switch (Load1->getMachineOpcode()) {
1040   default:
1041     return false;
1042   case ARM::LDR:
1043   case ARM::LDRB:
1044   case ARM::LDRD:
1045   case ARM::LDRH:
1046   case ARM::LDRSB:
1047   case ARM::LDRSH:
1048   case ARM::VLDRD:
1049   case ARM::VLDRS:
1050   case ARM::t2LDRi8:
1051   case ARM::t2LDRDi8:
1052   case ARM::t2LDRSHi8:
1053   case ARM::t2LDRi12:
1054   case ARM::t2LDRSHi12:
1055     break;
1056   }
1057
1058   switch (Load2->getMachineOpcode()) {
1059   default:
1060     return false;
1061   case ARM::LDR:
1062   case ARM::LDRB:
1063   case ARM::LDRD:
1064   case ARM::LDRH:
1065   case ARM::LDRSB:
1066   case ARM::LDRSH:
1067   case ARM::VLDRD:
1068   case ARM::VLDRS:
1069   case ARM::t2LDRi8:
1070   case ARM::t2LDRDi8:
1071   case ARM::t2LDRSHi8:
1072   case ARM::t2LDRi12:
1073   case ARM::t2LDRSHi12:
1074     break;
1075   }
1076
1077   // Check if base addresses and chain operands match.
1078   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1079       Load1->getOperand(4) != Load2->getOperand(4))
1080     return false;
1081
1082   // Index should be Reg0.
1083   if (Load1->getOperand(3) != Load2->getOperand(3))
1084     return false;
1085
1086   // Determine the offsets.
1087   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1088       isa<ConstantSDNode>(Load2->getOperand(1))) {
1089     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1090     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1091     return true;
1092   }
1093
1094   return false;
1095 }
1096
1097 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1098 /// determine (in conjuction with areLoadsFromSameBasePtr) if two loads should
1099 /// be scheduled togther. On some targets if two loads are loading from
1100 /// addresses in the same cache line, it's better if they are scheduled
1101 /// together. This function takes two integers that represent the load offsets
1102 /// from the common base address. It returns true if it decides it's desirable
1103 /// to schedule the two loads together. "NumLoads" is the number of loads that
1104 /// have already been scheduled after Load1.
1105 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1106                                                int64_t Offset1, int64_t Offset2,
1107                                                unsigned NumLoads) const {
1108   // Don't worry about Thumb: just ARM and Thumb2.
1109   if (Subtarget.isThumb1Only()) return false;
1110
1111   assert(Offset2 > Offset1);
1112
1113   if ((Offset2 - Offset1) / 8 > 64)
1114     return false;
1115
1116   if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1117     return false;  // FIXME: overly conservative?
1118
1119   // Four loads in a row should be sufficient.
1120   if (NumLoads >= 3)
1121     return false;
1122
1123   return true;
1124 }
1125
1126 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1127                                             const MachineBasicBlock *MBB,
1128                                             const MachineFunction &MF) const {
1129   // Debug info is never a scheduling boundary. It's necessary to be explicit
1130   // due to the special treatment of IT instructions below, otherwise a
1131   // dbg_value followed by an IT will result in the IT instruction being
1132   // considered a scheduling hazard, which is wrong. It should be the actual
1133   // instruction preceding the dbg_value instruction(s), just like it is
1134   // when debug info is not present.
1135   if (MI->isDebugValue())
1136     return false;
1137
1138   // Terminators and labels can't be scheduled around.
1139   if (MI->getDesc().isTerminator() || MI->isLabel())
1140     return true;
1141
1142   // Treat the start of the IT block as a scheduling boundary, but schedule
1143   // t2IT along with all instructions following it.
1144   // FIXME: This is a big hammer. But the alternative is to add all potential
1145   // true and anti dependencies to IT block instructions as implicit operands
1146   // to the t2IT instruction. The added compile time and complexity does not
1147   // seem worth it.
1148   MachineBasicBlock::const_iterator I = MI;
1149   // Make sure to skip any dbg_value instructions
1150   while (++I != MBB->end() && I->isDebugValue())
1151     ;
1152   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1153     return true;
1154
1155   // Don't attempt to schedule around any instruction that defines
1156   // a stack-oriented pointer, as it's unlikely to be profitable. This
1157   // saves compile time, because it doesn't require every single
1158   // stack slot reference to depend on the instruction that does the
1159   // modification.
1160   if (MI->definesRegister(ARM::SP))
1161     return true;
1162
1163   return false;
1164 }
1165
1166 bool ARMBaseInstrInfo::
1167 isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumInstrs) const {
1168   if (!NumInstrs)
1169     return false;
1170   if (Subtarget.getCPUString() == "generic")
1171     // Generic (and overly aggressive) if-conversion limits for testing.
1172     return NumInstrs <= 10;
1173   else if (Subtarget.hasV7Ops())
1174     return NumInstrs <= 3;
1175   return NumInstrs <= 2;
1176 }
1177   
1178 bool ARMBaseInstrInfo::
1179 isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumT,
1180                     MachineBasicBlock &FMBB, unsigned NumF) const {
1181   return NumT && NumF && NumT <= 2 && NumF <= 2;
1182 }
1183
1184 /// getInstrPredicate - If instruction is predicated, returns its predicate
1185 /// condition, otherwise returns AL. It also returns the condition code
1186 /// register by reference.
1187 ARMCC::CondCodes
1188 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1189   int PIdx = MI->findFirstPredOperandIdx();
1190   if (PIdx == -1) {
1191     PredReg = 0;
1192     return ARMCC::AL;
1193   }
1194
1195   PredReg = MI->getOperand(PIdx+1).getReg();
1196   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1197 }
1198
1199
1200 int llvm::getMatchingCondBranchOpcode(int Opc) {
1201   if (Opc == ARM::B)
1202     return ARM::Bcc;
1203   else if (Opc == ARM::tB)
1204     return ARM::tBcc;
1205   else if (Opc == ARM::t2B)
1206       return ARM::t2Bcc;
1207
1208   llvm_unreachable("Unknown unconditional branch opcode!");
1209   return 0;
1210 }
1211
1212
1213 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1214                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1215                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1216                                ARMCC::CondCodes Pred, unsigned PredReg,
1217                                const ARMBaseInstrInfo &TII) {
1218   bool isSub = NumBytes < 0;
1219   if (isSub) NumBytes = -NumBytes;
1220
1221   while (NumBytes) {
1222     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1223     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1224     assert(ThisVal && "Didn't extract field correctly");
1225
1226     // We will handle these bits from offset, clear them.
1227     NumBytes &= ~ThisVal;
1228
1229     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1230
1231     // Build the new ADD / SUB.
1232     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1233     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1234       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1235       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
1236     BaseReg = DestReg;
1237   }
1238 }
1239
1240 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1241                                 unsigned FrameReg, int &Offset,
1242                                 const ARMBaseInstrInfo &TII) {
1243   unsigned Opcode = MI.getOpcode();
1244   const TargetInstrDesc &Desc = MI.getDesc();
1245   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1246   bool isSub = false;
1247
1248   // Memory operands in inline assembly always use AddrMode2.
1249   if (Opcode == ARM::INLINEASM)
1250     AddrMode = ARMII::AddrMode2;
1251
1252   if (Opcode == ARM::ADDri) {
1253     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1254     if (Offset == 0) {
1255       // Turn it into a move.
1256       MI.setDesc(TII.get(ARM::MOVr));
1257       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1258       MI.RemoveOperand(FrameRegIdx+1);
1259       Offset = 0;
1260       return true;
1261     } else if (Offset < 0) {
1262       Offset = -Offset;
1263       isSub = true;
1264       MI.setDesc(TII.get(ARM::SUBri));
1265     }
1266
1267     // Common case: small offset, fits into instruction.
1268     if (ARM_AM::getSOImmVal(Offset) != -1) {
1269       // Replace the FrameIndex with sp / fp
1270       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1271       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1272       Offset = 0;
1273       return true;
1274     }
1275
1276     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1277     // as possible.
1278     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1279     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1280
1281     // We will handle these bits from offset, clear them.
1282     Offset &= ~ThisImmVal;
1283
1284     // Get the properly encoded SOImmVal field.
1285     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1286            "Bit extraction didn't work?");
1287     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1288  } else {
1289     unsigned ImmIdx = 0;
1290     int InstrOffs = 0;
1291     unsigned NumBits = 0;
1292     unsigned Scale = 1;
1293     switch (AddrMode) {
1294     case ARMII::AddrMode2: {
1295       ImmIdx = FrameRegIdx+2;
1296       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1297       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1298         InstrOffs *= -1;
1299       NumBits = 12;
1300       break;
1301     }
1302     case ARMII::AddrMode3: {
1303       ImmIdx = FrameRegIdx+2;
1304       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1305       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1306         InstrOffs *= -1;
1307       NumBits = 8;
1308       break;
1309     }
1310     case ARMII::AddrMode4:
1311     case ARMII::AddrMode6:
1312       // Can't fold any offset even if it's zero.
1313       return false;
1314     case ARMII::AddrMode5: {
1315       ImmIdx = FrameRegIdx+1;
1316       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1317       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1318         InstrOffs *= -1;
1319       NumBits = 8;
1320       Scale = 4;
1321       break;
1322     }
1323     default:
1324       llvm_unreachable("Unsupported addressing mode!");
1325       break;
1326     }
1327
1328     Offset += InstrOffs * Scale;
1329     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1330     if (Offset < 0) {
1331       Offset = -Offset;
1332       isSub = true;
1333     }
1334
1335     // Attempt to fold address comp. if opcode has offset bits
1336     if (NumBits > 0) {
1337       // Common case: small offset, fits into instruction.
1338       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1339       int ImmedOffset = Offset / Scale;
1340       unsigned Mask = (1 << NumBits) - 1;
1341       if ((unsigned)Offset <= Mask * Scale) {
1342         // Replace the FrameIndex with sp
1343         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1344         if (isSub)
1345           ImmedOffset |= 1 << NumBits;
1346         ImmOp.ChangeToImmediate(ImmedOffset);
1347         Offset = 0;
1348         return true;
1349       }
1350
1351       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1352       ImmedOffset = ImmedOffset & Mask;
1353       if (isSub)
1354         ImmedOffset |= 1 << NumBits;
1355       ImmOp.ChangeToImmediate(ImmedOffset);
1356       Offset &= ~(Mask*Scale);
1357     }
1358   }
1359
1360   Offset = (isSub) ? -Offset : Offset;
1361   return Offset == 0;
1362 }
1363
1364 bool ARMBaseInstrInfo::
1365 AnalyzeCompare(const MachineInstr *MI, unsigned &SrcReg, int &CmpValue) const {
1366   switch (MI->getOpcode()) {
1367   default: break;
1368   case ARM::CMPri:
1369   case ARM::CMPzri:
1370   case ARM::t2CMPri:
1371   case ARM::t2CMPzri:
1372     SrcReg = MI->getOperand(0).getReg();
1373     CmpValue = MI->getOperand(1).getImm();
1374     return true;
1375   }
1376
1377   return false;
1378 }
1379
1380 /// ConvertToSetZeroFlag - Convert the instruction to set the "zero" flag so
1381 /// that we can remove a "comparison with zero". Update the iterator *only* if a
1382 /// transformation took place.
1383 bool ARMBaseInstrInfo::
1384 ConvertToSetZeroFlag(MachineInstr *MI, MachineInstr *CmpInstr,
1385                      MachineBasicBlock::iterator &MII) const {
1386   // Conservatively refuse to convert an instruction which isn't in the same BB
1387   // as the comparison.
1388   if (MI->getParent() != CmpInstr->getParent())
1389     return false;
1390
1391   // Check that CPSR isn't set between the comparison instruction and the one we
1392   // want to change.
1393   MachineBasicBlock::const_iterator I = CmpInstr, E = MI;
1394   --I;
1395   for (; I != E; --I) {
1396     const MachineInstr &Instr = *I;
1397
1398     for (unsigned IO = 0, EO = Instr.getNumOperands(); IO != EO; ++IO) {
1399       const MachineOperand &MO = Instr.getOperand(IO);
1400       if (!MO.isReg() || !MO.isDef()) continue;
1401
1402       // This instruction modifies CPSR before the one we want to change. We
1403       // can't do this transformation.
1404       if (MO.getReg() == ARM::CPSR)
1405         return false;
1406     }
1407   }
1408
1409   // Set the "zero" bit in CPSR.
1410   switch (MI->getOpcode()) {
1411   default: break;
1412   case ARM::ADDri:
1413   case ARM::SUBri:
1414   case ARM::t2ADDri:
1415   case ARM::t2SUBri:
1416     MI->RemoveOperand(5);
1417     MachineInstrBuilder(MI)
1418       .addReg(ARM::CPSR, RegState::Define | RegState::Implicit);
1419     MII = llvm::next(MachineBasicBlock::iterator(CmpInstr));
1420     CmpInstr->eraseFromParent();
1421     return true;
1422   }
1423
1424   return false;
1425 }
1426
1427 unsigned
1428 ARMBaseInstrInfo::getNumMicroOps(const MachineInstr *MI,
1429                                  const InstrItineraryData *ItinData) const {
1430   if (!ItinData || ItinData->isEmpty())
1431     return 1;
1432
1433   const TargetInstrDesc &Desc = MI->getDesc();
1434   unsigned Class = Desc.getSchedClass();
1435   unsigned UOps = ItinData->Itineratries[Class].NumMicroOps;
1436   if (UOps)
1437     return UOps;
1438
1439   unsigned Opc = MI->getOpcode();
1440   switch (Opc) {
1441   default:
1442     llvm_unreachable("Unexpected multi-uops instruction!");
1443     break;
1444   case ARM::VLDMQ:
1445   case ARM::VSTMQ:
1446     return 2;
1447
1448   // The number of uOps for load / store multiple are determined by the number
1449   // registers.
1450   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
1451   // same cycle. The scheduling for the first load / store must be done
1452   // separately by assuming the the address is not 64-bit aligned.
1453   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
1454   // is not 64-bit aligned, then AGU would take an extra cycle.
1455   // For VFP / NEON load / store multiple, the formula is
1456   // (#reg / 2) + (#reg % 2) + 1.
1457   case ARM::VLDMD:
1458   case ARM::VLDMS:
1459   case ARM::VLDMD_UPD:
1460   case ARM::VLDMS_UPD:
1461   case ARM::VSTMD:
1462   case ARM::VSTMS:
1463   case ARM::VSTMD_UPD:
1464   case ARM::VSTMS_UPD: {
1465     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
1466     return (NumRegs / 2) + (NumRegs % 2) + 1;
1467   }
1468   case ARM::LDM_RET:
1469   case ARM::LDM:
1470   case ARM::LDM_UPD:
1471   case ARM::STM:
1472   case ARM::STM_UPD:
1473   case ARM::tLDM:
1474   case ARM::tLDM_UPD:
1475   case ARM::tSTM_UPD:
1476   case ARM::tPOP_RET:
1477   case ARM::tPOP:
1478   case ARM::tPUSH:
1479   case ARM::t2LDM_RET:
1480   case ARM::t2LDM:
1481   case ARM::t2LDM_UPD:
1482   case ARM::t2STM:
1483   case ARM::t2STM_UPD: {
1484     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
1485     if (Subtarget.isCortexA8()) {
1486       // 4 registers would be issued: 1, 2, 1.
1487       // 5 registers would be issued: 1, 2, 2.
1488       return 1 + (NumRegs / 2);
1489     } else if (Subtarget.isCortexA9()) {
1490       UOps = (NumRegs / 2);
1491       // If there are odd number of registers or if it's not 64-bit aligned,
1492       // then it takes an extra AGU (Address Generation Unit) cycle.
1493       if ((NumRegs % 2) ||
1494           !MI->hasOneMemOperand() ||
1495           (*MI->memoperands_begin())->getAlignment() < 8)
1496         ++UOps;
1497       return UOps;
1498     } else {
1499       // Assume the worst.
1500       return NumRegs;
1501     }      
1502   }
1503   }
1504 }