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 "ARMBaseRegisterInfo.h"
13#include "ARMBaseInstrInfo.h"
14#include "ARMSubtarget.h"
15#include "Thumb2InstrInfo.h"
16#include "MCTargetDesc/ARMAddressingModes.h"
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/Support/CommandLine.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"
25using namespace llvm;
26
27STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
28STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
29STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
30
31static cl::opt<int> ReduceLimit("t2-reduce-limit",
32                                cl::init(-1), cl::Hidden);
33static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
34                                     cl::init(-1), cl::Hidden);
35static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
36                                     cl::init(-1), cl::Hidden);
37
38namespace {
39  /// ReduceTable - A static table with information on mapping from wide
40  /// opcodes to narrow
41  struct ReduceEntry {
42    uint16_t WideOpc;      // Wide opcode
43    uint16_t NarrowOpc1;   // Narrow opcode to transform to
44    uint16_t 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 PartFlag : 1; // 16-bit instruction does partial flag update
54    unsigned Special  : 1; // Needs to be dealt with specially
55  };
56
57  static const ReduceEntry ReduceTable[] = {
58    // Wide,        Narrow1,      Narrow2,     imm1,imm2,  lo1, lo2, P/C, PF, S
59    { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,    0,   1,  0,0, 0,0 },
60    { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  0,0, 0,1 },
61    { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,    1,   0,  0,1, 0,0 },
62    { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  2,2, 0,1 },
63    { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,    1,   0,  2,0, 0,1 },
64    { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,    0,   1,  0,0, 1,0 },
65    { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,    1,   0,  0,0, 1,0 },
66    { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,    0,   1,  0,0, 1,0 },
67    { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,    0,   1,  0,0, 1,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,0 },
70    { ARM::t2CMNzrr, ARM::tCMNz,  0,             0,   0,    1,   0,  2,0, 0,0 },
71    { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,    1,   0,  2,0, 0,0 },
72    { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,    0,   0,  2,0, 0,1 },
73    { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,    0,   1,  0,0, 1,0 },
74    // FIXME: adr.n immediate offset must be multiple of 4.
75    //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,   0,   0,    1,   0,  1,0, 0,0 },
76    { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,    1,   0,  0,0, 1,0 },
77    { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,    0,   1,  0,0, 1,0 },
78    { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,    1,   0,  0,0, 1,0 },
79    { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,    0,   1,  0,0, 1,0 },
80    // FIXME: tMOVi8 and tMVN also partially update CPSR but they are less
81    // likely to cause issue in the loop. As a size / performance workaround,
82    // they are not marked as such.
83    { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 0,0 },
84    { ARM::t2MOVi16,ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 0,1 },
85    // FIXME: Do we need the 16-bit 'S' variant?
86    { ARM::t2MOVr,ARM::tMOVr,     0,             0,   0,    0,   0,  1,0, 0,0 },
87    { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,    0,   1,  0,0, 1,0 },
88    { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,    1,   0,  0,0, 0,0 },
89    { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,    0,   1,  0,0, 1,0 },
90    { ARM::t2REV,   ARM::tREV,    0,             0,   0,    1,   0,  1,0, 0,0 },
91    { ARM::t2REV16, ARM::tREV16,  0,             0,   0,    1,   0,  1,0, 0,0 },
92    { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,    1,   0,  1,0, 0,0 },
93    { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,    0,   1,  0,0, 1,0 },
94    { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,    1,   0,  0,0, 0,1 },
95    { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,    1,   0,  2,0, 0,1 },
96    { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,    0,   1,  0,0, 0,0 },
97    { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  0,0, 0,0 },
98    { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,    1,   0,  0,0, 0,0 },
99    { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  2,2, 0,0 },
100    { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,    1,   0,  2,0, 0,0 },
101    { ARM::t2SXTB,  ARM::tSXTB,   0,             0,   0,    1,   0,  1,0, 0,1 },
102    { ARM::t2SXTH,  ARM::tSXTH,   0,             0,   0,    1,   0,  1,0, 0,1 },
103    { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,    1,   0,  2,0, 0,0 },
104    { ARM::t2UXTB,  ARM::tUXTB,   0,             0,   0,    1,   0,  1,0, 0,1 },
105    { ARM::t2UXTH,  ARM::tUXTH,   0,             0,   0,    1,   0,  1,0, 0,1 },
106
107    // FIXME: Clean this up after splitting each Thumb load / store opcode
108    // into multiple ones.
109    { ARM::t2LDRi12,ARM::tLDRi,   ARM::tLDRspi,  5,   8,    1,   0,  0,0, 0,1 },
110    { ARM::t2LDRs,  ARM::tLDRr,   0,             0,   0,    1,   0,  0,0, 0,1 },
111    { ARM::t2LDRBi12,ARM::tLDRBi, 0,             5,   0,    1,   0,  0,0, 0,1 },
112    { ARM::t2LDRBs, ARM::tLDRBr,  0,             0,   0,    1,   0,  0,0, 0,1 },
113    { ARM::t2LDRHi12,ARM::tLDRHi, 0,             5,   0,    1,   0,  0,0, 0,1 },
114    { ARM::t2LDRHs, ARM::tLDRHr,  0,             0,   0,    1,   0,  0,0, 0,1 },
115    { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,    1,   0,  0,0, 0,1 },
116    { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,    1,   0,  0,0, 0,1 },
117    { ARM::t2STRi12,ARM::tSTRi,   ARM::tSTRspi,  5,   8,    1,   0,  0,0, 0,1 },
118    { ARM::t2STRs,  ARM::tSTRr,   0,             0,   0,    1,   0,  0,0, 0,1 },
119    { ARM::t2STRBi12,ARM::tSTRBi, 0,             5,   0,    1,   0,  0,0, 0,1 },
120    { ARM::t2STRBs, ARM::tSTRBr,  0,             0,   0,    1,   0,  0,0, 0,1 },
121    { ARM::t2STRHi12,ARM::tSTRHi, 0,             5,   0,    1,   0,  0,0, 0,1 },
122    { ARM::t2STRHs, ARM::tSTRHr,  0,             0,   0,    1,   0,  0,0, 0,1 },
123
124    { ARM::t2LDMIA, ARM::tLDMIA,  0,             0,   0,    1,   1,  1,1, 0,1 },
125    { ARM::t2LDMIA_RET,0,         ARM::tPOP_RET, 0,   0,    1,   1,  1,1, 0,1 },
126    { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0,   0,    1,   1,  1,1, 0,1 },
127    // ARM::t2STM (with no basereg writeback) has no Thumb1 equivalent
128    { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0,       0,   0,    1,   1,  1,1, 0,1 },
129    { ARM::t2STMDB_UPD, 0,        ARM::tPUSH,    0,   0,    1,   1,  1,1, 0,1 },
130  };
131
132  class Thumb2SizeReduce : public MachineFunctionPass {
133  public:
134    static char ID;
135    Thumb2SizeReduce();
136
137    const Thumb2InstrInfo *TII;
138    const ARMSubtarget *STI;
139
140    virtual bool runOnMachineFunction(MachineFunction &MF);
141
142    virtual const char *getPassName() const {
143      return "Thumb2 instruction size reduction pass";
144    }
145
146  private:
147    /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
148    DenseMap<unsigned, unsigned> ReduceOpcodeMap;
149
150    bool canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use,
151                             bool IsSelfLoop);
152
153    bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
154                         bool is2Addr, ARMCC::CondCodes Pred,
155                         bool LiveCPSR, bool &HasCC, bool &CCDead);
156
157    bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
158                         const ReduceEntry &Entry);
159
160    bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
161                       const ReduceEntry &Entry, bool LiveCPSR,
162                       MachineInstr *CPSRDef, bool IsSelfLoop);
163
164    /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
165    /// instruction.
166    bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
167                       const ReduceEntry &Entry,
168                       bool LiveCPSR, MachineInstr *CPSRDef,
169                       bool IsSelfLoop);
170
171    /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
172    /// non-two-address instruction.
173    bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
174                        const ReduceEntry &Entry,
175                        bool LiveCPSR, MachineInstr *CPSRDef,
176                        bool IsSelfLoop);
177
178    /// ReduceMBB - Reduce width of instructions in the specified basic block.
179    bool ReduceMBB(MachineBasicBlock &MBB);
180  };
181  char Thumb2SizeReduce::ID = 0;
182}
183
184Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(ID) {
185  for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
186    unsigned FromOpc = ReduceTable[i].WideOpc;
187    if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
188      assert(false && "Duplicated entries?");
189  }
190}
191
192static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
193  for (const uint16_t *Regs = MCID.getImplicitDefs(); *Regs; ++Regs)
194    if (*Regs == ARM::CPSR)
195      return true;
196  return false;
197}
198
199/// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
200/// the 's' 16-bit instruction partially update CPSR. Abort the
201/// transformation to avoid adding false dependency on last CPSR setting
202/// instruction which hurts the ability for out-of-order execution engine
203/// to do register renaming magic.
204/// This function checks if there is a read-of-write dependency between the
205/// last instruction that defines the CPSR and the current instruction. If there
206/// is, then there is no harm done since the instruction cannot be retired
207/// before the CPSR setting instruction anyway.
208/// Note, we are not doing full dependency analysis here for the sake of compile
209/// time. We're not looking for cases like:
210/// r0 = muls ...
211/// r1 = add.w r0, ...
212/// ...
213///    = mul.w r1
214/// In this case it would have been ok to narrow the mul.w to muls since there
215/// are indirect RAW dependency between the muls and the mul.w
216bool
217Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use,
218                                      bool FirstInSelfLoop) {
219  // FIXME: Disable check for -Oz (aka OptimizeForSizeHarder).
220  if (!STI->avoidCPSRPartialUpdate())
221    return false;
222
223  if (!Def)
224    // If this BB loops back to itself, conservatively avoid narrowing the
225    // first instruction that does partial flag update.
226    return FirstInSelfLoop;
227
228  SmallSet<unsigned, 2> Defs;
229  for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
230    const MachineOperand &MO = Def->getOperand(i);
231    if (!MO.isReg() || MO.isUndef() || MO.isUse())
232      continue;
233    unsigned Reg = MO.getReg();
234    if (Reg == 0 || Reg == ARM::CPSR)
235      continue;
236    Defs.insert(Reg);
237  }
238
239  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
240    const MachineOperand &MO = Use->getOperand(i);
241    if (!MO.isReg() || MO.isUndef() || MO.isDef())
242      continue;
243    unsigned Reg = MO.getReg();
244    if (Defs.count(Reg))
245      return false;
246  }
247
248  // No read-after-write dependency. The narrowing will add false dependency.
249  return true;
250}
251
252bool
253Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
254                                  bool is2Addr, ARMCC::CondCodes Pred,
255                                  bool LiveCPSR, bool &HasCC, bool &CCDead) {
256  if ((is2Addr  && Entry.PredCC2 == 0) ||
257      (!is2Addr && Entry.PredCC1 == 0)) {
258    if (Pred == ARMCC::AL) {
259      // Not predicated, must set CPSR.
260      if (!HasCC) {
261        // Original instruction was not setting CPSR, but CPSR is not
262        // currently live anyway. It's ok to set it. The CPSR def is
263        // dead though.
264        if (!LiveCPSR) {
265          HasCC = true;
266          CCDead = true;
267          return true;
268        }
269        return false;
270      }
271    } else {
272      // Predicated, must not set CPSR.
273      if (HasCC)
274        return false;
275    }
276  } else if ((is2Addr  && Entry.PredCC2 == 2) ||
277             (!is2Addr && Entry.PredCC1 == 2)) {
278    /// Old opcode has an optional def of CPSR.
279    if (HasCC)
280      return true;
281    // If old opcode does not implicitly define CPSR, then it's not ok since
282    // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
283    if (!HasImplicitCPSRDef(MI->getDesc()))
284      return false;
285    HasCC = true;
286  } else {
287    // 16-bit instruction does not set CPSR.
288    if (HasCC)
289      return false;
290  }
291
292  return true;
293}
294
295static bool VerifyLowRegs(MachineInstr *MI) {
296  unsigned Opc = MI->getOpcode();
297  bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA     ||
298                 Opc == ARM::t2LDMDB     || Opc == ARM::t2LDMIA_UPD ||
299                 Opc == ARM::t2LDMDB_UPD);
300  bool isLROk = (Opc == ARM::t2STMIA_UPD || Opc == ARM::t2STMDB_UPD);
301  bool isSPOk = isPCOk || isLROk;
302  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
303    const MachineOperand &MO = MI->getOperand(i);
304    if (!MO.isReg() || MO.isImplicit())
305      continue;
306    unsigned Reg = MO.getReg();
307    if (Reg == 0 || Reg == ARM::CPSR)
308      continue;
309    if (isPCOk && Reg == ARM::PC)
310      continue;
311    if (isLROk && Reg == ARM::LR)
312      continue;
313    if (Reg == ARM::SP) {
314      if (isSPOk)
315        continue;
316      if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
317        // Special case for these ldr / str with sp as base register.
318        continue;
319    }
320    if (!isARMLowRegister(Reg))
321      return false;
322  }
323  return true;
324}
325
326bool
327Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
328                                  const ReduceEntry &Entry) {
329  if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
330    return false;
331
332  unsigned Scale = 1;
333  bool HasImmOffset = false;
334  bool HasShift = false;
335  bool HasOffReg = true;
336  bool isLdStMul = false;
337  unsigned Opc = Entry.NarrowOpc1;
338  unsigned OpNum = 3; // First 'rest' of operands.
339  uint8_t  ImmLimit = Entry.Imm1Limit;
340
341  switch (Entry.WideOpc) {
342  default:
343    llvm_unreachable("Unexpected Thumb2 load / store opcode!");
344  case ARM::t2LDRi12:
345  case ARM::t2STRi12:
346    if (MI->getOperand(1).getReg() == ARM::SP) {
347      Opc = Entry.NarrowOpc2;
348      ImmLimit = Entry.Imm2Limit;
349      HasOffReg = false;
350    }
351
352    Scale = 4;
353    HasImmOffset = true;
354    HasOffReg = false;
355    break;
356  case ARM::t2LDRBi12:
357  case ARM::t2STRBi12:
358    HasImmOffset = true;
359    HasOffReg = false;
360    break;
361  case ARM::t2LDRHi12:
362  case ARM::t2STRHi12:
363    Scale = 2;
364    HasImmOffset = true;
365    HasOffReg = false;
366    break;
367  case ARM::t2LDRs:
368  case ARM::t2LDRBs:
369  case ARM::t2LDRHs:
370  case ARM::t2LDRSBs:
371  case ARM::t2LDRSHs:
372  case ARM::t2STRs:
373  case ARM::t2STRBs:
374  case ARM::t2STRHs:
375    HasShift = true;
376    OpNum = 4;
377    break;
378  case ARM::t2LDMIA:
379  case ARM::t2LDMDB: {
380    unsigned BaseReg = MI->getOperand(0).getReg();
381    if (!isARMLowRegister(BaseReg) || Entry.WideOpc != ARM::t2LDMIA)
382      return false;
383
384    // For the non-writeback version (this one), the base register must be
385    // one of the registers being loaded.
386    bool isOK = false;
387    for (unsigned i = 4; i < MI->getNumOperands(); ++i) {
388      if (MI->getOperand(i).getReg() == BaseReg) {
389        isOK = true;
390        break;
391      }
392    }
393
394    if (!isOK)
395      return false;
396
397    OpNum = 0;
398    isLdStMul = true;
399    break;
400  }
401  case ARM::t2LDMIA_RET: {
402    unsigned BaseReg = MI->getOperand(1).getReg();
403    if (BaseReg != ARM::SP)
404      return false;
405    Opc = Entry.NarrowOpc2; // tPOP_RET
406    OpNum = 2;
407    isLdStMul = true;
408    break;
409  }
410  case ARM::t2LDMIA_UPD:
411  case ARM::t2LDMDB_UPD:
412  case ARM::t2STMIA_UPD:
413  case ARM::t2STMDB_UPD: {
414    OpNum = 0;
415
416    unsigned BaseReg = MI->getOperand(1).getReg();
417    if (BaseReg == ARM::SP &&
418        (Entry.WideOpc == ARM::t2LDMIA_UPD ||
419         Entry.WideOpc == ARM::t2STMDB_UPD)) {
420      Opc = Entry.NarrowOpc2; // tPOP or tPUSH
421      OpNum = 2;
422    } else if (!isARMLowRegister(BaseReg) ||
423               (Entry.WideOpc != ARM::t2LDMIA_UPD &&
424                Entry.WideOpc != ARM::t2STMIA_UPD)) {
425      return false;
426    }
427
428    isLdStMul = true;
429    break;
430  }
431  }
432
433  unsigned OffsetReg = 0;
434  bool OffsetKill = false;
435  if (HasShift) {
436    OffsetReg  = MI->getOperand(2).getReg();
437    OffsetKill = MI->getOperand(2).isKill();
438
439    if (MI->getOperand(3).getImm())
440      // Thumb1 addressing mode doesn't support shift.
441      return false;
442  }
443
444  unsigned OffsetImm = 0;
445  if (HasImmOffset) {
446    OffsetImm = MI->getOperand(2).getImm();
447    unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
448
449    if ((OffsetImm & (Scale - 1)) || OffsetImm > MaxOffset)
450      // Make sure the immediate field fits.
451      return false;
452  }
453
454  // Add the 16-bit load / store instruction.
455  DebugLoc dl = MI->getDebugLoc();
456  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, TII->get(Opc));
457  if (!isLdStMul) {
458    MIB.addOperand(MI->getOperand(0));
459    MIB.addOperand(MI->getOperand(1));
460
461    if (HasImmOffset)
462      MIB.addImm(OffsetImm / Scale);
463
464    assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
465
466    if (HasOffReg)
467      MIB.addReg(OffsetReg, getKillRegState(OffsetKill));
468  }
469
470  // Transfer the rest of operands.
471  for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
472    MIB.addOperand(MI->getOperand(OpNum));
473
474  // Transfer memoperands.
475  MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
476
477  // Transfer MI flags.
478  MIB.setMIFlags(MI->getFlags());
479
480  DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
481
482  MBB.erase_instr(MI);
483  ++NumLdSts;
484  return true;
485}
486
487bool
488Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
489                                const ReduceEntry &Entry,
490                                bool LiveCPSR, MachineInstr *CPSRDef,
491                                bool IsSelfLoop) {
492  unsigned Opc = MI->getOpcode();
493  if (Opc == ARM::t2ADDri) {
494    // If the source register is SP, try to reduce to tADDrSPi, otherwise
495    // it's a normal reduce.
496    if (MI->getOperand(1).getReg() != ARM::SP) {
497      if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop))
498        return true;
499      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
500    }
501    // Try to reduce to tADDrSPi.
502    unsigned Imm = MI->getOperand(2).getImm();
503    // The immediate must be in range, the destination register must be a low
504    // reg, the predicate must be "always" and the condition flags must not
505    // be being set.
506    if (Imm & 3 || Imm > 1020)
507      return false;
508    if (!isARMLowRegister(MI->getOperand(0).getReg()))
509      return false;
510    if (MI->getOperand(3).getImm() != ARMCC::AL)
511      return false;
512    const MCInstrDesc &MCID = MI->getDesc();
513    if (MCID.hasOptionalDef() &&
514        MI->getOperand(MCID.getNumOperands()-1).getReg() == ARM::CPSR)
515      return false;
516
517    MachineInstrBuilder MIB = BuildMI(MBB, MI, MI->getDebugLoc(),
518                                      TII->get(ARM::tADDrSPi))
519      .addOperand(MI->getOperand(0))
520      .addOperand(MI->getOperand(1))
521      .addImm(Imm / 4); // The tADDrSPi has an implied scale by four.
522    AddDefaultPred(MIB);
523
524    // Transfer MI flags.
525    MIB.setMIFlags(MI->getFlags());
526
527    DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " <<*MIB);
528
529    MBB.erase_instr(MI);
530    ++NumNarrows;
531    return true;
532  }
533
534  if (Entry.LowRegs1 && !VerifyLowRegs(MI))
535    return false;
536
537  if (MI->mayLoad() || MI->mayStore())
538    return ReduceLoadStore(MBB, MI, Entry);
539
540  switch (Opc) {
541  default: break;
542  case ARM::t2ADDSri:
543  case ARM::t2ADDSrr: {
544    unsigned PredReg = 0;
545    if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
546      switch (Opc) {
547      default: break;
548      case ARM::t2ADDSri: {
549        if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop))
550          return true;
551        // fallthrough
552      }
553      case ARM::t2ADDSrr:
554        return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
555      }
556    }
557    break;
558  }
559  case ARM::t2RSBri:
560  case ARM::t2RSBSri:
561  case ARM::t2SXTB:
562  case ARM::t2SXTH:
563  case ARM::t2UXTB:
564  case ARM::t2UXTH:
565    if (MI->getOperand(2).getImm() == 0)
566      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
567    break;
568  case ARM::t2MOVi16:
569    // Can convert only 'pure' immediate operands, not immediates obtained as
570    // globals' addresses.
571    if (MI->getOperand(1).isImm())
572      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
573    break;
574  case ARM::t2CMPrr: {
575    // Try to reduce to the lo-reg only version first. Why there are two
576    // versions of the instruction is a mystery.
577    // It would be nice to just have two entries in the master table that
578    // are prioritized, but the table assumes a unique entry for each
579    // source insn opcode. So for now, we hack a local entry record to use.
580    static const ReduceEntry NarrowEntry =
581      { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1 };
582    if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, CPSRDef, IsSelfLoop))
583      return true;
584    return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
585  }
586  }
587  return false;
588}
589
590bool
591Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
592                                const ReduceEntry &Entry,
593                                bool LiveCPSR, MachineInstr *CPSRDef,
594                                bool IsSelfLoop) {
595
596  if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
597    return false;
598
599  unsigned Reg0 = MI->getOperand(0).getReg();
600  unsigned Reg1 = MI->getOperand(1).getReg();
601  // t2MUL is "special". The tied source operand is second, not first.
602  if (MI->getOpcode() == ARM::t2MUL) {
603    unsigned Reg2 = MI->getOperand(2).getReg();
604    // Early exit if the regs aren't all low regs.
605    if (!isARMLowRegister(Reg0) || !isARMLowRegister(Reg1)
606        || !isARMLowRegister(Reg2))
607      return false;
608    if (Reg0 != Reg2) {
609      // If the other operand also isn't the same as the destination, we
610      // can't reduce.
611      if (Reg1 != Reg0)
612        return false;
613      // Try to commute the operands to make it a 2-address instruction.
614      MachineInstr *CommutedMI = TII->commuteInstruction(MI);
615      if (!CommutedMI)
616        return false;
617    }
618  } else if (Reg0 != Reg1) {
619    // Try to commute the operands to make it a 2-address instruction.
620    unsigned CommOpIdx1, CommOpIdx2;
621    if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
622        CommOpIdx1 != 1 || MI->getOperand(CommOpIdx2).getReg() != Reg0)
623      return false;
624    MachineInstr *CommutedMI = TII->commuteInstruction(MI);
625    if (!CommutedMI)
626      return false;
627  }
628  if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
629    return false;
630  if (Entry.Imm2Limit) {
631    unsigned Imm = MI->getOperand(2).getImm();
632    unsigned Limit = (1 << Entry.Imm2Limit) - 1;
633    if (Imm > Limit)
634      return false;
635  } else {
636    unsigned Reg2 = MI->getOperand(2).getReg();
637    if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
638      return false;
639  }
640
641  // Check if it's possible / necessary to transfer the predicate.
642  const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
643  unsigned PredReg = 0;
644  ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
645  bool SkipPred = false;
646  if (Pred != ARMCC::AL) {
647    if (!NewMCID.isPredicable())
648      // Can't transfer predicate, fail.
649      return false;
650  } else {
651    SkipPred = !NewMCID.isPredicable();
652  }
653
654  bool HasCC = false;
655  bool CCDead = false;
656  const MCInstrDesc &MCID = MI->getDesc();
657  if (MCID.hasOptionalDef()) {
658    unsigned NumOps = MCID.getNumOperands();
659    HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
660    if (HasCC && MI->getOperand(NumOps-1).isDead())
661      CCDead = true;
662  }
663  if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
664    return false;
665
666  // Avoid adding a false dependency on partial flag update by some 16-bit
667  // instructions which has the 's' bit set.
668  if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
669      canAddPseudoFlagDep(CPSRDef, MI, IsSelfLoop))
670    return false;
671
672  // Add the 16-bit instruction.
673  DebugLoc dl = MI->getDebugLoc();
674  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
675  MIB.addOperand(MI->getOperand(0));
676  if (NewMCID.hasOptionalDef()) {
677    if (HasCC)
678      AddDefaultT1CC(MIB, CCDead);
679    else
680      AddNoT1CC(MIB);
681  }
682
683  // Transfer the rest of operands.
684  unsigned NumOps = MCID.getNumOperands();
685  for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
686    if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
687      continue;
688    if (SkipPred && MCID.OpInfo[i].isPredicate())
689      continue;
690    MIB.addOperand(MI->getOperand(i));
691  }
692
693  // Transfer MI flags.
694  MIB.setMIFlags(MI->getFlags());
695
696  DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
697
698  MBB.erase_instr(MI);
699  ++Num2Addrs;
700  return true;
701}
702
703bool
704Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
705                                 const ReduceEntry &Entry,
706                                 bool LiveCPSR, MachineInstr *CPSRDef,
707                                 bool IsSelfLoop) {
708  if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
709    return false;
710
711  unsigned Limit = ~0U;
712  if (Entry.Imm1Limit)
713    Limit = (1 << Entry.Imm1Limit) - 1;
714
715  const MCInstrDesc &MCID = MI->getDesc();
716  for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
717    if (MCID.OpInfo[i].isPredicate())
718      continue;
719    const MachineOperand &MO = MI->getOperand(i);
720    if (MO.isReg()) {
721      unsigned Reg = MO.getReg();
722      if (!Reg || Reg == ARM::CPSR)
723        continue;
724      if (Entry.LowRegs1 && !isARMLowRegister(Reg))
725        return false;
726    } else if (MO.isImm() &&
727               !MCID.OpInfo[i].isPredicate()) {
728      if (((unsigned)MO.getImm()) > Limit)
729        return false;
730    }
731  }
732
733  // Check if it's possible / necessary to transfer the predicate.
734  const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
735  unsigned PredReg = 0;
736  ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
737  bool SkipPred = false;
738  if (Pred != ARMCC::AL) {
739    if (!NewMCID.isPredicable())
740      // Can't transfer predicate, fail.
741      return false;
742  } else {
743    SkipPred = !NewMCID.isPredicable();
744  }
745
746  bool HasCC = false;
747  bool CCDead = false;
748  if (MCID.hasOptionalDef()) {
749    unsigned NumOps = MCID.getNumOperands();
750    HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
751    if (HasCC && MI->getOperand(NumOps-1).isDead())
752      CCDead = true;
753  }
754  if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
755    return false;
756
757  // Avoid adding a false dependency on partial flag update by some 16-bit
758  // instructions which has the 's' bit set.
759  if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
760      canAddPseudoFlagDep(CPSRDef, MI, IsSelfLoop))
761    return false;
762
763  // Add the 16-bit instruction.
764  DebugLoc dl = MI->getDebugLoc();
765  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
766  MIB.addOperand(MI->getOperand(0));
767  if (NewMCID.hasOptionalDef()) {
768    if (HasCC)
769      AddDefaultT1CC(MIB, CCDead);
770    else
771      AddNoT1CC(MIB);
772  }
773
774  // Transfer the rest of operands.
775  unsigned NumOps = MCID.getNumOperands();
776  for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
777    if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
778      continue;
779    if ((MCID.getOpcode() == ARM::t2RSBSri ||
780         MCID.getOpcode() == ARM::t2RSBri ||
781         MCID.getOpcode() == ARM::t2SXTB ||
782         MCID.getOpcode() == ARM::t2SXTH ||
783         MCID.getOpcode() == ARM::t2UXTB ||
784         MCID.getOpcode() == ARM::t2UXTH) && i == 2)
785      // Skip the zero immediate operand, it's now implicit.
786      continue;
787    bool isPred = (i < NumOps && MCID.OpInfo[i].isPredicate());
788    if (SkipPred && isPred)
789        continue;
790    const MachineOperand &MO = MI->getOperand(i);
791    if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
792      // Skip implicit def of CPSR. Either it's modeled as an optional
793      // def now or it's already an implicit def on the new instruction.
794      continue;
795    MIB.addOperand(MO);
796  }
797  if (!MCID.isPredicable() && NewMCID.isPredicable())
798    AddDefaultPred(MIB);
799
800  // Transfer MI flags.
801  MIB.setMIFlags(MI->getFlags());
802
803  DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB);
804
805  MBB.erase_instr(MI);
806  ++NumNarrows;
807  return true;
808}
809
810static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
811  bool HasDef = false;
812  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
813    const MachineOperand &MO = MI.getOperand(i);
814    if (!MO.isReg() || MO.isUndef() || MO.isUse())
815      continue;
816    if (MO.getReg() != ARM::CPSR)
817      continue;
818
819    DefCPSR = true;
820    if (!MO.isDead())
821      HasDef = true;
822  }
823
824  return HasDef || LiveCPSR;
825}
826
827static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
828  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
829    const MachineOperand &MO = MI.getOperand(i);
830    if (!MO.isReg() || MO.isUndef() || MO.isDef())
831      continue;
832    if (MO.getReg() != ARM::CPSR)
833      continue;
834    assert(LiveCPSR && "CPSR liveness tracking is wrong!");
835    if (MO.isKill()) {
836      LiveCPSR = false;
837      break;
838    }
839  }
840
841  return LiveCPSR;
842}
843
844bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
845  bool Modified = false;
846
847  // Yes, CPSR could be livein.
848  bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
849  MachineInstr *CPSRDef = 0;
850  MachineInstr *BundleMI = 0;
851
852  // If this BB loops back to itself, conservatively avoid narrowing the
853  // first instruction that does partial flag update.
854  bool IsSelfLoop = MBB.isSuccessor(&MBB);
855  MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),E = MBB.instr_end();
856  MachineBasicBlock::instr_iterator NextMII;
857  for (; MII != E; MII = NextMII) {
858    NextMII = llvm::next(MII);
859
860    MachineInstr *MI = &*MII;
861    if (MI->isBundle()) {
862      BundleMI = MI;
863      continue;
864    }
865
866    LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
867
868    unsigned Opcode = MI->getOpcode();
869    DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
870    if (OPI != ReduceOpcodeMap.end()) {
871      const ReduceEntry &Entry = ReduceTable[OPI->second];
872      // Ignore "special" cases for now.
873      if (Entry.Special) {
874        if (ReduceSpecial(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop)) {
875          Modified = true;
876          MachineBasicBlock::instr_iterator I = prior(NextMII);
877          MI = &*I;
878        }
879        goto ProcessNext;
880      }
881
882      // Try to transform to a 16-bit two-address instruction.
883      if (Entry.NarrowOpc2 &&
884          ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop)) {
885        Modified = true;
886        MachineBasicBlock::instr_iterator I = prior(NextMII);
887        MI = &*I;
888        goto ProcessNext;
889      }
890
891      // Try to transform to a 16-bit non-two-address instruction.
892      if (Entry.NarrowOpc1 &&
893          ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop)) {
894        Modified = true;
895        MachineBasicBlock::instr_iterator I = prior(NextMII);
896        MI = &*I;
897      }
898    }
899
900  ProcessNext:
901    if (NextMII != E && MI->isInsideBundle() && !NextMII->isInsideBundle()) {
902      // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
903      // marker is only on the BUNDLE instruction. Process the BUNDLE
904      // instruction as we finish with the bundled instruction to work around
905      // the inconsistency.
906      if (BundleMI->killsRegister(ARM::CPSR))
907        LiveCPSR = false;
908      MachineOperand *MO = BundleMI->findRegisterDefOperand(ARM::CPSR);
909      if (MO && !MO->isDead())
910        LiveCPSR = true;
911    }
912
913    bool DefCPSR = false;
914    LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
915    if (MI->isCall()) {
916      // Calls don't really set CPSR.
917      CPSRDef = 0;
918      IsSelfLoop = false;
919    } else if (DefCPSR) {
920      // This is the last CPSR defining instruction.
921      CPSRDef = MI;
922      IsSelfLoop = false;
923    }
924  }
925
926  return Modified;
927}
928
929bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
930  const TargetMachine &TM = MF.getTarget();
931  TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
932  STI = &TM.getSubtarget<ARMSubtarget>();
933
934  bool Modified = false;
935  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
936    Modified |= ReduceMBB(*I);
937  return Modified;
938}
939
940/// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
941/// reduction pass.
942FunctionPass *llvm::createThumb2SizeReductionPass() {
943  return new Thumb2SizeReduce();
944}
945