Make ARM and Thumb2 32-bit immediate materialization into a single 32-bit pseudo
[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/Compiler.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/Statistic.h"
25 using namespace llvm;
26
27 STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
28 STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
29 STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
30
31 static cl::opt<int> ReduceLimit("t2-reduce-limit",
32                                 cl::init(-1), cl::Hidden);
33 static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
34                                      cl::init(-1), cl::Hidden);
35 static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
36                                      cl::init(-1), cl::Hidden);
37
38 namespace {
39   /// ReduceTable - A static table with information on mapping from wide
40   /// opcodes to narrow
41   struct ReduceEntry {
42     unsigned WideOpc;      // Wide opcode
43     unsigned NarrowOpc1;   // Narrow opcode to transform to
44     unsigned NarrowOpc2;   // Narrow opcode when it's two-address
45     uint8_t  Imm1Limit;    // Limit of immediate field (bits)
46     uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
47     unsigned LowRegs1 : 1; // Only possible if low-registers are used
48     unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
49     unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
50                            // 1 - No cc field.
51                            // 2 - Always set CPSR.
52     unsigned PredCC2  : 2;
53     unsigned Special  : 1; // Needs to be dealt with specially
54   };
55
56   static const ReduceEntry ReduceTable[] = {
57     // Wide,        Narrow1,      Narrow2,     imm1,imm2,  lo1, lo2, P/C, S
58     { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,    0,   1,  0,0, 0 },
59     { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  0,0, 0 },
60     { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,    1,   0,  0,1, 0 },
61     // Note: immediate scale is 4.
62     { ARM::t2ADDrSPi,ARM::tADDrSPi,0,            8,   0,    1,   0,  1,0, 0 },
63     { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  2,2, 1 },
64     { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,    1,   0,  2,0, 1 },
65     { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,    0,   1,  0,0, 0 },
66     { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,    1,   0,  0,0, 0 },
67     { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,    0,   1,  0,0, 0 },
68     { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,    0,   1,  0,0, 0 },
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, 0 },
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,   0,  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,    0,             5,   0,    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,    0,             5,   0,    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::t2LDM_RET,0,           ARM::tPOP_RET, 0,   0,    1,   1,  1,1, 1 },
125     { ARM::t2LDM,   ARM::tLDM,    ARM::tPOP,     0,   0,    1,   1,  1,1, 1 },
126     { ARM::t2STM,   ARM::tSTM,    ARM::tPUSH,    0,   0,    1,   1,  1,1, 1 },
127   };
128
129   class VISIBILITY_HIDDEN Thumb2SizeReduce : public MachineFunctionPass {
130   public:
131     static char ID;
132     Thumb2SizeReduce();
133
134     const Thumb2InstrInfo *TII;
135
136     virtual bool runOnMachineFunction(MachineFunction &MF);
137
138     virtual const char *getPassName() const {
139       return "Thumb2 instruction size reduction pass";
140     }
141
142   private:
143     /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
144     DenseMap<unsigned, unsigned> ReduceOpcodeMap;
145
146     bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
147                          bool is2Addr, ARMCC::CondCodes Pred,
148                          bool LiveCPSR, bool &HasCC, bool &CCDead);
149
150     bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
151                          const ReduceEntry &Entry);
152
153     bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
154                        const ReduceEntry &Entry, bool LiveCPSR);
155
156     /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
157     /// instruction.
158     bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
159                        const ReduceEntry &Entry,
160                        bool LiveCPSR);
161
162     /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
163     /// non-two-address instruction.
164     bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
165                         const ReduceEntry &Entry,
166                         bool LiveCPSR);
167
168     /// ReduceMBB - Reduce width of instructions in the specified basic block.
169     bool ReduceMBB(MachineBasicBlock &MBB);
170   };
171   char Thumb2SizeReduce::ID = 0;
172 }
173
174 Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(&ID) {
175   for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
176     unsigned FromOpc = ReduceTable[i].WideOpc;
177     if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
178       assert(false && "Duplicated entries?");
179   }
180 }
181
182 static bool HasImplicitCPSRDef(const TargetInstrDesc &TID) {
183   for (const unsigned *Regs = TID.ImplicitDefs; *Regs; ++Regs)
184     if (*Regs == ARM::CPSR)
185       return true;
186   return false;
187 }
188
189 bool
190 Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
191                                   bool is2Addr, ARMCC::CondCodes Pred,
192                                   bool LiveCPSR, bool &HasCC, bool &CCDead) {
193   if ((is2Addr  && Entry.PredCC2 == 0) ||
194       (!is2Addr && Entry.PredCC1 == 0)) {
195     if (Pred == ARMCC::AL) {
196       // Not predicated, must set CPSR.
197       if (!HasCC) {
198         // Original instruction was not setting CPSR, but CPSR is not
199         // currently live anyway. It's ok to set it. The CPSR def is
200         // dead though.
201         if (!LiveCPSR) {
202           HasCC = true;
203           CCDead = true;
204           return true;
205         }
206         return false;
207       }
208     } else {
209       // Predicated, must not set CPSR.
210       if (HasCC)
211         return false;
212     }
213   } else if ((is2Addr  && Entry.PredCC2 == 2) ||
214              (!is2Addr && Entry.PredCC1 == 2)) {
215     /// Old opcode has an optional def of CPSR.
216     if (HasCC)
217       return true;
218     // If both old opcode does not implicit CPSR def, then it's not ok since
219     // these new opcodes CPSR def is not meant to be thrown away. e.g. CMP.
220     if (!HasImplicitCPSRDef(MI->getDesc()))
221       return false;
222     HasCC = true;
223   } else {
224     // 16-bit instruction does not set CPSR.
225     if (HasCC)
226       return false;
227   }
228
229   return true;
230 }
231
232 static bool VerifyLowRegs(MachineInstr *MI) {
233   unsigned Opc = MI->getOpcode();
234   bool isPCOk = (Opc == ARM::t2LDM_RET) || (Opc == ARM::t2LDM);
235   bool isLROk = (Opc == ARM::t2STM);
236   bool isSPOk = isPCOk || isLROk || (Opc == ARM::t2ADDrSPi);
237   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
238     const MachineOperand &MO = MI->getOperand(i);
239     if (!MO.isReg() || MO.isImplicit())
240       continue;
241     unsigned Reg = MO.getReg();
242     if (Reg == 0 || Reg == ARM::CPSR)
243       continue;
244     if (isPCOk && Reg == ARM::PC)
245       continue;
246     if (isLROk && Reg == ARM::LR)
247       continue;
248     if (isSPOk && Reg == ARM::SP)
249       continue;
250     if (!isARMLowRegister(Reg))
251       return false;
252   }
253   return true;
254 }
255
256 bool
257 Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
258                                   const ReduceEntry &Entry) {
259   if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
260     return false;
261
262   unsigned Scale = 1;
263   bool HasImmOffset = false;
264   bool HasShift = false;
265   bool isLdStMul = false;
266   unsigned Opc = Entry.NarrowOpc1;
267   unsigned OpNum = 3; // First 'rest' of operands.
268   switch (Entry.WideOpc) {
269   default:
270     llvm_unreachable("Unexpected Thumb2 load / store opcode!");
271   case ARM::t2LDRi12:
272   case ARM::t2STRi12:
273     Scale = 4;
274     HasImmOffset = true;
275     break;
276   case ARM::t2LDRBi12:
277   case ARM::t2STRBi12:
278     HasImmOffset = true;
279     break;
280   case ARM::t2LDRHi12:
281   case ARM::t2STRHi12:
282     Scale = 2;
283     HasImmOffset = true;
284     break;
285   case ARM::t2LDRs:
286   case ARM::t2LDRBs:
287   case ARM::t2LDRHs:
288   case ARM::t2LDRSBs:
289   case ARM::t2LDRSHs:
290   case ARM::t2STRs:
291   case ARM::t2STRBs:
292   case ARM::t2STRHs:
293     HasShift = true;
294     OpNum = 4;
295     break;
296   case ARM::t2LDM_RET:
297   case ARM::t2LDM:
298   case ARM::t2STM: {
299     OpNum = 0;
300     unsigned BaseReg = MI->getOperand(0).getReg();
301     unsigned Mode = MI->getOperand(1).getImm();
302     if (BaseReg == ARM::SP && ARM_AM::getAM4WBFlag(Mode)) {
303       Opc = Entry.NarrowOpc2;
304       OpNum = 2;
305     } else if (Entry.WideOpc == ARM::t2LDM_RET ||
306                !isARMLowRegister(BaseReg) ||
307                !ARM_AM::getAM4WBFlag(Mode) ||
308                ARM_AM::getAM4SubMode(Mode) != ARM_AM::ia) {
309       return false;
310     }
311     isLdStMul = true;
312     break;
313   }
314   }
315
316   unsigned OffsetReg = 0;
317   bool OffsetKill = false;
318   if (HasShift) {
319     OffsetReg  = MI->getOperand(2).getReg();
320     OffsetKill = MI->getOperand(2).isKill();
321     if (MI->getOperand(3).getImm())
322       // Thumb1 addressing mode doesn't support shift.
323       return false;
324   }
325
326   unsigned OffsetImm = 0;
327   if (HasImmOffset) {
328     OffsetImm = MI->getOperand(2).getImm();
329     unsigned MaxOffset = ((1 << Entry.Imm1Limit) - 1) * Scale;
330     if ((OffsetImm & (Scale-1)) || OffsetImm > MaxOffset)
331       // Make sure the immediate field fits.
332       return false;
333   }
334
335   // Add the 16-bit load / store instruction.
336   // FIXME: Thumb1 addressing mode encode both immediate and register offset.
337   DebugLoc dl = MI->getDebugLoc();
338   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, TII->get(Opc));
339   if (!isLdStMul) {
340     MIB.addOperand(MI->getOperand(0)).addOperand(MI->getOperand(1));
341     if (Entry.NarrowOpc1 != ARM::tLDRSB && Entry.NarrowOpc1 != ARM::tLDRSH) {
342       // tLDRSB and tLDRSH do not have an immediate offset field. On the other
343       // hand, it must have an offset register.
344       // FIXME: Remove this special case.
345       MIB.addImm(OffsetImm/Scale);
346     }
347     assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
348
349     MIB.addReg(OffsetReg, getKillRegState(OffsetKill));
350   }
351
352   // Transfer the rest of operands.
353   for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
354     MIB.addOperand(MI->getOperand(OpNum));
355
356   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
357
358   MBB.erase(MI);
359   ++NumLdSts;
360   return true;
361 }
362
363 bool
364 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
365                                 const ReduceEntry &Entry,
366                                 bool LiveCPSR) {
367   if (Entry.LowRegs1 && !VerifyLowRegs(MI))
368     return false;
369
370   const TargetInstrDesc &TID = MI->getDesc();
371   if (TID.mayLoad() || TID.mayStore())
372     return ReduceLoadStore(MBB, MI, Entry);
373
374   unsigned Opc = MI->getOpcode();
375   switch (Opc) {
376   default: break;
377   case ARM::t2ADDSri: 
378   case ARM::t2ADDSrr: {
379     unsigned PredReg = 0;
380     if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
381       switch (Opc) {
382       default: break;
383       case ARM::t2ADDSri: {
384         if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR))
385           return true;
386         // fallthrough
387       }
388       case ARM::t2ADDSrr:
389         return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
390       }
391     }
392     break;
393   }
394   case ARM::t2RSBri:
395   case ARM::t2RSBSri:
396     if (MI->getOperand(2).getImm() == 0)
397       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
398     break;
399   }
400   return false;
401 }
402
403 bool
404 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
405                                 const ReduceEntry &Entry,
406                                 bool LiveCPSR) {
407
408   if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
409     return false;
410
411   const TargetInstrDesc &TID = MI->getDesc();
412   unsigned Reg0 = MI->getOperand(0).getReg();
413   unsigned Reg1 = MI->getOperand(1).getReg();
414   if (Reg0 != Reg1)
415     return false;
416   if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
417     return false;
418   if (Entry.Imm2Limit) {
419     unsigned Imm = MI->getOperand(2).getImm();
420     unsigned Limit = (1 << Entry.Imm2Limit) - 1;
421     if (Imm > Limit)
422       return false;
423   } else {
424     unsigned Reg2 = MI->getOperand(2).getReg();
425     if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
426       return false;
427   }
428
429   // Check if it's possible / necessary to transfer the predicate.
430   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc2);
431   unsigned PredReg = 0;
432   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
433   bool SkipPred = false;
434   if (Pred != ARMCC::AL) {
435     if (!NewTID.isPredicable())
436       // Can't transfer predicate, fail.
437       return false;
438   } else {
439     SkipPred = !NewTID.isPredicable();
440   }
441
442   bool HasCC = false;
443   bool CCDead = false;
444   if (TID.hasOptionalDef()) {
445     unsigned NumOps = TID.getNumOperands();
446     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
447     if (HasCC && MI->getOperand(NumOps-1).isDead())
448       CCDead = true;
449   }
450   if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
451     return false;
452
453   // Add the 16-bit instruction.
454   DebugLoc dl = MI->getDebugLoc();
455   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
456   MIB.addOperand(MI->getOperand(0));
457   if (NewTID.hasOptionalDef()) {
458     if (HasCC)
459       AddDefaultT1CC(MIB, CCDead);
460     else
461       AddNoT1CC(MIB);
462   }
463
464   // Transfer the rest of operands.
465   unsigned NumOps = TID.getNumOperands();
466   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
467     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
468       continue;
469     if (SkipPred && TID.OpInfo[i].isPredicate())
470       continue;
471     MIB.addOperand(MI->getOperand(i));
472   }
473
474   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
475
476   MBB.erase(MI);
477   ++Num2Addrs;
478   return true;
479 }
480
481 bool
482 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
483                                  const ReduceEntry &Entry,
484                                  bool LiveCPSR) {
485   if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
486     return false;
487
488   unsigned Limit = ~0U;
489   unsigned Scale = (Entry.WideOpc == ARM::t2ADDrSPi) ? 4 : 1;
490   if (Entry.Imm1Limit)
491     Limit = ((1 << Entry.Imm1Limit) - 1) * Scale;
492
493   const TargetInstrDesc &TID = MI->getDesc();
494   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
495     if (TID.OpInfo[i].isPredicate())
496       continue;
497     const MachineOperand &MO = MI->getOperand(i);
498     if (MO.isReg()) {
499       unsigned Reg = MO.getReg();
500       if (!Reg || Reg == ARM::CPSR)
501         continue;
502       if (Entry.WideOpc == ARM::t2ADDrSPi && Reg == ARM::SP)
503         continue;
504       if (Entry.LowRegs1 && !isARMLowRegister(Reg))
505         return false;
506     } else if (MO.isImm() &&
507                !TID.OpInfo[i].isPredicate()) {
508       if (((unsigned)MO.getImm()) > Limit || (MO.getImm() & (Scale-1)) != 0)
509         return false;
510     }
511   }
512
513   // Check if it's possible / necessary to transfer the predicate.
514   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc1);
515   unsigned PredReg = 0;
516   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
517   bool SkipPred = false;
518   if (Pred != ARMCC::AL) {
519     if (!NewTID.isPredicable())
520       // Can't transfer predicate, fail.
521       return false;
522   } else {
523     SkipPred = !NewTID.isPredicable();
524   }
525
526   bool HasCC = false;
527   bool CCDead = false;
528   if (TID.hasOptionalDef()) {
529     unsigned NumOps = TID.getNumOperands();
530     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
531     if (HasCC && MI->getOperand(NumOps-1).isDead())
532       CCDead = true;
533   }
534   if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
535     return false;
536
537   // Add the 16-bit instruction.
538   DebugLoc dl = MI->getDebugLoc();
539   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
540   MIB.addOperand(MI->getOperand(0));
541   if (NewTID.hasOptionalDef()) {
542     if (HasCC)
543       AddDefaultT1CC(MIB, CCDead);
544     else
545       AddNoT1CC(MIB);
546   }
547
548   // Transfer the rest of operands.
549   unsigned NumOps = TID.getNumOperands();
550   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
551     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
552       continue;
553     if ((TID.getOpcode() == ARM::t2RSBSri ||
554          TID.getOpcode() == ARM::t2RSBri) && i == 2)
555       // Skip the zero immediate operand, it's now implicit.
556       continue;
557     bool isPred = (i < NumOps && TID.OpInfo[i].isPredicate());
558     if (SkipPred && isPred)
559         continue;
560     const MachineOperand &MO = MI->getOperand(i);
561     if (Scale > 1 && !isPred && MO.isImm())
562       MIB.addImm(MO.getImm() / Scale);
563     else {
564       if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
565         // Skip implicit def of CPSR. Either it's modeled as an optional
566         // def now or it's already an implicit def on the new instruction.
567         continue;
568       MIB.addOperand(MO);
569     }
570   }
571   if (!TID.isPredicable() && NewTID.isPredicable())
572     AddDefaultPred(MIB);
573
574   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
575
576   MBB.erase(MI);
577   ++NumNarrows;
578   return true;
579 }
580
581 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR) {
582   bool HasDef = false;
583   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
584     const MachineOperand &MO = MI.getOperand(i);
585     if (!MO.isReg() || MO.isUndef() || MO.isUse())
586       continue;
587     if (MO.getReg() != ARM::CPSR)
588       continue;
589     if (!MO.isDead())
590       HasDef = true;
591   }
592
593   return HasDef || LiveCPSR;
594 }
595
596 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
597   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
598     const MachineOperand &MO = MI.getOperand(i);
599     if (!MO.isReg() || MO.isUndef() || MO.isDef())
600       continue;
601     if (MO.getReg() != ARM::CPSR)
602       continue;
603     assert(LiveCPSR && "CPSR liveness tracking is wrong!");
604     if (MO.isKill()) {
605       LiveCPSR = false;
606       break;
607     }
608   }
609
610   return LiveCPSR;
611 }
612
613 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
614   bool Modified = false;
615
616   bool LiveCPSR = false;
617   // Yes, CPSR could be livein.
618   for (MachineBasicBlock::const_livein_iterator I = MBB.livein_begin(),
619          E = MBB.livein_end(); I != E; ++I) {
620     if (*I == ARM::CPSR) {
621       LiveCPSR = true;
622       break;
623     }
624   }
625
626   MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
627   MachineBasicBlock::iterator NextMII;
628   for (; MII != E; MII = NextMII) {
629     NextMII = next(MII);
630
631     MachineInstr *MI = &*MII;
632     LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
633
634     unsigned Opcode = MI->getOpcode();
635     DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
636     if (OPI != ReduceOpcodeMap.end()) {
637       const ReduceEntry &Entry = ReduceTable[OPI->second];
638       // Ignore "special" cases for now.
639       if (Entry.Special) {
640         if (ReduceSpecial(MBB, MI, Entry, LiveCPSR)) {
641           Modified = true;
642           MachineBasicBlock::iterator I = prior(NextMII);
643           MI = &*I;
644         }
645         goto ProcessNext;
646       }
647
648       // Try to transform to a 16-bit two-address instruction.
649       if (Entry.NarrowOpc2 && ReduceTo2Addr(MBB, MI, Entry, LiveCPSR)) {
650         Modified = true;
651         MachineBasicBlock::iterator I = prior(NextMII);
652         MI = &*I;
653         goto ProcessNext;
654       }
655
656       // Try to transform ro a 16-bit non-two-address instruction.
657       if (Entry.NarrowOpc1 && ReduceToNarrow(MBB, MI, Entry, LiveCPSR)) {
658         Modified = true;
659         MachineBasicBlock::iterator I = prior(NextMII);
660         MI = &*I;
661       }
662     }
663
664   ProcessNext:
665     LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR);
666   }
667
668   return Modified;
669 }
670
671 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
672   const TargetMachine &TM = MF.getTarget();
673   TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
674
675   bool Modified = false;
676   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
677     Modified |= ReduceMBB(*I);
678   return Modified;
679 }
680
681 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
682 /// reduction pass.
683 FunctionPass *llvm::createThumb2SizeReductionPass() {
684   return new Thumb2SizeReduce();
685 }