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