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