Encode the multi-load/store instructions with their respective modes ('ia',
[oota-llvm.git] / lib / Target / ARM / Thumb2SizeReduction.cpp
1 //===-- Thumb2SizeReduction.cpp - Thumb2 code size reduction pass -*- 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 #define DEBUG_TYPE "t2-reduce-size"
11 #include "ARM.h"
12 #include "ARMAddressingModes.h"
13 #include "ARMBaseRegisterInfo.h"
14 #include "ARMBaseInstrInfo.h"
15 #include "Thumb2InstrInfo.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/Statistic.h"
24 using namespace llvm;
25
26 STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
27 STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
28 STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
29
30 static cl::opt<int> ReduceLimit("t2-reduce-limit",
31                                 cl::init(-1), cl::Hidden);
32 static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
33                                      cl::init(-1), cl::Hidden);
34 static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
35                                      cl::init(-1), cl::Hidden);
36
37 namespace {
38   /// ReduceTable - A static table with information on mapping from wide
39   /// opcodes to narrow
40   struct ReduceEntry {
41     unsigned WideOpc;      // Wide opcode
42     unsigned NarrowOpc1;   // Narrow opcode to transform to
43     unsigned NarrowOpc2;   // Narrow opcode when it's two-address
44     uint8_t  Imm1Limit;    // Limit of immediate field (bits)
45     uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
46     unsigned LowRegs1 : 1; // Only possible if low-registers are used
47     unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
48     unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
49                            // 1 - No cc field.
50                            // 2 - Always set CPSR.
51     unsigned PredCC2  : 2;
52     unsigned Special  : 1; // Needs to be dealt with specially
53   };
54
55   static const ReduceEntry ReduceTable[] = {
56     // Wide,        Narrow1,      Narrow2,     imm1,imm2,  lo1, lo2, P/C, S
57     { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,    0,   1,  0,0, 0 },
58     { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  0,0, 0 },
59     { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,    1,   0,  0,1, 0 },
60     // Note: immediate scale is 4.
61     { ARM::t2ADDrSPi,ARM::tADDrSPi,0,            8,   0,    1,   0,  1,0, 0 },
62     { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  2,2, 1 },
63     { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,    1,   0,  2,0, 1 },
64     { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,    0,   1,  0,0, 0 },
65     { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,    1,   0,  0,0, 0 },
66     { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,    0,   1,  0,0, 0 },
67     { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,    0,   1,  0,0, 0 },
68     //FIXME: Disable CMN, as CCodes are backwards from compare expectations
69     //{ ARM::t2CMNrr, ARM::tCMN,    0,             0,   0,    1,   0,  2,0, 0 },
70     { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,    1,   0,  2,0, 0 },
71     { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,    0,   0,  2,0, 0 },
72     { ARM::t2CMPzri,ARM::tCMPzi8, 0,             8,   0,    1,   0,  2,0, 0 },
73     { ARM::t2CMPzrr,ARM::tCMPzhir,0,             0,   0,    0,   0,  2,0, 0 },
74     { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,    0,   1,  0,0, 0 },
75     // FIXME: adr.n immediate offset must be multiple of 4.
76     //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,     0,   0,    1,   0,  1,0, 0 },
77     { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,    1,   0,  0,0, 0 },
78     { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,    0,   1,  0,0, 0 },
79     { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,    1,   0,  0,0, 0 },
80     { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,    0,   1,  0,0, 0 },
81     { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 0 },
82     { ARM::t2MOVi16,ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 1 },
83     // FIXME: Do we need the 16-bit 'S' variant?
84     { ARM::t2MOVr,ARM::tMOVgpr2gpr,0,            0,   0,    0,   0,  1,0, 0 },
85     { ARM::t2MOVCCr,0,            ARM::tMOVCCr,  0,   0,    0,   0,  0,1, 0 },
86     { ARM::t2MOVCCi,0,            ARM::tMOVCCi,  0,   8,    0,   1,  0,1, 0 },
87     { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,    0,   1,  0,0, 0 },
88     { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,    1,   0,  0,0, 0 },
89     { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,    0,   1,  0,0, 0 },
90     { ARM::t2REV,   ARM::tREV,    0,             0,   0,    1,   0,  1,0, 0 },
91     { ARM::t2REV16, ARM::tREV16,  0,             0,   0,    1,   0,  1,0, 0 },
92     { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,    1,   0,  1,0, 0 },
93     { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,    0,   1,  0,0, 0 },
94     { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,    1,   0,  0,0, 1 },
95     { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,    1,   0,  2,0, 1 },
96     { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,    0,   1,  0,0, 0 },
97     { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  0,0, 0 },
98     { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,    1,   0,  0,0, 0 },
99     { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  2,2, 0 },
100     { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,    1,   0,  2,0, 0 },
101     { ARM::t2SXTBr, ARM::tSXTB,   0,             0,   0,    1,   0,  1,0, 0 },
102     { ARM::t2SXTHr, ARM::tSXTH,   0,             0,   0,    1,   0,  1,0, 0 },
103     { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,    1,   0,  2,0, 0 },
104     { ARM::t2UXTBr, ARM::tUXTB,   0,             0,   0,    1,   0,  1,0, 0 },
105     { ARM::t2UXTHr, ARM::tUXTH,   0,             0,   0,    1,   0,  1,0, 0 },
106
107     // FIXME: Clean this up after splitting each Thumb load / store opcode
108     // into multiple ones.
109     { ARM::t2LDRi12,ARM::tLDR,    ARM::tLDRspi,  5,   8,    1,   0,  0,0, 1 },
110     { ARM::t2LDRs,  ARM::tLDR,    0,             0,   0,    1,   0,  0,0, 1 },
111     { ARM::t2LDRBi12,ARM::tLDRB,  0,             5,   0,    1,   0,  0,0, 1 },
112     { ARM::t2LDRBs, ARM::tLDRB,   0,             0,   0,    1,   0,  0,0, 1 },
113     { ARM::t2LDRHi12,ARM::tLDRH,  0,             5,   0,    1,   0,  0,0, 1 },
114     { ARM::t2LDRHs, ARM::tLDRH,   0,             0,   0,    1,   0,  0,0, 1 },
115     { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,    1,   0,  0,0, 1 },
116     { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,    1,   0,  0,0, 1 },
117     { ARM::t2STRi12,ARM::tSTR,    ARM::tSTRspi,  5,   8,    1,   0,  0,0, 1 },
118     { ARM::t2STRs,  ARM::tSTR,    0,             0,   0,    1,   0,  0,0, 1 },
119     { ARM::t2STRBi12,ARM::tSTRB,  0,             5,   0,    1,   0,  0,0, 1 },
120     { ARM::t2STRBs, ARM::tSTRB,   0,             0,   0,    1,   0,  0,0, 1 },
121     { ARM::t2STRHi12,ARM::tSTRH,  0,             5,   0,    1,   0,  0,0, 1 },
122     { ARM::t2STRHs, ARM::tSTRH,   0,             0,   0,    1,   0,  0,0, 1 },
123
124     { ARM::t2LDMIA, ARM::tLDMIA,  0,             0,   0,    1,   1,  1,1, 1 },
125     { ARM::t2LDMIA_RET,0,         ARM::tPOP_RET, 0,   0,    1,   1,  1,1, 1 },
126     { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0,   0,    1,   1,  1,1, 1 },
127     // ARM::t2STM (with no basereg writeback) has no Thumb1 equivalent
128     { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD,ARM::tPUSH,0,  0,    1,   1,  1,1, 1 },
129   };
130
131   class Thumb2SizeReduce : public MachineFunctionPass {
132   public:
133     static char ID;
134     Thumb2SizeReduce();
135
136     const Thumb2InstrInfo *TII;
137
138     virtual bool runOnMachineFunction(MachineFunction &MF);
139
140     virtual const char *getPassName() const {
141       return "Thumb2 instruction size reduction pass";
142     }
143
144   private:
145     /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
146     DenseMap<unsigned, unsigned> ReduceOpcodeMap;
147
148     bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
149                          bool is2Addr, ARMCC::CondCodes Pred,
150                          bool LiveCPSR, bool &HasCC, bool &CCDead);
151
152     bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
153                          const ReduceEntry &Entry);
154
155     bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
156                        const ReduceEntry &Entry, bool LiveCPSR);
157
158     /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
159     /// instruction.
160     bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
161                        const ReduceEntry &Entry,
162                        bool LiveCPSR);
163
164     /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
165     /// non-two-address instruction.
166     bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
167                         const ReduceEntry &Entry,
168                         bool LiveCPSR);
169
170     /// ReduceMBB - Reduce width of instructions in the specified basic block.
171     bool ReduceMBB(MachineBasicBlock &MBB);
172   };
173   char Thumb2SizeReduce::ID = 0;
174 }
175
176 Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(ID) {
177   for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
178     unsigned FromOpc = ReduceTable[i].WideOpc;
179     if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
180       assert(false && "Duplicated entries?");
181   }
182 }
183
184 static bool HasImplicitCPSRDef(const TargetInstrDesc &TID) {
185   for (const unsigned *Regs = TID.ImplicitDefs; *Regs; ++Regs)
186     if (*Regs == ARM::CPSR)
187       return true;
188   return false;
189 }
190
191 bool
192 Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
193                                   bool is2Addr, ARMCC::CondCodes Pred,
194                                   bool LiveCPSR, bool &HasCC, bool &CCDead) {
195   if ((is2Addr  && Entry.PredCC2 == 0) ||
196       (!is2Addr && Entry.PredCC1 == 0)) {
197     if (Pred == ARMCC::AL) {
198       // Not predicated, must set CPSR.
199       if (!HasCC) {
200         // Original instruction was not setting CPSR, but CPSR is not
201         // currently live anyway. It's ok to set it. The CPSR def is
202         // dead though.
203         if (!LiveCPSR) {
204           HasCC = true;
205           CCDead = true;
206           return true;
207         }
208         return false;
209       }
210     } else {
211       // Predicated, must not set CPSR.
212       if (HasCC)
213         return false;
214     }
215   } else if ((is2Addr  && Entry.PredCC2 == 2) ||
216              (!is2Addr && Entry.PredCC1 == 2)) {
217     /// Old opcode has an optional def of CPSR.
218     if (HasCC)
219       return true;
220     // If old opcode does not implicitly define CPSR, then it's not ok since
221     // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
222     if (!HasImplicitCPSRDef(MI->getDesc()))
223       return false;
224     HasCC = true;
225   } else {
226     // 16-bit instruction does not set CPSR.
227     if (HasCC)
228       return false;
229   }
230
231   return true;
232 }
233
234 static bool VerifyLowRegs(MachineInstr *MI) {
235   unsigned Opc = MI->getOpcode();
236   bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA     ||
237                  Opc == ARM::t2LDMDB     || Opc == ARM::t2LDMIA_UPD ||
238                  Opc == ARM::t2LDMDB_UPD);
239   bool isLROk = (Opc == ARM::t2STMIA_UPD || Opc == ARM::t2STMDB_UPD);
240   bool isSPOk = isPCOk || isLROk || (Opc == ARM::t2ADDrSPi);
241   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
242     const MachineOperand &MO = MI->getOperand(i);
243     if (!MO.isReg() || MO.isImplicit())
244       continue;
245     unsigned Reg = MO.getReg();
246     if (Reg == 0 || Reg == ARM::CPSR)
247       continue;
248     if (isPCOk && Reg == ARM::PC)
249       continue;
250     if (isLROk && Reg == ARM::LR)
251       continue;
252     if (Reg == ARM::SP) {
253       if (isSPOk)
254         continue;
255       if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
256         // Special case for these ldr / str with sp as base register.
257         continue;
258     }
259     if (!isARMLowRegister(Reg))
260       return false;
261   }
262   return true;
263 }
264
265 bool
266 Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
267                                   const ReduceEntry &Entry) {
268   if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
269     return false;
270
271   unsigned Scale = 1;
272   bool HasImmOffset = false;
273   bool HasShift = false;
274   bool HasOffReg = true;
275   bool isLdStMul = false;
276   unsigned Opc = Entry.NarrowOpc1;
277   unsigned OpNum = 3; // First 'rest' of operands.
278   uint8_t  ImmLimit = Entry.Imm1Limit;
279
280   switch (Entry.WideOpc) {
281   default:
282     llvm_unreachable("Unexpected Thumb2 load / store opcode!");
283   case ARM::t2LDRi12:
284   case ARM::t2STRi12: {
285     unsigned BaseReg = MI->getOperand(1).getReg();
286     if (BaseReg == ARM::SP) {
287       Opc = Entry.NarrowOpc2;
288       ImmLimit = Entry.Imm2Limit;
289       HasOffReg = false;
290     }
291     Scale = 4;
292     HasImmOffset = true;
293     break;
294   }
295   case ARM::t2LDRBi12:
296   case ARM::t2STRBi12:
297     HasImmOffset = true;
298     break;
299   case ARM::t2LDRHi12:
300   case ARM::t2STRHi12:
301     Scale = 2;
302     HasImmOffset = true;
303     break;
304   case ARM::t2LDRs:
305   case ARM::t2LDRBs:
306   case ARM::t2LDRHs:
307   case ARM::t2LDRSBs:
308   case ARM::t2LDRSHs:
309   case ARM::t2STRs:
310   case ARM::t2STRBs:
311   case ARM::t2STRHs:
312     HasShift = true;
313     OpNum = 4;
314     break;
315   case ARM::t2LDMIA:
316   case ARM::t2LDMDB: {
317     unsigned BaseReg = MI->getOperand(0).getReg();
318     if (!isARMLowRegister(BaseReg) || Entry.WideOpc != ARM::t2LDMIA)
319       return false;
320     // For the non-writeback version (this one), the base register must be
321     // one of the registers being loaded.
322     bool isOK = false;
323     for (unsigned i = 4; i < MI->getNumOperands(); ++i) {
324       if (MI->getOperand(i).getReg() == BaseReg) {
325         isOK = true;
326         break;
327       }
328     }
329     if (!isOK)
330       return false;
331
332     OpNum = 0;
333     isLdStMul = true;
334     break;
335   }
336   case ARM::t2LDMIA_RET: {
337     unsigned BaseReg = MI->getOperand(1).getReg();
338     if (BaseReg != ARM::SP)
339       return false;
340     Opc = Entry.NarrowOpc2; // tPOP_RET
341     OpNum = 2;
342     isLdStMul = true;
343     break;
344   }
345   case ARM::t2LDMIA_UPD:
346   case ARM::t2LDMDB_UPD:
347   case ARM::t2STMIA_UPD:
348   case ARM::t2STMDB_UPD: {
349     OpNum = 0;
350     unsigned BaseReg = MI->getOperand(1).getReg();
351     if (BaseReg == ARM::SP &&
352         (Entry.WideOpc == ARM::t2LDMIA_UPD ||
353          Entry.WideOpc == ARM::t2STMDB_UPD)) {
354       Opc = Entry.NarrowOpc2; // tPOP or tPUSH
355       OpNum = 2;
356     } else if (!isARMLowRegister(BaseReg) ||
357                (Entry.WideOpc != ARM::t2LDMIA_UPD &&
358                 Entry.WideOpc != ARM::t2STMIA_UPD)) {
359       return false;
360     }
361     isLdStMul = true;
362     break;
363   }
364   }
365
366   unsigned OffsetReg = 0;
367   bool OffsetKill = false;
368   if (HasShift) {
369     OffsetReg  = MI->getOperand(2).getReg();
370     OffsetKill = MI->getOperand(2).isKill();
371     if (MI->getOperand(3).getImm())
372       // Thumb1 addressing mode doesn't support shift.
373       return false;
374   }
375
376   unsigned OffsetImm = 0;
377   if (HasImmOffset) {
378     OffsetImm = MI->getOperand(2).getImm();
379     unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
380     if ((OffsetImm & (Scale-1)) || OffsetImm > MaxOffset)
381       // Make sure the immediate field fits.
382       return false;
383   }
384
385   // Add the 16-bit load / store instruction.
386   // FIXME: Thumb1 addressing mode encode both immediate and register offset.
387   DebugLoc dl = MI->getDebugLoc();
388   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, TII->get(Opc));
389   if (!isLdStMul) {
390     MIB.addOperand(MI->getOperand(0)).addOperand(MI->getOperand(1));
391     if (Opc != ARM::tLDRSB && Opc != ARM::tLDRSH) {
392       // tLDRSB and tLDRSH do not have an immediate offset field. On the other
393       // hand, it must have an offset register.
394       // FIXME: Remove this special case.
395       MIB.addImm(OffsetImm/Scale);
396     }
397     assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
398
399     if (HasOffReg)
400       MIB.addReg(OffsetReg, getKillRegState(OffsetKill));
401   }
402
403   // Transfer the rest of operands.
404   for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
405     MIB.addOperand(MI->getOperand(OpNum));
406
407   // Transfer memoperands.
408   (*MIB).setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
409
410   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
411
412   MBB.erase(MI);
413   ++NumLdSts;
414   return true;
415 }
416
417 bool
418 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
419                                 const ReduceEntry &Entry,
420                                 bool LiveCPSR) {
421   if (Entry.LowRegs1 && !VerifyLowRegs(MI))
422     return false;
423
424   const TargetInstrDesc &TID = MI->getDesc();
425   if (TID.mayLoad() || TID.mayStore())
426     return ReduceLoadStore(MBB, MI, Entry);
427
428   unsigned Opc = MI->getOpcode();
429   switch (Opc) {
430   default: break;
431   case ARM::t2ADDSri: 
432   case ARM::t2ADDSrr: {
433     unsigned PredReg = 0;
434     if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
435       switch (Opc) {
436       default: break;
437       case ARM::t2ADDSri: {
438         if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR))
439           return true;
440         // fallthrough
441       }
442       case ARM::t2ADDSrr:
443         return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
444       }
445     }
446     break;
447   }
448   case ARM::t2RSBri:
449   case ARM::t2RSBSri:
450     if (MI->getOperand(2).getImm() == 0)
451       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
452     break;
453   case ARM::t2MOVi16:
454     // Can convert only 'pure' immediate operands, not immediates obtained as
455     // globals' addresses.
456     if (MI->getOperand(1).isImm())
457       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
458     break;
459   }
460   return false;
461 }
462
463 bool
464 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
465                                 const ReduceEntry &Entry,
466                                 bool LiveCPSR) {
467
468   if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
469     return false;
470
471   unsigned Reg0 = MI->getOperand(0).getReg();
472   unsigned Reg1 = MI->getOperand(1).getReg();
473   if (Reg0 != Reg1) {
474     // Try to commute the operands to make it a 2-address instruction.
475     unsigned CommOpIdx1, CommOpIdx2;
476     if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
477         CommOpIdx1 != 1 || MI->getOperand(CommOpIdx2).getReg() != Reg0)
478       return false;
479     MachineInstr *CommutedMI = TII->commuteInstruction(MI);
480     if (!CommutedMI)
481       return false;
482   }
483   if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
484     return false;
485   if (Entry.Imm2Limit) {
486     unsigned Imm = MI->getOperand(2).getImm();
487     unsigned Limit = (1 << Entry.Imm2Limit) - 1;
488     if (Imm > Limit)
489       return false;
490   } else {
491     unsigned Reg2 = MI->getOperand(2).getReg();
492     if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
493       return false;
494   }
495
496   // Check if it's possible / necessary to transfer the predicate.
497   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc2);
498   unsigned PredReg = 0;
499   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
500   bool SkipPred = false;
501   if (Pred != ARMCC::AL) {
502     if (!NewTID.isPredicable())
503       // Can't transfer predicate, fail.
504       return false;
505   } else {
506     SkipPred = !NewTID.isPredicable();
507   }
508
509   bool HasCC = false;
510   bool CCDead = false;
511   const TargetInstrDesc &TID = MI->getDesc();
512   if (TID.hasOptionalDef()) {
513     unsigned NumOps = TID.getNumOperands();
514     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
515     if (HasCC && MI->getOperand(NumOps-1).isDead())
516       CCDead = true;
517   }
518   if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
519     return false;
520
521   // Add the 16-bit instruction.
522   DebugLoc dl = MI->getDebugLoc();
523   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
524   MIB.addOperand(MI->getOperand(0));
525   if (NewTID.hasOptionalDef()) {
526     if (HasCC)
527       AddDefaultT1CC(MIB, CCDead);
528     else
529       AddNoT1CC(MIB);
530   }
531
532   // Transfer the rest of operands.
533   unsigned NumOps = TID.getNumOperands();
534   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
535     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
536       continue;
537     if (SkipPred && TID.OpInfo[i].isPredicate())
538       continue;
539     MIB.addOperand(MI->getOperand(i));
540   }
541
542   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
543
544   MBB.erase(MI);
545   ++Num2Addrs;
546   return true;
547 }
548
549 bool
550 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
551                                  const ReduceEntry &Entry,
552                                  bool LiveCPSR) {
553   if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
554     return false;
555
556   unsigned Limit = ~0U;
557   unsigned Scale = (Entry.WideOpc == ARM::t2ADDrSPi) ? 4 : 1;
558   if (Entry.Imm1Limit)
559     Limit = ((1 << Entry.Imm1Limit) - 1) * Scale;
560
561   const TargetInstrDesc &TID = MI->getDesc();
562   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
563     if (TID.OpInfo[i].isPredicate())
564       continue;
565     const MachineOperand &MO = MI->getOperand(i);
566     if (MO.isReg()) {
567       unsigned Reg = MO.getReg();
568       if (!Reg || Reg == ARM::CPSR)
569         continue;
570       if (Entry.WideOpc == ARM::t2ADDrSPi && Reg == ARM::SP)
571         continue;
572       if (Entry.LowRegs1 && !isARMLowRegister(Reg))
573         return false;
574     } else if (MO.isImm() &&
575                !TID.OpInfo[i].isPredicate()) {
576       if (((unsigned)MO.getImm()) > Limit || (MO.getImm() & (Scale-1)) != 0)
577         return false;
578     }
579   }
580
581   // Check if it's possible / necessary to transfer the predicate.
582   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc1);
583   unsigned PredReg = 0;
584   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
585   bool SkipPred = false;
586   if (Pred != ARMCC::AL) {
587     if (!NewTID.isPredicable())
588       // Can't transfer predicate, fail.
589       return false;
590   } else {
591     SkipPred = !NewTID.isPredicable();
592   }
593
594   bool HasCC = false;
595   bool CCDead = false;
596   if (TID.hasOptionalDef()) {
597     unsigned NumOps = TID.getNumOperands();
598     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
599     if (HasCC && MI->getOperand(NumOps-1).isDead())
600       CCDead = true;
601   }
602   if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
603     return false;
604
605   // Add the 16-bit instruction.
606   DebugLoc dl = MI->getDebugLoc();
607   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
608   MIB.addOperand(MI->getOperand(0));
609   if (NewTID.hasOptionalDef()) {
610     if (HasCC)
611       AddDefaultT1CC(MIB, CCDead);
612     else
613       AddNoT1CC(MIB);
614   }
615
616   // Transfer the rest of operands.
617   unsigned NumOps = TID.getNumOperands();
618   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
619     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
620       continue;
621     if ((TID.getOpcode() == ARM::t2RSBSri ||
622          TID.getOpcode() == ARM::t2RSBri) && i == 2)
623       // Skip the zero immediate operand, it's now implicit.
624       continue;
625     bool isPred = (i < NumOps && TID.OpInfo[i].isPredicate());
626     if (SkipPred && isPred)
627         continue;
628     const MachineOperand &MO = MI->getOperand(i);
629     if (Scale > 1 && !isPred && MO.isImm())
630       MIB.addImm(MO.getImm() / Scale);
631     else {
632       if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
633         // Skip implicit def of CPSR. Either it's modeled as an optional
634         // def now or it's already an implicit def on the new instruction.
635         continue;
636       MIB.addOperand(MO);
637     }
638   }
639   if (!TID.isPredicable() && NewTID.isPredicable())
640     AddDefaultPred(MIB);
641
642   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
643
644   MBB.erase(MI);
645   ++NumNarrows;
646   return true;
647 }
648
649 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR) {
650   bool HasDef = false;
651   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
652     const MachineOperand &MO = MI.getOperand(i);
653     if (!MO.isReg() || MO.isUndef() || MO.isUse())
654       continue;
655     if (MO.getReg() != ARM::CPSR)
656       continue;
657     if (!MO.isDead())
658       HasDef = true;
659   }
660
661   return HasDef || LiveCPSR;
662 }
663
664 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
665   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
666     const MachineOperand &MO = MI.getOperand(i);
667     if (!MO.isReg() || MO.isUndef() || MO.isDef())
668       continue;
669     if (MO.getReg() != ARM::CPSR)
670       continue;
671     assert(LiveCPSR && "CPSR liveness tracking is wrong!");
672     if (MO.isKill()) {
673       LiveCPSR = false;
674       break;
675     }
676   }
677
678   return LiveCPSR;
679 }
680
681 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
682   bool Modified = false;
683
684   // Yes, CPSR could be livein.
685   bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
686
687   MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
688   MachineBasicBlock::iterator NextMII;
689   for (; MII != E; MII = NextMII) {
690     NextMII = llvm::next(MII);
691
692     MachineInstr *MI = &*MII;
693     LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
694
695     unsigned Opcode = MI->getOpcode();
696     DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
697     if (OPI != ReduceOpcodeMap.end()) {
698       const ReduceEntry &Entry = ReduceTable[OPI->second];
699       // Ignore "special" cases for now.
700       if (Entry.Special) {
701         if (ReduceSpecial(MBB, MI, Entry, LiveCPSR)) {
702           Modified = true;
703           MachineBasicBlock::iterator I = prior(NextMII);
704           MI = &*I;
705         }
706         goto ProcessNext;
707       }
708
709       // Try to transform to a 16-bit two-address instruction.
710       if (Entry.NarrowOpc2 && ReduceTo2Addr(MBB, MI, Entry, LiveCPSR)) {
711         Modified = true;
712         MachineBasicBlock::iterator I = prior(NextMII);
713         MI = &*I;
714         goto ProcessNext;
715       }
716
717       // Try to transform to a 16-bit non-two-address instruction.
718       if (Entry.NarrowOpc1 && ReduceToNarrow(MBB, MI, Entry, LiveCPSR)) {
719         Modified = true;
720         MachineBasicBlock::iterator I = prior(NextMII);
721         MI = &*I;
722       }
723     }
724
725   ProcessNext:
726     LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR);
727   }
728
729   return Modified;
730 }
731
732 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
733   const TargetMachine &TM = MF.getTarget();
734   TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
735
736   bool Modified = false;
737   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
738     Modified |= ReduceMBB(*I);
739   return Modified;
740 }
741
742 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
743 /// reduction pass.
744 FunctionPass *llvm::createThumb2SizeReductionPass() {
745   return new Thumb2SizeReduce();
746 }