Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Thumb2SizeReduction.cpp - Thumb2 code size reduction pass -*- C++ -*-=//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "ARM.h"
10
#include "ARMBaseInstrInfo.h"
11
#include "ARMSubtarget.h"
12
#include "MCTargetDesc/ARMBaseInfo.h"
13
#include "Thumb2InstrInfo.h"
14
#include "llvm/ADT/DenseMap.h"
15
#include "llvm/ADT/PostOrderIterator.h"
16
#include "llvm/ADT/STLExtras.h"
17
#include "llvm/ADT/SmallSet.h"
18
#include "llvm/ADT/SmallVector.h"
19
#include "llvm/ADT/Statistic.h"
20
#include "llvm/ADT/StringRef.h"
21
#include "llvm/CodeGen/MachineBasicBlock.h"
22
#include "llvm/CodeGen/MachineFunction.h"
23
#include "llvm/CodeGen/MachineFunctionPass.h"
24
#include "llvm/CodeGen/MachineInstr.h"
25
#include "llvm/CodeGen/MachineInstrBuilder.h"
26
#include "llvm/CodeGen/MachineOperand.h"
27
#include "llvm/CodeGen/TargetInstrInfo.h"
28
#include "llvm/IR/DebugLoc.h"
29
#include "llvm/IR/Function.h"
30
#include "llvm/MC/MCInstrDesc.h"
31
#include "llvm/MC/MCRegisterInfo.h"
32
#include "llvm/Support/CommandLine.h"
33
#include "llvm/Support/Compiler.h"
34
#include "llvm/Support/Debug.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/raw_ostream.h"
37
#include <algorithm>
38
#include <cassert>
39
#include <cstdint>
40
#include <functional>
41
#include <iterator>
42
#include <utility>
43
44
using namespace llvm;
45
46
#define DEBUG_TYPE "t2-reduce-size"
47
61.8k
#define THUMB2_SIZE_REDUCE_NAME "Thumb2 instruction size reduce pass"
48
49
STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
50
STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
51
STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
52
53
static cl::opt<int> ReduceLimit("t2-reduce-limit",
54
                                cl::init(-1), cl::Hidden);
55
static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
56
                                     cl::init(-1), cl::Hidden);
57
static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
58
                                     cl::init(-1), cl::Hidden);
59
60
namespace {
61
62
  /// ReduceTable - A static table with information on mapping from wide
63
  /// opcodes to narrow
64
  struct ReduceEntry {
65
    uint16_t WideOpc;      // Wide opcode
66
    uint16_t NarrowOpc1;   // Narrow opcode to transform to
67
    uint16_t NarrowOpc2;   // Narrow opcode when it's two-address
68
    uint8_t  Imm1Limit;    // Limit of immediate field (bits)
69
    uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
70
    unsigned LowRegs1 : 1; // Only possible if low-registers are used
71
    unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
72
    unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
73
                           // 1 - No cc field.
74
                           // 2 - Always set CPSR.
75
    unsigned PredCC2  : 2;
76
    unsigned PartFlag : 1; // 16-bit instruction does partial flag update
77
    unsigned Special  : 1; // Needs to be dealt with specially
78
    unsigned AvoidMovs: 1; // Avoid movs with shifter operand (for Swift)
79
  };
80
81
  static const ReduceEntry ReduceTable[] = {
82
  // Wide,        Narrow1,      Narrow2,     imm1,imm2, lo1, lo2, P/C,PF,S,AM
83
  { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,   0,   1,  0,0, 0,0,0 },
84
  { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,   1,   1,  0,0, 0,1,0 },
85
  { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,   1,   0,  0,1, 0,0,0 },
86
  { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,   1,   1,  2,2, 0,1,0 },
87
  { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,   1,   0,  2,0, 0,1,0 },
88
  { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,   0,   1,  0,0, 1,0,0 },
89
  { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
90
  { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,   0,   1,  0,0, 1,0,1 },
91
  { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,   0,   1,  0,0, 1,0,0 },
92
  //FIXME: Disable CMN, as CCodes are backwards from compare expectations
93
  //{ ARM::t2CMNrr, ARM::tCMN,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
94
  { ARM::t2CMNzrr, ARM::tCMNz,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
95
  { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,   1,   0,  2,0, 0,0,0 },
96
  { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,   0,   0,  2,0, 0,1,0 },
97
  { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,   0,   1,  0,0, 1,0,0 },
98
  // FIXME: adr.n immediate offset must be multiple of 4.
99
  //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,   0,   0,   1,   0,  1,0, 0,0,0 },
100
  { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
101
  { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,   0,   1,  0,0, 1,0,1 },
102
  { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,   1,   0,  0,0, 1,0,1 },
103
  { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,   0,   1,  0,0, 1,0,1 },
104
  { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,   1,   0,  0,0, 1,0,0 },
105
  { ARM::t2MOVi16,ARM::tMOVi8,  0,             8,   0,   1,   0,  0,0, 1,1,0 },
106
  // FIXME: Do we need the 16-bit 'S' variant?
107
  { ARM::t2MOVr,ARM::tMOVr,     0,             0,   0,   0,   0,  1,0, 0,0,0 },
108
  { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,   0,   1,  0,0, 1,0,0 },
109
  { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,   1,   0,  0,0, 0,0,0 },
110
  { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,   0,   1,  0,0, 1,0,0 },
111
  { ARM::t2REV,   ARM::tREV,    0,             0,   0,   1,   0,  1,0, 0,0,0 },
112
  { ARM::t2REV16, ARM::tREV16,  0,             0,   0,   1,   0,  1,0, 0,0,0 },
113
  { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,   1,   0,  1,0, 0,0,0 },
114
  { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,   0,   1,  0,0, 1,0,0 },
115
  { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,   1,   0,  0,0, 0,1,0 },
116
  { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,   1,   0,  2,0, 0,1,0 },
117
  { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,   0,   1,  0,0, 0,0,0 },
118
  { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,   1,   1,  0,0, 0,0,0 },
119
  { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,   1,   0,  0,0, 0,0,0 },
120
  { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,   1,   1,  2,2, 0,0,0 },
121
  { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,   1,   0,  2,0, 0,0,0 },
122
  { ARM::t2SXTB,  ARM::tSXTB,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
123
  { ARM::t2SXTH,  ARM::tSXTH,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
124
  { ARM::t2TEQrr, ARM::tEOR,    0,             0,   0,   1,   0,  2,0, 0,1,0 },
125
  { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,   1,   0,  2,0, 0,0,0 },
126
  { ARM::t2UXTB,  ARM::tUXTB,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
127
  { ARM::t2UXTH,  ARM::tUXTH,   0,             0,   0,   1,   0,  1,0, 0,1,0 },
128
129
  // FIXME: Clean this up after splitting each Thumb load / store opcode
130
  // into multiple ones.
131
  { ARM::t2LDRi12,ARM::tLDRi,   ARM::tLDRspi,  5,   8,   1,   0,  0,0, 0,1,0 },
132
  { ARM::t2LDRs,  ARM::tLDRr,   0,             0,   0,   1,   0,  0,0, 0,1,0 },
133
  { ARM::t2LDRBi12,ARM::tLDRBi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
134
  { ARM::t2LDRBs, ARM::tLDRBr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
135
  { ARM::t2LDRHi12,ARM::tLDRHi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
136
  { ARM::t2LDRHs, ARM::tLDRHr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
137
  { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
138
  { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
139
  { ARM::t2LDR_POST,ARM::tLDMIA_UPD,0,         0,   0,   1,   0,  0,0, 0,1,0 },
140
  { ARM::t2STRi12,ARM::tSTRi,   ARM::tSTRspi,  5,   8,   1,   0,  0,0, 0,1,0 },
141
  { ARM::t2STRs,  ARM::tSTRr,   0,             0,   0,   1,   0,  0,0, 0,1,0 },
142
  { ARM::t2STRBi12,ARM::tSTRBi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
143
  { ARM::t2STRBs, ARM::tSTRBr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
144
  { ARM::t2STRHi12,ARM::tSTRHi, 0,             5,   0,   1,   0,  0,0, 0,1,0 },
145
  { ARM::t2STRHs, ARM::tSTRHr,  0,             0,   0,   1,   0,  0,0, 0,1,0 },
146
  { ARM::t2STR_POST,ARM::tSTMIA_UPD,0,         0,   0,   1,   0,  0,0, 0,1,0 },
147
148
  { ARM::t2LDMIA, ARM::tLDMIA,  0,             0,   0,   1,   1,  1,1, 0,1,0 },
149
  { ARM::t2LDMIA_RET,0,         ARM::tPOP_RET, 0,   0,   1,   1,  1,1, 0,1,0 },
150
  { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0,   0,   1,   1,  1,1, 0,1,0 },
151
  // ARM::t2STMIA (with no basereg writeback) has no Thumb1 equivalent.
152
  // tSTMIA_UPD is a change in semantics which can only be used if the base
153
  // register is killed. This difference is correctly handled elsewhere.
154
  { ARM::t2STMIA, ARM::tSTMIA_UPD, 0,          0,   0,   1,   1,  1,1, 0,1,0 },
155
  { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0,       0,   0,   1,   1,  1,1, 0,1,0 },
156
  { ARM::t2STMDB_UPD, 0,        ARM::tPUSH,    0,   0,   1,   1,  1,1, 0,1,0 }
157
  };
158
159
  class Thumb2SizeReduce : public MachineFunctionPass {
160
  public:
161
    static char ID;
162
163
    const Thumb2InstrInfo *TII;
164
    const ARMSubtarget *STI;
165
166
    Thumb2SizeReduce(std::function<bool(const Function &)> Ftor = nullptr);
167
168
    bool runOnMachineFunction(MachineFunction &MF) override;
169
170
10.0k
    MachineFunctionProperties getRequiredProperties() const override {
171
10.0k
      return MachineFunctionProperties().set(
172
10.0k
          MachineFunctionProperties::Property::NoVRegs);
173
10.0k
    }
174
175
61.8k
    StringRef getPassName() const override {
176
61.8k
      return THUMB2_SIZE_REDUCE_NAME;
177
61.8k
    }
178
179
  private:
180
    /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
181
    DenseMap<unsigned, unsigned> ReduceOpcodeMap;
182
183
    bool canAddPseudoFlagDep(MachineInstr *Use, bool IsSelfLoop);
184
185
    bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
186
                         bool is2Addr, ARMCC::CondCodes Pred,
187
                         bool LiveCPSR, bool &HasCC, bool &CCDead);
188
189
    bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
190
                         const ReduceEntry &Entry);
191
192
    bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
193
                       const ReduceEntry &Entry, bool LiveCPSR, bool IsSelfLoop);
194
195
    /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
196
    /// instruction.
197
    bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
198
                       const ReduceEntry &Entry, bool LiveCPSR,
199
                       bool IsSelfLoop);
200
201
    /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
202
    /// non-two-address instruction.
203
    bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
204
                        const ReduceEntry &Entry, bool LiveCPSR,
205
                        bool IsSelfLoop);
206
207
    /// ReduceMI - Attempt to reduce MI, return true on success.
208
    bool ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
209
                  bool LiveCPSR, bool IsSelfLoop);
210
211
    /// ReduceMBB - Reduce width of instructions in the specified basic block.
212
    bool ReduceMBB(MachineBasicBlock &MBB);
213
214
    bool OptimizeSize;
215
    bool MinimizeSize;
216
217
    // Last instruction to define CPSR in the current block.
218
    MachineInstr *CPSRDef;
219
    // Was CPSR last defined by a high latency instruction?
220
    // When CPSRDef is null, this refers to CPSR defs in predecessors.
221
    bool HighLatencyCPSR;
222
223
    struct MBBInfo {
224
      // The flags leaving this block have high latency.
225
      bool HighLatencyCPSR = false;
226
      // Has this block been visited yet?
227
      bool Visited = false;
228
229
102k
      MBBInfo() = default;
230
    };
231
232
    SmallVector<MBBInfo, 8> BlockInfo;
233
234
    std::function<bool(const Function &)> PredicateFtor;
235
  };
236
237
  char Thumb2SizeReduce::ID = 0;
238
239
} // end anonymous namespace
240
241
INITIALIZE_PASS(Thumb2SizeReduce, DEBUG_TYPE, THUMB2_SIZE_REDUCE_NAME, false,
242
                false)
243
244
Thumb2SizeReduce::Thumb2SizeReduce(std::function<bool(const Function &)> Ftor)
245
10.1k
    : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
246
10.1k
  OptimizeSize = MinimizeSize = false;
247
636k
  for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; 
++i626k
) {
248
626k
    unsigned FromOpc = ReduceTable[i].WideOpc;
249
626k
    if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
250
626k
      
llvm_unreachable0
("Duplicated entries?");
251
626k
  }
252
10.1k
}
253
254
42.8k
static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
255
42.8k
  for (const MCPhysReg *Regs = MCID.getImplicitDefs(); *Regs; 
++Regs0
)
256
42.8k
    if (*Regs == ARM::CPSR)
257
42.8k
      return true;
258
42.8k
  
return false0
;
259
42.8k
}
260
261
// Check for a likely high-latency flag def.
262
113k
static bool isHighLatencyCPSR(MachineInstr *Def) {
263
113k
  switch(Def->getOpcode()) {
264
113k
  case ARM::FMSTAT:
265
1.83k
  case ARM::tMUL:
266
1.83k
    return true;
267
111k
  }
268
111k
  return false;
269
111k
}
270
271
/// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
272
/// the 's' 16-bit instruction partially update CPSR. Abort the
273
/// transformation to avoid adding false dependency on last CPSR setting
274
/// instruction which hurts the ability for out-of-order execution engine
275
/// to do register renaming magic.
276
/// This function checks if there is a read-of-write dependency between the
277
/// last instruction that defines the CPSR and the current instruction. If there
278
/// is, then there is no harm done since the instruction cannot be retired
279
/// before the CPSR setting instruction anyway.
280
/// Note, we are not doing full dependency analysis here for the sake of compile
281
/// time. We're not looking for cases like:
282
/// r0 = muls ...
283
/// r1 = add.w r0, ...
284
/// ...
285
///    = mul.w r1
286
/// In this case it would have been ok to narrow the mul.w to muls since there
287
/// are indirect RAW dependency between the muls and the mul.w
288
bool
289
42.2k
Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Use, bool FirstInSelfLoop) {
290
42.2k
  // Disable the check for -Oz (aka OptimizeForSizeHarder).
291
42.2k
  if (MinimizeSize || 
!STI->avoidCPSRPartialUpdate()38.6k
)
292
30.8k
    return false;
293
11.3k
294
11.3k
  if (!CPSRDef)
295
7.82k
    // If this BB loops back to itself, conservatively avoid narrowing the
296
7.82k
    // first instruction that does partial flag update.
297
7.82k
    return HighLatencyCPSR || 
FirstInSelfLoop7.79k
;
298
3.56k
299
3.56k
  SmallSet<unsigned, 2> Defs;
300
18.4k
  for (const MachineOperand &MO : CPSRDef->operands()) {
301
18.4k
    if (!MO.isReg() || 
MO.isUndef()11.6k
||
MO.isUse()11.6k
)
302
11.5k
      continue;
303
6.90k
    unsigned Reg = MO.getReg();
304
6.90k
    if (Reg == 0 || Reg == ARM::CPSR)
305
3.56k
      continue;
306
3.33k
    Defs.insert(Reg);
307
3.33k
  }
308
3.56k
309
17.7k
  for (const MachineOperand &MO : Use->operands()) {
310
17.7k
    if (!MO.isReg() || 
MO.isUndef()10.8k
||
MO.isDef()10.8k
)
311
10.4k
      continue;
312
7.24k
    unsigned Reg = MO.getReg();
313
7.24k
    if (Defs.count(Reg))
314
78
      return false;
315
7.24k
  }
316
3.56k
317
3.56k
  // If the current CPSR has high latency, try to avoid the false dependency.
318
3.56k
  
if (3.49k
HighLatencyCPSR3.49k
)
319
12
    return true;
320
3.47k
321
3.47k
  // tMOVi8 usually doesn't start long dependency chains, and there are a lot
322
3.47k
  // of them, so always shrink them when CPSR doesn't have high latency.
323
3.47k
  if (Use->getOpcode() == ARM::t2MOVi ||
324
3.47k
      
Use->getOpcode() == ARM::t2MOVi1693
)
325
3.39k
    return false;
326
81
327
81
  // No read-after-write dependency. The narrowing will add false dependency.
328
81
  return true;
329
81
}
330
331
bool
332
Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
333
                                  bool is2Addr, ARMCC::CondCodes Pred,
334
113k
                                  bool LiveCPSR, bool &HasCC, bool &CCDead) {
335
113k
  if ((is2Addr  && 
Entry.PredCC2 == 013.9k
) ||
336
113k
      
(102k
!is2Addr102k
&&
Entry.PredCC1 == 099.5k
)) {
337
63.9k
    if (Pred == ARMCC::AL) {
338
60.0k
      // Not predicated, must set CPSR.
339
60.0k
      if (!HasCC) {
340
56.0k
        // Original instruction was not setting CPSR, but CPSR is not
341
56.0k
        // currently live anyway. It's ok to set it. The CPSR def is
342
56.0k
        // dead though.
343
56.0k
        if (!LiveCPSR) {
344
54.1k
          HasCC = true;
345
54.1k
          CCDead = true;
346
54.1k
          return true;
347
54.1k
        }
348
1.85k
        return false;
349
1.85k
      }
350
3.87k
    } else {
351
3.87k
      // Predicated, must not set CPSR.
352
3.87k
      if (HasCC)
353
54
        return false;
354
49.5k
    }
355
49.5k
  } else if ((is2Addr  && 
Entry.PredCC2 == 23.23k
) ||
356
49.5k
             (!is2Addr && 
Entry.PredCC1 == 246.3k
)) {
357
42.8k
    /// Old opcode has an optional def of CPSR.
358
42.8k
    if (HasCC)
359
0
      return true;
360
42.8k
    // If old opcode does not implicitly define CPSR, then it's not ok since
361
42.8k
    // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
362
42.8k
    if (!HasImplicitCPSRDef(MI->getDesc()))
363
0
      return false;
364
42.8k
    HasCC = true;
365
42.8k
  } else {
366
6.65k
    // 16-bit instruction does not set CPSR.
367
6.65k
    if (HasCC)
368
292
      return false;
369
57.1k
  }
370
57.1k
371
57.1k
  return true;
372
57.1k
}
373
374
117k
static bool VerifyLowRegs(MachineInstr *MI) {
375
117k
  unsigned Opc = MI->getOpcode();
376
117k
  bool isPCOk = (Opc == ARM::t2LDMIA_RET || 
Opc == ARM::t2LDMIA_UPD106k
);
377
117k
  bool isLROk = (Opc == ARM::t2STMDB_UPD);
378
117k
  bool isSPOk = isPCOk || 
isLROk101k
;
379
699k
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; 
++i582k
) {
380
605k
    const MachineOperand &MO = MI->getOperand(i);
381
605k
    if (!MO.isReg() || 
MO.isImplicit()426k
)
382
189k
      continue;
383
415k
    unsigned Reg = MO.getReg();
384
415k
    if (Reg == 0 || 
Reg == ARM::CPSR314k
)
385
104k
      continue;
386
311k
    if (isPCOk && 
Reg == ARM::PC81.2k
)
387
9.75k
      continue;
388
301k
    if (isLROk && 
Reg == ARM::LR54.1k
)
389
7.95k
      continue;
390
293k
    if (Reg == ARM::SP) {
391
79.4k
      if (isSPOk)
392
50.5k
        continue;
393
28.8k
      if (i == 1 && 
(28.4k
Opc == ARM::t2LDRi1228.4k
||
Opc == ARM::t2STRi1219.2k
))
394
28.0k
        // Special case for these ldr / str with sp as base register.
395
28.0k
        continue;
396
215k
    }
397
215k
    if (!isARMLowRegister(Reg))
398
22.3k
      return false;
399
215k
  }
400
117k
  
return true94.6k
;
401
117k
}
402
403
bool
404
Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
405
86.8k
                                  const ReduceEntry &Entry) {
406
86.8k
  if (ReduceLimitLdSt != -1 && 
((int)NumLdSts >= ReduceLimitLdSt)0
)
407
0
    return false;
408
86.8k
409
86.8k
  unsigned Scale = 1;
410
86.8k
  bool HasImmOffset = false;
411
86.8k
  bool HasShift = false;
412
86.8k
  bool HasOffReg = true;
413
86.8k
  bool isLdStMul = false;
414
86.8k
  unsigned Opc = Entry.NarrowOpc1;
415
86.8k
  unsigned OpNum = 3; // First 'rest' of operands.
416
86.8k
  uint8_t  ImmLimit = Entry.Imm1Limit;
417
86.8k
418
86.8k
  switch (Entry.WideOpc) {
419
86.8k
  default:
420
0
    llvm_unreachable("Unexpected Thumb2 load / store opcode!");
421
86.8k
  case ARM::t2LDRi12:
422
56.8k
  case ARM::t2STRi12:
423
56.8k
    if (MI->getOperand(1).getReg() == ARM::SP) {
424
28.0k
      Opc = Entry.NarrowOpc2;
425
28.0k
      ImmLimit = Entry.Imm2Limit;
426
28.0k
    }
427
56.8k
428
56.8k
    Scale = 4;
429
56.8k
    HasImmOffset = true;
430
56.8k
    HasOffReg = false;
431
56.8k
    break;
432
56.8k
  case ARM::t2LDRBi12:
433
7.24k
  case ARM::t2STRBi12:
434
7.24k
    HasImmOffset = true;
435
7.24k
    HasOffReg = false;
436
7.24k
    break;
437
7.24k
  case ARM::t2LDRHi12:
438
680
  case ARM::t2STRHi12:
439
680
    Scale = 2;
440
680
    HasImmOffset = true;
441
680
    HasOffReg = false;
442
680
    break;
443
3.82k
  case ARM::t2LDRs:
444
3.82k
  case ARM::t2LDRBs:
445
3.82k
  case ARM::t2LDRHs:
446
3.82k
  case ARM::t2LDRSBs:
447
3.82k
  case ARM::t2LDRSHs:
448
3.82k
  case ARM::t2STRs:
449
3.82k
  case ARM::t2STRBs:
450
3.82k
  case ARM::t2STRHs:
451
3.82k
    HasShift = true;
452
3.82k
    OpNum = 4;
453
3.82k
    break;
454
3.82k
  case ARM::t2LDR_POST:
455
301
  case ARM::t2STR_POST: {
456
301
    if (!MinimizeSize)
457
293
      return false;
458
8
459
8
    if (!MI->hasOneMemOperand() ||
460
8
        (*MI->memoperands_begin())->getAlignment() < 4)
461
2
      return false;
462
6
463
6
    // We're creating a completely different type of load/store - LDM from LDR.
464
6
    // For this reason we can't reuse the logic at the end of this function; we
465
6
    // have to implement the MI building here.
466
6
    bool IsStore = Entry.WideOpc == ARM::t2STR_POST;
467
6
    unsigned Rt = MI->getOperand(IsStore ? 
13
:
03
).getReg();
468
6
    unsigned Rn = MI->getOperand(IsStore ? 
03
:
13
).getReg();
469
6
    unsigned Offset = MI->getOperand(3).getImm();
470
6
    unsigned PredImm = MI->getOperand(4).getImm();
471
6
    unsigned PredReg = MI->getOperand(5).getReg();
472
6
    assert(isARMLowRegister(Rt));
473
6
    assert(isARMLowRegister(Rn));
474
6
475
6
    if (Offset != 4)
476
2
      return false;
477
4
478
4
    // Add the 16-bit load / store instruction.
479
4
    DebugLoc dl = MI->getDebugLoc();
480
4
    auto MIB = BuildMI(MBB, MI, dl, TII->get(Entry.NarrowOpc1))
481
4
                   .addReg(Rn, RegState::Define)
482
4
                   .addReg(Rn)
483
4
                   .addImm(PredImm)
484
4
                   .addReg(PredReg)
485
4
                   .addReg(Rt, IsStore ? 
01
:
RegState::Define3
);
486
4
487
4
    // Transfer memoperands.
488
4
    MIB.setMemRefs(MI->memoperands());
489
4
490
4
    // Transfer MI flags.
491
4
    MIB.setMIFlags(MI->getFlags());
492
4
493
4
    // Kill the old instruction.
494
4
    MI->eraseFromBundle();
495
4
    ++NumLdSts;
496
4
    return true;
497
4
  }
498
145
  case ARM::t2LDMIA: {
499
145
    unsigned BaseReg = MI->getOperand(0).getReg();
500
145
    assert(isARMLowRegister(BaseReg));
501
145
502
145
    // For the non-writeback version (this one), the base register must be
503
145
    // one of the registers being loaded.
504
145
    bool isOK = false;
505
505
    for (unsigned i = 3; i < MI->getNumOperands(); 
++i360
) {
506
492
      if (MI->getOperand(i).getReg() == BaseReg) {
507
132
        isOK = true;
508
132
        break;
509
132
      }
510
492
    }
511
145
512
145
    if (!isOK)
513
13
      return false;
514
132
515
132
    OpNum = 0;
516
132
    isLdStMul = true;
517
132
    break;
518
132
  }
519
132
  case ARM::t2STMIA:
520
94
    // If the base register is killed, we don't care what its value is after the
521
94
    // instruction, so we can use an updating STMIA.
522
94
    if (!MI->getOperand(0).isKill())
523
34
      return false;
524
60
525
60
    break;
526
9.75k
  case ARM::t2LDMIA_RET: {
527
9.75k
    unsigned BaseReg = MI->getOperand(1).getReg();
528
9.75k
    if (BaseReg != ARM::SP)
529
0
      return false;
530
9.75k
    Opc = Entry.NarrowOpc2; // tPOP_RET
531
9.75k
    OpNum = 2;
532
9.75k
    isLdStMul = true;
533
9.75k
    break;
534
9.75k
  }
535
9.75k
  case ARM::t2LDMIA_UPD:
536
7.96k
  case ARM::t2STMIA_UPD:
537
7.96k
  case ARM::t2STMDB_UPD: {
538
7.96k
    OpNum = 0;
539
7.96k
540
7.96k
    unsigned BaseReg = MI->getOperand(1).getReg();
541
7.96k
    if (BaseReg == ARM::SP &&
542
7.96k
        
(7.96k
Entry.WideOpc == ARM::t2LDMIA_UPD7.96k
||
543
7.96k
         
Entry.WideOpc == ARM::t2STMDB_UPD7.95k
)) {
544
7.96k
      Opc = Entry.NarrowOpc2; // tPOP or tPUSH
545
7.96k
      OpNum = 2;
546
7.96k
    } else 
if (6
!isARMLowRegister(BaseReg)6
||
547
6
               (Entry.WideOpc != ARM::t2LDMIA_UPD &&
548
6
                
Entry.WideOpc != ARM::t2STMIA_UPD3
)) {
549
0
      return false;
550
0
    }
551
7.96k
552
7.96k
    isLdStMul = true;
553
7.96k
    break;
554
7.96k
  }
555
86.5k
  }
556
86.5k
557
86.5k
  unsigned OffsetReg = 0;
558
86.5k
  bool OffsetKill = false;
559
86.5k
  bool OffsetInternal = false;
560
86.5k
  if (HasShift) {
561
3.82k
    OffsetReg  = MI->getOperand(2).getReg();
562
3.82k
    OffsetKill = MI->getOperand(2).isKill();
563
3.82k
    OffsetInternal = MI->getOperand(2).isInternalRead();
564
3.82k
565
3.82k
    if (MI->getOperand(3).getImm())
566
1.02k
      // Thumb1 addressing mode doesn't support shift.
567
1.02k
      return false;
568
85.4k
  }
569
85.4k
570
85.4k
  unsigned OffsetImm = 0;
571
85.4k
  if (HasImmOffset) {
572
64.7k
    OffsetImm = MI->getOperand(2).getImm();
573
64.7k
    unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
574
64.7k
575
64.7k
    if ((OffsetImm & (Scale - 1)) || 
OffsetImm > MaxOffset64.7k
)
576
8.25k
      // Make sure the immediate field fits.
577
8.25k
      return false;
578
77.2k
  }
579
77.2k
580
77.2k
  // Add the 16-bit load / store instruction.
581
77.2k
  DebugLoc dl = MI->getDebugLoc();
582
77.2k
  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, TII->get(Opc));
583
77.2k
584
77.2k
  // tSTMIA_UPD takes a defining register operand. We've already checked that
585
77.2k
  // the register is killed, so mark it as dead here.
586
77.2k
  if (Entry.WideOpc == ARM::t2STMIA)
587
60
    MIB.addReg(MI->getOperand(0).getReg(), RegState::Define | RegState::Dead);
588
77.2k
589
77.2k
  if (!isLdStMul) {
590
59.3k
    MIB.add(MI->getOperand(0));
591
59.3k
    MIB.add(MI->getOperand(1));
592
59.3k
593
59.3k
    if (HasImmOffset)
594
56.5k
      MIB.addImm(OffsetImm / Scale);
595
59.3k
596
59.3k
    assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
597
59.3k
598
59.3k
    if (HasOffReg)
599
2.85k
      MIB.addReg(OffsetReg, getKillRegState(OffsetKill) |
600
2.85k
                            getInternalReadRegState(OffsetInternal));
601
59.3k
  }
602
77.2k
603
77.2k
  // Transfer the rest of operands.
604
311k
  for (unsigned e = MI->getNumOperands(); OpNum != e; 
++OpNum234k
)
605
234k
    MIB.add(MI->getOperand(OpNum));
606
77.2k
607
77.2k
  // Transfer memoperands.
608
77.2k
  MIB.setMemRefs(MI->memoperands());
609
77.2k
610
77.2k
  // Transfer MI flags.
611
77.2k
  MIB.setMIFlags(MI->getFlags());
612
77.2k
613
77.2k
  LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
614
77.2k
                    << "       to 16-bit: " << *MIB);
615
77.2k
616
77.2k
  MBB.erase_instr(MI);
617
77.2k
  ++NumLdSts;
618
77.2k
  return true;
619
77.2k
}
620
621
bool
622
Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
623
                                const ReduceEntry &Entry,
624
160k
                                bool LiveCPSR, bool IsSelfLoop) {
625
160k
  unsigned Opc = MI->getOpcode();
626
160k
  if (Opc == ARM::t2ADDri) {
627
32.8k
    // If the source register is SP, try to reduce to tADDrSPi, otherwise
628
32.8k
    // it's a normal reduce.
629
32.8k
    if (MI->getOperand(1).getReg() != ARM::SP) {
630
16.2k
      if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
631
4.67k
        return true;
632
11.6k
      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
633
11.6k
    }
634
16.5k
    // Try to reduce to tADDrSPi.
635
16.5k
    unsigned Imm = MI->getOperand(2).getImm();
636
16.5k
    // The immediate must be in range, the destination register must be a low
637
16.5k
    // reg, the predicate must be "always" and the condition flags must not
638
16.5k
    // be being set.
639
16.5k
    if (Imm & 3 || 
Imm > 102016.5k
)
640
2.97k
      return false;
641
13.5k
    if (!isARMLowRegister(MI->getOperand(0).getReg()))
642
1.56k
      return false;
643
11.9k
    if (MI->getOperand(3).getImm() != ARMCC::AL)
644
32
      return false;
645
11.9k
    const MCInstrDesc &MCID = MI->getDesc();
646
11.9k
    if (MCID.hasOptionalDef() &&
647
11.9k
        MI->getOperand(MCID.getNumOperands()-1).getReg() == ARM::CPSR)
648
1
      return false;
649
11.9k
650
11.9k
    MachineInstrBuilder MIB =
651
11.9k
        BuildMI(MBB, MI, MI->getDebugLoc(),
652
11.9k
                TII->get(ARM::tADDrSPi))
653
11.9k
            .add(MI->getOperand(0))
654
11.9k
            .add(MI->getOperand(1))
655
11.9k
            .addImm(Imm / 4) // The tADDrSPi has an implied scale by four.
656
11.9k
            .add(predOps(ARMCC::AL));
657
11.9k
658
11.9k
    // Transfer MI flags.
659
11.9k
    MIB.setMIFlags(MI->getFlags());
660
11.9k
661
11.9k
    LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
662
11.9k
                      << "       to 16-bit: " << *MIB);
663
11.9k
664
11.9k
    MBB.erase_instr(MI);
665
11.9k
    ++NumNarrows;
666
11.9k
    return true;
667
11.9k
  }
668
127k
669
127k
  if (Entry.LowRegs1 && 
!VerifyLowRegs(MI)117k
)
670
22.3k
    return false;
671
105k
672
105k
  if (MI->mayLoadOrStore())
673
86.8k
    return ReduceLoadStore(MBB, MI, Entry);
674
18.4k
675
18.4k
  switch (Opc) {
676
18.4k
  
default: break0
;
677
18.4k
  case ARM::t2ADDSri:
678
0
  case ARM::t2ADDSrr: {
679
0
    unsigned PredReg = 0;
680
0
    if (getInstrPredicate(*MI, PredReg) == ARMCC::AL) {
681
0
      switch (Opc) {
682
0
      default: break;
683
0
      case ARM::t2ADDSri:
684
0
        if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
685
0
          return true;
686
0
        LLVM_FALLTHROUGH;
687
0
      case ARM::t2ADDSrr:
688
0
        return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
689
0
      }
690
0
    }
691
0
    break;
692
0
  }
693
3.33k
  case ARM::t2RSBri:
694
3.33k
  case ARM::t2RSBSri:
695
3.33k
  case ARM::t2SXTB:
696
3.33k
  case ARM::t2SXTH:
697
3.33k
  case ARM::t2UXTB:
698
3.33k
  case ARM::t2UXTH:
699
3.33k
    if (MI->getOperand(2).getImm() == 0)
700
2.43k
      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
701
901
    break;
702
4.48k
  case ARM::t2MOVi16:
703
4.48k
    // Can convert only 'pure' immediate operands, not immediates obtained as
704
4.48k
    // globals' addresses.
705
4.48k
    if (MI->getOperand(1).isImm())
706
4.06k
      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
707
413
    break;
708
10.6k
  case ARM::t2CMPrr: {
709
10.6k
    // Try to reduce to the lo-reg only version first. Why there are two
710
10.6k
    // versions of the instruction is a mystery.
711
10.6k
    // It would be nice to just have two entries in the master table that
712
10.6k
    // are prioritized, but the table assumes a unique entry for each
713
10.6k
    // source insn opcode. So for now, we hack a local entry record to use.
714
10.6k
    static const ReduceEntry NarrowEntry =
715
10.6k
      { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1,0 };
716
10.6k
    if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, IsSelfLoop))
717
7.96k
      return true;
718
2.68k
    return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
719
2.68k
  }
720
2.68k
  case ARM::t2TEQrr: {
721
8
    unsigned PredReg = 0;
722
8
    // Can only convert to eors if we're not in an IT block.
723
8
    if (getInstrPredicate(*MI, PredReg) != ARMCC::AL)
724
1
      break;
725
7
    // TODO if Operand 0 is not killed but Operand 1 is, then we could write
726
7
    // to Op1 instead.
727
7
    if (MI->getOperand(0).isKill())
728
5
      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
729
1.31k
  }
730
1.31k
  }
731
1.31k
  return false;
732
1.31k
}
733
734
bool
735
Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
736
                                const ReduceEntry &Entry,
737
38.7k
                                bool LiveCPSR, bool IsSelfLoop) {
738
38.7k
  if (ReduceLimit2Addr != -1 && 
((int)Num2Addrs >= ReduceLimit2Addr)6
)
739
6
    return false;
740
38.7k
741
38.7k
  if (!OptimizeSize && 
Entry.AvoidMovs34.3k
&&
STI->avoidMOVsShifterOperand()2.34k
)
742
674
    // Don't issue movs with shifter operand for some CPUs unless we
743
674
    // are optimizing for size.
744
674
    return false;
745
38.0k
746
38.0k
  unsigned Reg0 = MI->getOperand(0).getReg();
747
38.0k
  unsigned Reg1 = MI->getOperand(1).getReg();
748
38.0k
  // t2MUL is "special". The tied source operand is second, not first.
749
38.0k
  if (MI->getOpcode() == ARM::t2MUL) {
750
613
    unsigned Reg2 = MI->getOperand(2).getReg();
751
613
    // Early exit if the regs aren't all low regs.
752
613
    if (!isARMLowRegister(Reg0) || 
!isARMLowRegister(Reg1)570
753
613
        || 
!isARMLowRegister(Reg2)553
)
754
134
      return false;
755
479
    if (Reg0 != Reg2) {
756
219
      // If the other operand also isn't the same as the destination, we
757
219
      // can't reduce.
758
219
      if (Reg1 != Reg0)
759
83
        return false;
760
136
      // Try to commute the operands to make it a 2-address instruction.
761
136
      MachineInstr *CommutedMI = TII->commuteInstruction(*MI);
762
136
      if (!CommutedMI)
763
0
        return false;
764
37.4k
    }
765
37.4k
  } else if (Reg0 != Reg1) {
766
24.0k
    // Try to commute the operands to make it a 2-address instruction.
767
24.0k
    unsigned CommOpIdx1 = 1;
768
24.0k
    unsigned CommOpIdx2 = TargetInstrInfo::CommuteAnyOperandIndex;
769
24.0k
    if (!TII->findCommutedOpIndices(*MI, CommOpIdx1, CommOpIdx2) ||
770
24.0k
        
MI->getOperand(CommOpIdx2).getReg() != Reg07.03k
)
771
21.3k
      return false;
772
2.70k
    MachineInstr *CommutedMI =
773
2.70k
        TII->commuteInstruction(*MI, false, CommOpIdx1, CommOpIdx2);
774
2.70k
    if (!CommutedMI)
775
0
      return false;
776
16.5k
  }
777
16.5k
  if (Entry.LowRegs2 && 
!isARMLowRegister(Reg0)13.2k
)
778
1.72k
    return false;
779
14.7k
  if (Entry.Imm2Limit) {
780
7.69k
    unsigned Imm = MI->getOperand(2).getImm();
781
7.69k
    unsigned Limit = (1 << Entry.Imm2Limit) - 1;
782
7.69k
    if (Imm > Limit)
783
480
      return false;
784
7.09k
  } else {
785
7.09k
    unsigned Reg2 = MI->getOperand(2).getReg();
786
7.09k
    if (Entry.LowRegs2 && 
!isARMLowRegister(Reg2)3.85k
)
787
373
      return false;
788
13.9k
  }
789
13.9k
790
13.9k
  // Check if it's possible / necessary to transfer the predicate.
791
13.9k
  const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
792
13.9k
  unsigned PredReg = 0;
793
13.9k
  ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
794
13.9k
  bool SkipPred = false;
795
13.9k
  if (Pred != ARMCC::AL) {
796
665
    if (!NewMCID.isPredicable())
797
0
      // Can't transfer predicate, fail.
798
0
      return false;
799
13.2k
  } else {
800
13.2k
    SkipPred = !NewMCID.isPredicable();
801
13.2k
  }
802
13.9k
803
13.9k
  bool HasCC = false;
804
13.9k
  bool CCDead = false;
805
13.9k
  const MCInstrDesc &MCID = MI->getDesc();
806
13.9k
  if (MCID.hasOptionalDef()) {
807
13.5k
    unsigned NumOps = MCID.getNumOperands();
808
13.5k
    HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
809
13.5k
    if (HasCC && 
MI->getOperand(NumOps-1).isDead()2.04k
)
810
0
      CCDead = true;
811
13.5k
  }
812
13.9k
  if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
813
933
    return false;
814
13.0k
815
13.0k
  // Avoid adding a false dependency on partial flag update by some 16-bit
816
13.0k
  // instructions which has the 's' bit set.
817
13.0k
  if (Entry.PartFlag && 
NewMCID.hasOptionalDef()2.96k
&&
HasCC2.96k
&&
818
13.0k
      
canAddPseudoFlagDep(MI, IsSelfLoop)2.84k
)
819
106
    return false;
820
12.8k
821
12.8k
  // Add the 16-bit instruction.
822
12.8k
  DebugLoc dl = MI->getDebugLoc();
823
12.8k
  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
824
12.8k
  MIB.add(MI->getOperand(0));
825
12.8k
  if (NewMCID.hasOptionalDef())
826
9.95k
    MIB.add(HasCC ? 
t1CondCodeOp(CCDead)9.43k
:
condCodeOp()527
);
827
12.8k
828
12.8k
  // Transfer the rest of operands.
829
12.8k
  unsigned NumOps = MCID.getNumOperands();
830
78.5k
  for (unsigned i = 1, e = MI->getNumOperands(); i != e; 
++i65.6k
) {
831
65.6k
    if (i < NumOps && 
MCID.OpInfo[i].isOptionalDef()64.1k
)
832
12.5k
      continue;
833
53.0k
    if (SkipPred && 
MCID.OpInfo[i].isPredicate()0
)
834
0
      continue;
835
53.0k
    MIB.add(MI->getOperand(i));
836
53.0k
  }
837
12.8k
838
12.8k
  // Transfer MI flags.
839
12.8k
  MIB.setMIFlags(MI->getFlags());
840
12.8k
841
12.8k
  LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
842
12.8k
                    << "       to 16-bit: " << *MIB);
843
12.8k
844
12.8k
  MBB.erase_instr(MI);
845
12.8k
  ++Num2Addrs;
846
12.8k
  return true;
847
12.8k
}
848
849
bool
850
Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
851
                                 const ReduceEntry &Entry,
852
135k
                                 bool LiveCPSR, bool IsSelfLoop) {
853
135k
  if (ReduceLimit != -1 && 
((int)NumNarrows >= ReduceLimit)5
)
854
5
    return false;
855
135k
856
135k
  if (!OptimizeSize && 
Entry.AvoidMovs126k
&&
STI->avoidMOVsShifterOperand()5.19k
)
857
1.56k
    // Don't issue movs with shifter operand for some CPUs unless we
858
1.56k
    // are optimizing for size.
859
1.56k
    return false;
860
133k
861
133k
  unsigned Limit = ~0U;
862
133k
  if (Entry.Imm1Limit)
863
108k
    Limit = (1 << Entry.Imm1Limit) - 1;
864
133k
865
133k
  const MCInstrDesc &MCID = MI->getDesc();
866
632k
  for (unsigned i = 0, e = MCID.getNumOperands(); i != e; 
++i498k
) {
867
533k
    if (MCID.OpInfo[i].isPredicate())
868
199k
      continue;
869
334k
    const MachineOperand &MO = MI->getOperand(i);
870
334k
    if (MO.isReg()) {
871
234k
      unsigned Reg = MO.getReg();
872
234k
      if (!Reg || 
Reg == ARM::CPSR182k
)
873
54.9k
        continue;
874
179k
      if (Entry.LowRegs1 && 
!isARMLowRegister(Reg)170k
)
875
16.7k
        return false;
876
99.4k
    } else if (MO.isImm() &&
877
99.4k
               !MCID.OpInfo[i].isPredicate()) {
878
99.4k
      if (((unsigned)MO.getImm()) > Limit)
879
17.6k
        return false;
880
99.4k
    }
881
334k
  }
882
133k
883
133k
  // Check if it's possible / necessary to transfer the predicate.
884
133k
  const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
885
99.5k
  unsigned PredReg = 0;
886
99.5k
  ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
887
99.5k
  bool SkipPred = false;
888
99.5k
  if (Pred != ARMCC::AL) {
889
6.48k
    if (!NewMCID.isPredicable())
890
0
      // Can't transfer predicate, fail.
891
0
      return false;
892
93.0k
  } else {
893
93.0k
    SkipPred = !NewMCID.isPredicable();
894
93.0k
  }
895
99.5k
896
99.5k
  bool HasCC = false;
897
99.5k
  bool CCDead = false;
898
99.5k
  if (MCID.hasOptionalDef()) {
899
54.9k
    unsigned NumOps = MCID.getNumOperands();
900
54.9k
    HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
901
54.9k
    if (HasCC && 
MI->getOperand(NumOps-1).isDead()2.37k
)
902
0
      CCDead = true;
903
54.9k
  }
904
99.5k
  if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
905
1.26k
    return false;
906
98.2k
907
98.2k
  // Avoid adding a false dependency on partial flag update by some 16-bit
908
98.2k
  // instructions which has the 's' bit set.
909
98.2k
  if (Entry.PartFlag && 
NewMCID.hasOptionalDef()42.3k
&&
HasCC42.3k
&&
910
98.2k
      
canAddPseudoFlagDep(MI, IsSelfLoop)39.4k
)
911
36
    return false;
912
98.2k
913
98.2k
  // Add the 16-bit instruction.
914
98.2k
  DebugLoc dl = MI->getDebugLoc();
915
98.2k
  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
916
98.2k
917
98.2k
  // TEQ is special in that it doesn't define a register but we're converting
918
98.2k
  // it into an EOR which does. So add the first operand as a def and then
919
98.2k
  // again as a use.
920
98.2k
  if (MCID.getOpcode() == ARM::t2TEQrr) {
921
5
    MIB.add(MI->getOperand(0));
922
5
    MIB->getOperand(0).setIsKill(false);
923
5
    MIB->getOperand(0).setIsDef(true);
924
5
    MIB->getOperand(0).setIsDead(true);
925
5
926
5
    if (NewMCID.hasOptionalDef())
927
5
      MIB.add(HasCC ? t1CondCodeOp(CCDead) : 
condCodeOp()0
);
928
5
    MIB.add(MI->getOperand(0));
929
98.2k
  } else {
930
98.2k
    MIB.add(MI->getOperand(0));
931
98.2k
    if (NewMCID.hasOptionalDef())
932
51.9k
      MIB.add(HasCC ? 
t1CondCodeOp(CCDead)48.6k
:
condCodeOp()3.29k
);
933
98.2k
  }
934
98.2k
935
98.2k
  // Transfer the rest of operands.
936
98.2k
  unsigned NumOps = MCID.getNumOperands();
937
514k
  for (unsigned i = 1, e = MI->getNumOperands(); i != e; 
++i416k
) {
938
416k
    if (i < NumOps && 
MCID.OpInfo[i].isOptionalDef()362k
)
939
53.7k
      continue;
940
363k
    if ((MCID.getOpcode() == ARM::t2RSBSri ||
941
363k
         MCID.getOpcode() == ARM::t2RSBri ||
942
363k
         
MCID.getOpcode() == ARM::t2SXTB358k
||
943
363k
         
MCID.getOpcode() == ARM::t2SXTH357k
||
944
363k
         
MCID.getOpcode() == ARM::t2UXTB356k
||
945
363k
         
MCID.getOpcode() == ARM::t2UXTH354k
) &&
i == 29.83k
)
946
2.41k
      // Skip the zero immediate operand, it's now implicit.
947
2.41k
      continue;
948
360k
    bool isPred = (i < NumOps && 
MCID.OpInfo[i].isPredicate()306k
);
949
360k
    if (SkipPred && 
isPred0
)
950
0
        continue;
951
360k
    const MachineOperand &MO = MI->getOperand(i);
952
360k
    if (MO.isReg() && 
MO.isImplicit()184k
&&
MO.getReg() == ARM::CPSR53.9k
)
953
42.8k
      // Skip implicit def of CPSR. Either it's modeled as an optional
954
42.8k
      // def now or it's already an implicit def on the new instruction.
955
42.8k
      continue;
956
317k
    MIB.add(MO);
957
317k
  }
958
98.2k
  if (!MCID.isPredicable() && 
NewMCID.isPredicable()0
)
959
0
    MIB.add(predOps(ARMCC::AL));
960
98.2k
961
98.2k
  // Transfer MI flags.
962
98.2k
  MIB.setMIFlags(MI->getFlags());
963
98.2k
964
98.2k
  LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
965
98.2k
                    << "       to 16-bit: " << *MIB);
966
98.2k
967
98.2k
  MBB.erase_instr(MI);
968
98.2k
  ++NumNarrows;
969
98.2k
  return true;
970
98.2k
}
971
972
810k
static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
973
810k
  bool HasDef = false;
974
3.83M
  for (const MachineOperand &MO : MI.operands()) {
975
3.83M
    if (!MO.isReg() || 
MO.isUndef()2.46M
||
MO.isUse()2.46M
)
976
3.00M
      continue;
977
827k
    if (MO.getReg() != ARM::CPSR)
978
713k
      continue;
979
113k
980
113k
    DefCPSR = true;
981
113k
    if (!MO.isDead())
982
59.2k
      HasDef = true;
983
113k
  }
984
810k
985
810k
  return HasDef || 
LiveCPSR751k
;
986
810k
}
987
988
810k
static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
989
3.84M
  for (const MachineOperand &MO : MI.operands()) {
990
3.84M
    if (!MO.isReg() || 
MO.isUndef()2.46M
||
MO.isDef()2.46M
)
991
2.15M
      continue;
992
1.68M
    if (MO.getReg() != ARM::CPSR)
993
1.62M
      continue;
994
64.9k
    assert(LiveCPSR && "CPSR liveness tracking is wrong!");
995
64.9k
    if (MO.isKill()) {
996
54.7k
      LiveCPSR = false;
997
54.7k
      break;
998
54.7k
    }
999
64.9k
  }
1000
810k
1001
810k
  return LiveCPSR;
1002
810k
}
1003
1004
bool Thumb2SizeReduce::ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
1005
810k
                                bool LiveCPSR, bool IsSelfLoop) {
1006
810k
  unsigned Opcode = MI->getOpcode();
1007
810k
  DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
1008
810k
  if (OPI == ReduceOpcodeMap.end())
1009
531k
    return false;
1010
279k
  const ReduceEntry &Entry = ReduceTable[OPI->second];
1011
279k
1012
279k
  // Don't attempt normal reductions on "special" cases for now.
1013
279k
  if (Entry.Special)
1014
160k
    return ReduceSpecial(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
1015
118k
1016
118k
  // Try to transform to a 16-bit two-address instruction.
1017
118k
  if (Entry.NarrowOpc2 &&
1018
118k
      
ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop)22.4k
)
1019
8.22k
    return true;
1020
110k
1021
110k
  // Try to transform to a 16-bit non-two-address instruction.
1022
110k
  if (Entry.NarrowOpc1 &&
1023
110k
      
ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop)104k
)
1024
82.0k
    return true;
1025
28.3k
1026
28.3k
  return false;
1027
28.3k
}
1028
1029
100k
bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
1030
100k
  bool Modified = false;
1031
100k
1032
100k
  // Yes, CPSR could be livein.
1033
100k
  bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
1034
100k
  MachineInstr *BundleMI = nullptr;
1035
100k
1036
100k
  CPSRDef = nullptr;
1037
100k
  HighLatencyCPSR = false;
1038
100k
1039
100k
  // Check predecessors for the latest CPSRDef.
1040
111k
  for (auto *Pred : MBB.predecessors()) {
1041
111k
    const MBBInfo &PInfo = BlockInfo[Pred->getNumber()];
1042
111k
    if (!PInfo.Visited) {
1043
6.03k
      // Since blocks are visited in RPO, this must be a back-edge.
1044
6.03k
      continue;
1045
6.03k
    }
1046
105k
    if (PInfo.HighLatencyCPSR) {
1047
677
      HighLatencyCPSR = true;
1048
677
      break;
1049
677
    }
1050
105k
  }
1051
100k
1052
100k
  // If this BB loops back to itself, conservatively avoid narrowing the
1053
100k
  // first instruction that does partial flag update.
1054
100k
  bool IsSelfLoop = MBB.isSuccessor(&MBB);
1055
100k
  MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),E = MBB.instr_end();
1056
100k
  MachineBasicBlock::instr_iterator NextMII;
1057
922k
  for (; MII != E; 
MII = NextMII821k
) {
1058
821k
    NextMII = std::next(MII);
1059
821k
1060
821k
    MachineInstr *MI = &*MII;
1061
821k
    if (MI->isBundle()) {
1062
10.6k
      BundleMI = MI;
1063
10.6k
      continue;
1064
10.6k
    }
1065
810k
    if (MI->isDebugInstr())
1066
160
      continue;
1067
810k
1068
810k
    LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
1069
810k
1070
810k
    // Does NextMII belong to the same bundle as MI?
1071
810k
    bool NextInSameBundle = NextMII != E && 
NextMII->isBundledWithPred()709k
;
1072
810k
1073
810k
    if (ReduceMI(MBB, MI, LiveCPSR, IsSelfLoop)) {
1074
200k
      Modified = true;
1075
200k
      MachineBasicBlock::instr_iterator I = std::prev(NextMII);
1076
200k
      MI = &*I;
1077
200k
      // Removing and reinserting the first instruction in a bundle will break
1078
200k
      // up the bundle. Fix the bundling if it was broken.
1079
200k
      if (NextInSameBundle && 
!NextMII->isBundledWithPred()2.18k
)
1080
0
        NextMII->bundleWithPred();
1081
200k
    }
1082
810k
1083
810k
    if (BundleMI && 
!NextInSameBundle64.2k
&&
MI->isInsideBundle()49.0k
) {
1084
10.6k
      // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
1085
10.6k
      // marker is only on the BUNDLE instruction. Process the BUNDLE
1086
10.6k
      // instruction as we finish with the bundled instruction to work around
1087
10.6k
      // the inconsistency.
1088
10.6k
      if (BundleMI->killsRegister(ARM::CPSR))
1089
9.75k
        LiveCPSR = false;
1090
10.6k
      MachineOperand *MO = BundleMI->findRegisterDefOperand(ARM::CPSR);
1091
10.6k
      if (MO && 
!MO->isDead()1.29k
)
1092
1.25k
        LiveCPSR = true;
1093
10.6k
      MO = BundleMI->findRegisterUseOperand(ARM::CPSR);
1094
10.6k
      if (MO && 
!MO->isKill()10.5k
)
1095
806
        LiveCPSR = true;
1096
10.6k
    }
1097
810k
1098
810k
    bool DefCPSR = false;
1099
810k
    LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
1100
810k
    if (MI->isCall()) {
1101
55.9k
      // Calls don't really set CPSR.
1102
55.9k
      CPSRDef = nullptr;
1103
55.9k
      HighLatencyCPSR = false;
1104
55.9k
      IsSelfLoop = false;
1105
754k
    } else if (DefCPSR) {
1106
113k
      // This is the last CPSR defining instruction.
1107
113k
      CPSRDef = MI;
1108
113k
      HighLatencyCPSR = isHighLatencyCPSR(CPSRDef);
1109
113k
      IsSelfLoop = false;
1110
113k
    }
1111
810k
  }
1112
100k
1113
100k
  MBBInfo &Info = BlockInfo[MBB.getNumber()];
1114
100k
  Info.HighLatencyCPSR = HighLatencyCPSR;
1115
100k
  Info.Visited = true;
1116
100k
  return Modified;
1117
100k
}
1118
1119
51.8k
bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
1120
51.8k
  if (PredicateFtor && 
!PredicateFtor(MF.getFunction())25.2k
)
1121
23.7k
    return false;
1122
28.0k
1123
28.0k
  STI = &static_cast<const ARMSubtarget &>(MF.getSubtarget());
1124
28.0k
  if (STI->isThumb1Only() || 
STI->prefers32BitThumb()26.4k
)
1125
1.55k
    return false;
1126
26.4k
1127
26.4k
  TII = static_cast<const Thumb2InstrInfo *>(STI->getInstrInfo());
1128
26.4k
1129
26.4k
  // Optimizing / minimizing size? Minimizing size implies optimizing for size.
1130
26.4k
  OptimizeSize = MF.getFunction().hasOptSize();
1131
26.4k
  MinimizeSize = STI->hasMinSize();
1132
26.4k
1133
26.4k
  BlockInfo.clear();
1134
26.4k
  BlockInfo.resize(MF.getNumBlockIDs());
1135
26.4k
1136
26.4k
  // Visit blocks in reverse post-order so LastCPSRDef is known for all
1137
26.4k
  // predecessors.
1138
26.4k
  ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
1139
26.4k
  bool Modified = false;
1140
26.4k
  for (ReversePostOrderTraversal<MachineFunction*>::rpo_iterator
1141
127k
       I = RPOT.begin(), E = RPOT.end(); I != E; 
++I100k
)
1142
100k
    Modified |= ReduceMBB(**I);
1143
26.4k
  return Modified;
1144
26.4k
}
1145
1146
/// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
1147
/// reduction pass.
1148
FunctionPass *llvm::createThumb2SizeReductionPass(
1149
10.1k
    std::function<bool(const Function &)> Ftor) {
1150
10.1k
  return new Thumb2SizeReduce(std::move(Ftor));
1151
10.1k
}