1 //===-- Thumb2SizeReduction.cpp - Thumb2 code size reduction pass -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "ARMBaseInstrInfo.h"
12 #include "ARMSubtarget.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "Thumb2InstrInfo.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/TargetInstrInfo.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
47 #define DEBUG_TYPE "t2-reduce-size"
48 #define THUMB2_SIZE_REDUCE_NAME "Thumb2 instruction size reduce pass"
50 STATISTIC(NumNarrows, "Number of 32-bit instrs reduced to 16-bit ones");
51 STATISTIC(Num2Addrs, "Number of 32-bit instrs reduced to 2addr 16-bit ones");
52 STATISTIC(NumLdSts, "Number of 32-bit load / store reduced to 16-bit ones");
54 static cl::opt<int> ReduceLimit("t2-reduce-limit",
55 cl::init(-1), cl::Hidden);
56 static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
57 cl::init(-1), cl::Hidden);
58 static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
59 cl::init(-1), cl::Hidden);
63 /// ReduceTable - A static table with information on mapping from wide
66 uint16_t WideOpc; // Wide opcode
67 uint16_t NarrowOpc1; // Narrow opcode to transform to
68 uint16_t NarrowOpc2; // Narrow opcode when it's two-address
69 uint8_t Imm1Limit; // Limit of immediate field (bits)
70 uint8_t Imm2Limit; // Limit of immediate field when it's two-address
71 unsigned LowRegs1 : 1; // Only possible if low-registers are used
72 unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
73 unsigned PredCC1 : 2; // 0 - If predicated, cc is on and vice versa.
75 // 2 - Always set CPSR.
77 unsigned PartFlag : 1; // 16-bit instruction does partial flag update
78 unsigned Special : 1; // Needs to be dealt with specially
79 unsigned AvoidMovs: 1; // Avoid movs with shifter operand (for Swift)
82 static const ReduceEntry ReduceTable[] = {
83 // Wide, Narrow1, Narrow2, imm1,imm2, lo1, lo2, P/C,PF,S,AM
84 { ARM::t2ADCrr, 0, ARM::tADC, 0, 0, 0, 1, 0,0, 0,0,0 },
85 { ARM::t2ADDri, ARM::tADDi3, ARM::tADDi8, 3, 8, 1, 1, 0,0, 0,1,0 },
86 { ARM::t2ADDrr, ARM::tADDrr, ARM::tADDhirr, 0, 0, 1, 0, 0,1, 0,0,0 },
87 { ARM::t2ADDSri,ARM::tADDi3, ARM::tADDi8, 3, 8, 1, 1, 2,2, 0,1,0 },
88 { ARM::t2ADDSrr,ARM::tADDrr, 0, 0, 0, 1, 0, 2,0, 0,1,0 },
89 { ARM::t2ANDrr, 0, ARM::tAND, 0, 0, 0, 1, 0,0, 1,0,0 },
90 { ARM::t2ASRri, ARM::tASRri, 0, 5, 0, 1, 0, 0,0, 1,0,1 },
91 { ARM::t2ASRrr, 0, ARM::tASRrr, 0, 0, 0, 1, 0,0, 1,0,1 },
92 { ARM::t2BICrr, 0, ARM::tBIC, 0, 0, 0, 1, 0,0, 1,0,0 },
93 //FIXME: Disable CMN, as CCodes are backwards from compare expectations
94 //{ ARM::t2CMNrr, ARM::tCMN, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
95 { ARM::t2CMNzrr, ARM::tCMNz, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
96 { ARM::t2CMPri, ARM::tCMPi8, 0, 8, 0, 1, 0, 2,0, 0,0,0 },
97 { ARM::t2CMPrr, ARM::tCMPhir, 0, 0, 0, 0, 0, 2,0, 0,1,0 },
98 { ARM::t2EORrr, 0, ARM::tEOR, 0, 0, 0, 1, 0,0, 1,0,0 },
99 // FIXME: adr.n immediate offset must be multiple of 4.
100 //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
101 { ARM::t2LSLri, ARM::tLSLri, 0, 5, 0, 1, 0, 0,0, 1,0,1 },
102 { ARM::t2LSLrr, 0, ARM::tLSLrr, 0, 0, 0, 1, 0,0, 1,0,1 },
103 { ARM::t2LSRri, ARM::tLSRri, 0, 5, 0, 1, 0, 0,0, 1,0,1 },
104 { ARM::t2LSRrr, 0, ARM::tLSRrr, 0, 0, 0, 1, 0,0, 1,0,1 },
105 { ARM::t2MOVi, ARM::tMOVi8, 0, 8, 0, 1, 0, 0,0, 1,0,0 },
106 { ARM::t2MOVi16,ARM::tMOVi8, 0, 8, 0, 1, 0, 0,0, 1,1,0 },
107 // FIXME: Do we need the 16-bit 'S' variant?
108 { ARM::t2MOVr,ARM::tMOVr, 0, 0, 0, 0, 0, 1,0, 0,0,0 },
109 { ARM::t2MUL, 0, ARM::tMUL, 0, 0, 0, 1, 0,0, 1,0,0 },
110 { ARM::t2MVNr, ARM::tMVN, 0, 0, 0, 1, 0, 0,0, 0,0,0 },
111 { ARM::t2ORRrr, 0, ARM::tORR, 0, 0, 0, 1, 0,0, 1,0,0 },
112 { ARM::t2REV, ARM::tREV, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
113 { ARM::t2REV16, ARM::tREV16, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
114 { ARM::t2REVSH, ARM::tREVSH, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
115 { ARM::t2RORrr, 0, ARM::tROR, 0, 0, 0, 1, 0,0, 1,0,0 },
116 { ARM::t2RSBri, ARM::tRSB, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
117 { ARM::t2RSBSri,ARM::tRSB, 0, 0, 0, 1, 0, 2,0, 0,1,0 },
118 { ARM::t2SBCrr, 0, ARM::tSBC, 0, 0, 0, 1, 0,0, 0,0,0 },
119 { ARM::t2SUBri, ARM::tSUBi3, ARM::tSUBi8, 3, 8, 1, 1, 0,0, 0,0,0 },
120 { ARM::t2SUBrr, ARM::tSUBrr, 0, 0, 0, 1, 0, 0,0, 0,0,0 },
121 { ARM::t2SUBSri,ARM::tSUBi3, ARM::tSUBi8, 3, 8, 1, 1, 2,2, 0,0,0 },
122 { ARM::t2SUBSrr,ARM::tSUBrr, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
123 { ARM::t2SXTB, ARM::tSXTB, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
124 { ARM::t2SXTH, ARM::tSXTH, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
125 { ARM::t2TEQrr, ARM::tEOR, 0, 0, 0, 1, 0, 2,0, 0,1,0 },
126 { ARM::t2TSTrr, ARM::tTST, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
127 { ARM::t2UXTB, ARM::tUXTB, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
128 { ARM::t2UXTH, ARM::tUXTH, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
130 // FIXME: Clean this up after splitting each Thumb load / store opcode
131 // into multiple ones.
132 { ARM::t2LDRi12,ARM::tLDRi, ARM::tLDRspi, 5, 8, 1, 0, 0,0, 0,1,0 },
133 { ARM::t2LDRs, ARM::tLDRr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
134 { ARM::t2LDRBi12,ARM::tLDRBi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
135 { ARM::t2LDRBs, ARM::tLDRBr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
136 { ARM::t2LDRHi12,ARM::tLDRHi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
137 { ARM::t2LDRHs, ARM::tLDRHr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
138 { ARM::t2LDRSBs,ARM::tLDRSB, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
139 { ARM::t2LDRSHs,ARM::tLDRSH, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
140 { ARM::t2LDR_POST,ARM::tLDMIA_UPD,0, 0, 0, 1, 0, 0,0, 0,1,0 },
141 { ARM::t2STRi12,ARM::tSTRi, ARM::tSTRspi, 5, 8, 1, 0, 0,0, 0,1,0 },
142 { ARM::t2STRs, ARM::tSTRr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
143 { ARM::t2STRBi12,ARM::tSTRBi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
144 { ARM::t2STRBs, ARM::tSTRBr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
145 { ARM::t2STRHi12,ARM::tSTRHi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
146 { ARM::t2STRHs, ARM::tSTRHr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
147 { ARM::t2STR_POST,ARM::tSTMIA_UPD,0, 0, 0, 1, 0, 0,0, 0,1,0 },
149 { ARM::t2LDMIA, ARM::tLDMIA, 0, 0, 0, 1, 1, 1,1, 0,1,0 },
150 { ARM::t2LDMIA_RET,0, ARM::tPOP_RET, 0, 0, 1, 1, 1,1, 0,1,0 },
151 { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0, 0, 1, 1, 1,1, 0,1,0 },
152 // ARM::t2STMIA (with no basereg writeback) has no Thumb1 equivalent.
153 // tSTMIA_UPD is a change in semantics which can only be used if the base
154 // register is killed. This difference is correctly handled elsewhere.
155 { ARM::t2STMIA, ARM::tSTMIA_UPD, 0, 0, 0, 1, 1, 1,1, 0,1,0 },
156 { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0, 0, 0, 1, 1, 1,1, 0,1,0 },
157 { ARM::t2STMDB_UPD, 0, ARM::tPUSH, 0, 0, 1, 1, 1,1, 0,1,0 }
160 class Thumb2SizeReduce : public MachineFunctionPass {
164 const Thumb2InstrInfo *TII;
165 const ARMSubtarget *STI;
167 Thumb2SizeReduce(std::function<bool(const Function &)> Ftor = nullptr);
169 bool runOnMachineFunction(MachineFunction &MF) override;
171 MachineFunctionProperties getRequiredProperties() const override {
172 return MachineFunctionProperties().set(
173 MachineFunctionProperties::Property::NoVRegs);
176 StringRef getPassName() const override {
177 return THUMB2_SIZE_REDUCE_NAME;
181 /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
182 DenseMap<unsigned, unsigned> ReduceOpcodeMap;
184 bool canAddPseudoFlagDep(MachineInstr *Use, bool IsSelfLoop);
186 bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
187 bool is2Addr, ARMCC::CondCodes Pred,
188 bool LiveCPSR, bool &HasCC, bool &CCDead);
190 bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
191 const ReduceEntry &Entry);
193 bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
194 const ReduceEntry &Entry, bool LiveCPSR, bool IsSelfLoop);
196 /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
198 bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
199 const ReduceEntry &Entry, bool LiveCPSR,
202 /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
203 /// non-two-address instruction.
204 bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
205 const ReduceEntry &Entry, bool LiveCPSR,
208 /// ReduceMI - Attempt to reduce MI, return true on success.
209 bool ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
210 bool LiveCPSR, bool IsSelfLoop);
212 /// ReduceMBB - Reduce width of instructions in the specified basic block.
213 bool ReduceMBB(MachineBasicBlock &MBB);
218 // Last instruction to define CPSR in the current block.
219 MachineInstr *CPSRDef;
220 // Was CPSR last defined by a high latency instruction?
221 // When CPSRDef is null, this refers to CPSR defs in predecessors.
222 bool HighLatencyCPSR;
225 // The flags leaving this block have high latency.
226 bool HighLatencyCPSR = false;
227 // Has this block been visited yet?
228 bool Visited = false;
233 SmallVector<MBBInfo, 8> BlockInfo;
235 std::function<bool(const Function &)> PredicateFtor;
238 char Thumb2SizeReduce::ID = 0;
240 } // end anonymous namespace
242 INITIALIZE_PASS(Thumb2SizeReduce, DEBUG_TYPE, THUMB2_SIZE_REDUCE_NAME, false,
245 Thumb2SizeReduce::Thumb2SizeReduce(std::function<bool(const Function &)> Ftor)
246 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
247 OptimizeSize = MinimizeSize = false;
248 for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
249 unsigned FromOpc = ReduceTable[i].WideOpc;
250 if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
251 llvm_unreachable("Duplicated entries?");
255 static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
256 for (const MCPhysReg *Regs = MCID.getImplicitDefs(); *Regs; ++Regs)
257 if (*Regs == ARM::CPSR)
262 // Check for a likely high-latency flag def.
263 static bool isHighLatencyCPSR(MachineInstr *Def) {
264 switch(Def->getOpcode()) {
272 /// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
273 /// the 's' 16-bit instruction partially update CPSR. Abort the
274 /// transformation to avoid adding false dependency on last CPSR setting
275 /// instruction which hurts the ability for out-of-order execution engine
276 /// to do register renaming magic.
277 /// This function checks if there is a read-of-write dependency between the
278 /// last instruction that defines the CPSR and the current instruction. If there
279 /// is, then there is no harm done since the instruction cannot be retired
280 /// before the CPSR setting instruction anyway.
281 /// Note, we are not doing full dependency analysis here for the sake of compile
282 /// time. We're not looking for cases like:
284 /// r1 = add.w r0, ...
287 /// In this case it would have been ok to narrow the mul.w to muls since there
288 /// are indirect RAW dependency between the muls and the mul.w
290 Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Use, bool FirstInSelfLoop) {
291 // Disable the check for -Oz (aka OptimizeForSizeHarder).
292 if (MinimizeSize || !STI->avoidCPSRPartialUpdate())
296 // If this BB loops back to itself, conservatively avoid narrowing the
297 // first instruction that does partial flag update.
298 return HighLatencyCPSR || FirstInSelfLoop;
300 SmallSet<unsigned, 2> Defs;
301 for (const MachineOperand &MO : CPSRDef->operands()) {
302 if (!MO.isReg() || MO.isUndef() || MO.isUse())
304 unsigned Reg = MO.getReg();
305 if (Reg == 0 || Reg == ARM::CPSR)
310 for (const MachineOperand &MO : Use->operands()) {
311 if (!MO.isReg() || MO.isUndef() || MO.isDef())
313 unsigned Reg = MO.getReg();
318 // If the current CPSR has high latency, try to avoid the false dependency.
322 // tMOVi8 usually doesn't start long dependency chains, and there are a lot
323 // of them, so always shrink them when CPSR doesn't have high latency.
324 if (Use->getOpcode() == ARM::t2MOVi ||
325 Use->getOpcode() == ARM::t2MOVi16)
328 // No read-after-write dependency. The narrowing will add false dependency.
333 Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
334 bool is2Addr, ARMCC::CondCodes Pred,
335 bool LiveCPSR, bool &HasCC, bool &CCDead) {
336 if ((is2Addr && Entry.PredCC2 == 0) ||
337 (!is2Addr && Entry.PredCC1 == 0)) {
338 if (Pred == ARMCC::AL) {
339 // Not predicated, must set CPSR.
341 // Original instruction was not setting CPSR, but CPSR is not
342 // currently live anyway. It's ok to set it. The CPSR def is
352 // Predicated, must not set CPSR.
356 } else if ((is2Addr && Entry.PredCC2 == 2) ||
357 (!is2Addr && Entry.PredCC1 == 2)) {
358 /// Old opcode has an optional def of CPSR.
361 // If old opcode does not implicitly define CPSR, then it's not ok since
362 // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
363 if (!HasImplicitCPSRDef(MI->getDesc()))
367 // 16-bit instruction does not set CPSR.
375 static bool VerifyLowRegs(MachineInstr *MI) {
376 unsigned Opc = MI->getOpcode();
377 bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA_UPD);
378 bool isLROk = (Opc == ARM::t2STMDB_UPD);
379 bool isSPOk = isPCOk || isLROk;
380 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
381 const MachineOperand &MO = MI->getOperand(i);
382 if (!MO.isReg() || MO.isImplicit())
384 unsigned Reg = MO.getReg();
385 if (Reg == 0 || Reg == ARM::CPSR)
387 if (isPCOk && Reg == ARM::PC)
389 if (isLROk && Reg == ARM::LR)
391 if (Reg == ARM::SP) {
394 if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
395 // Special case for these ldr / str with sp as base register.
398 if (!isARMLowRegister(Reg))
405 Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
406 const ReduceEntry &Entry) {
407 if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
411 bool HasImmOffset = false;
412 bool HasShift = false;
413 bool HasOffReg = true;
414 bool isLdStMul = false;
415 unsigned Opc = Entry.NarrowOpc1;
416 unsigned OpNum = 3; // First 'rest' of operands.
417 uint8_t ImmLimit = Entry.Imm1Limit;
419 switch (Entry.WideOpc) {
421 llvm_unreachable("Unexpected Thumb2 load / store opcode!");
424 if (MI->getOperand(1).getReg() == ARM::SP) {
425 Opc = Entry.NarrowOpc2;
426 ImmLimit = Entry.Imm2Limit;
455 case ARM::t2LDR_POST:
456 case ARM::t2STR_POST: {
457 if (!MBB.getParent()->getFunction().optForMinSize())
460 if (!MI->hasOneMemOperand() ||
461 (*MI->memoperands_begin())->getAlignment() < 4)
464 // We're creating a completely different type of load/store - LDM from LDR.
465 // For this reason we can't reuse the logic at the end of this function; we
466 // have to implement the MI building here.
467 bool IsStore = Entry.WideOpc == ARM::t2STR_POST;
468 unsigned Rt = MI->getOperand(IsStore ? 1 : 0).getReg();
469 unsigned Rn = MI->getOperand(IsStore ? 0 : 1).getReg();
470 unsigned Offset = MI->getOperand(3).getImm();
471 unsigned PredImm = MI->getOperand(4).getImm();
472 unsigned PredReg = MI->getOperand(5).getReg();
473 assert(isARMLowRegister(Rt));
474 assert(isARMLowRegister(Rn));
479 // Add the 16-bit load / store instruction.
480 DebugLoc dl = MI->getDebugLoc();
481 auto MIB = BuildMI(MBB, MI, dl, TII->get(Entry.NarrowOpc1))
482 .addReg(Rn, RegState::Define)
486 .addReg(Rt, IsStore ? 0 : RegState::Define);
488 // Transfer memoperands.
489 MIB.setMemRefs(MI->memoperands());
491 // Transfer MI flags.
492 MIB.setMIFlags(MI->getFlags());
494 // Kill the old instruction.
495 MI->eraseFromBundle();
500 unsigned BaseReg = MI->getOperand(0).getReg();
501 assert(isARMLowRegister(BaseReg));
503 // For the non-writeback version (this one), the base register must be
504 // one of the registers being loaded.
506 for (unsigned i = 3; i < MI->getNumOperands(); ++i) {
507 if (MI->getOperand(i).getReg() == BaseReg) {
521 // If the base register is killed, we don't care what its value is after the
522 // instruction, so we can use an updating STMIA.
523 if (!MI->getOperand(0).isKill())
527 case ARM::t2LDMIA_RET: {
528 unsigned BaseReg = MI->getOperand(1).getReg();
529 if (BaseReg != ARM::SP)
531 Opc = Entry.NarrowOpc2; // tPOP_RET
536 case ARM::t2LDMIA_UPD:
537 case ARM::t2STMIA_UPD:
538 case ARM::t2STMDB_UPD: {
541 unsigned BaseReg = MI->getOperand(1).getReg();
542 if (BaseReg == ARM::SP &&
543 (Entry.WideOpc == ARM::t2LDMIA_UPD ||
544 Entry.WideOpc == ARM::t2STMDB_UPD)) {
545 Opc = Entry.NarrowOpc2; // tPOP or tPUSH
547 } else if (!isARMLowRegister(BaseReg) ||
548 (Entry.WideOpc != ARM::t2LDMIA_UPD &&
549 Entry.WideOpc != ARM::t2STMIA_UPD)) {
558 unsigned OffsetReg = 0;
559 bool OffsetKill = false;
560 bool OffsetInternal = false;
562 OffsetReg = MI->getOperand(2).getReg();
563 OffsetKill = MI->getOperand(2).isKill();
564 OffsetInternal = MI->getOperand(2).isInternalRead();
566 if (MI->getOperand(3).getImm())
567 // Thumb1 addressing mode doesn't support shift.
571 unsigned OffsetImm = 0;
573 OffsetImm = MI->getOperand(2).getImm();
574 unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
576 if ((OffsetImm & (Scale - 1)) || OffsetImm > MaxOffset)
577 // Make sure the immediate field fits.
581 // Add the 16-bit load / store instruction.
582 DebugLoc dl = MI->getDebugLoc();
583 MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, TII->get(Opc));
585 // tSTMIA_UPD takes a defining register operand. We've already checked that
586 // the register is killed, so mark it as dead here.
587 if (Entry.WideOpc == ARM::t2STMIA)
588 MIB.addReg(MI->getOperand(0).getReg(), RegState::Define | RegState::Dead);
591 MIB.add(MI->getOperand(0));
592 MIB.add(MI->getOperand(1));
595 MIB.addImm(OffsetImm / Scale);
597 assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
600 MIB.addReg(OffsetReg, getKillRegState(OffsetKill) |
601 getInternalReadRegState(OffsetInternal));
604 // Transfer the rest of operands.
605 for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
606 MIB.add(MI->getOperand(OpNum));
608 // Transfer memoperands.
609 MIB.setMemRefs(MI->memoperands());
611 // Transfer MI flags.
612 MIB.setMIFlags(MI->getFlags());
614 LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
615 << " to 16-bit: " << *MIB);
623 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
624 const ReduceEntry &Entry,
625 bool LiveCPSR, bool IsSelfLoop) {
626 unsigned Opc = MI->getOpcode();
627 if (Opc == ARM::t2ADDri) {
628 // If the source register is SP, try to reduce to tADDrSPi, otherwise
629 // it's a normal reduce.
630 if (MI->getOperand(1).getReg() != ARM::SP) {
631 if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
633 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
635 // Try to reduce to tADDrSPi.
636 unsigned Imm = MI->getOperand(2).getImm();
637 // The immediate must be in range, the destination register must be a low
638 // reg, the predicate must be "always" and the condition flags must not
640 if (Imm & 3 || Imm > 1020)
642 if (!isARMLowRegister(MI->getOperand(0).getReg()))
644 if (MI->getOperand(3).getImm() != ARMCC::AL)
646 const MCInstrDesc &MCID = MI->getDesc();
647 if (MCID.hasOptionalDef() &&
648 MI->getOperand(MCID.getNumOperands()-1).getReg() == ARM::CPSR)
651 MachineInstrBuilder MIB =
652 BuildMI(MBB, MI, MI->getDebugLoc(),
653 TII->get(ARM::tADDrSPi))
654 .add(MI->getOperand(0))
655 .add(MI->getOperand(1))
656 .addImm(Imm / 4) // The tADDrSPi has an implied scale by four.
657 .add(predOps(ARMCC::AL));
659 // Transfer MI flags.
660 MIB.setMIFlags(MI->getFlags());
662 LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
663 << " to 16-bit: " << *MIB);
670 if (Entry.LowRegs1 && !VerifyLowRegs(MI))
673 if (MI->mayLoadOrStore())
674 return ReduceLoadStore(MBB, MI, Entry);
679 case ARM::t2ADDSrr: {
680 unsigned PredReg = 0;
681 if (getInstrPredicate(*MI, PredReg) == ARMCC::AL) {
685 if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
689 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
700 if (MI->getOperand(2).getImm() == 0)
701 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
704 // Can convert only 'pure' immediate operands, not immediates obtained as
705 // globals' addresses.
706 if (MI->getOperand(1).isImm())
707 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
710 // Try to reduce to the lo-reg only version first. Why there are two
711 // versions of the instruction is a mystery.
712 // It would be nice to just have two entries in the master table that
713 // are prioritized, but the table assumes a unique entry for each
714 // source insn opcode. So for now, we hack a local entry record to use.
715 static const ReduceEntry NarrowEntry =
716 { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1,0 };
717 if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, IsSelfLoop))
719 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
722 unsigned PredReg = 0;
723 // Can only convert to eors if we're not in an IT block.
724 if (getInstrPredicate(*MI, PredReg) != ARMCC::AL)
726 // TODO if Operand 0 is not killed but Operand 1 is, then we could write
728 if (MI->getOperand(0).isKill())
729 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
736 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
737 const ReduceEntry &Entry,
738 bool LiveCPSR, bool IsSelfLoop) {
739 if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
742 if (!OptimizeSize && Entry.AvoidMovs && STI->avoidMOVsShifterOperand())
743 // Don't issue movs with shifter operand for some CPUs unless we
744 // are optimizing for size.
747 unsigned Reg0 = MI->getOperand(0).getReg();
748 unsigned Reg1 = MI->getOperand(1).getReg();
749 // t2MUL is "special". The tied source operand is second, not first.
750 if (MI->getOpcode() == ARM::t2MUL) {
751 unsigned Reg2 = MI->getOperand(2).getReg();
752 // Early exit if the regs aren't all low regs.
753 if (!isARMLowRegister(Reg0) || !isARMLowRegister(Reg1)
754 || !isARMLowRegister(Reg2))
757 // If the other operand also isn't the same as the destination, we
761 // Try to commute the operands to make it a 2-address instruction.
762 MachineInstr *CommutedMI = TII->commuteInstruction(*MI);
766 } else if (Reg0 != Reg1) {
767 // Try to commute the operands to make it a 2-address instruction.
768 unsigned CommOpIdx1 = 1;
769 unsigned CommOpIdx2 = TargetInstrInfo::CommuteAnyOperandIndex;
770 if (!TII->findCommutedOpIndices(*MI, CommOpIdx1, CommOpIdx2) ||
771 MI->getOperand(CommOpIdx2).getReg() != Reg0)
773 MachineInstr *CommutedMI =
774 TII->commuteInstruction(*MI, false, CommOpIdx1, CommOpIdx2);
778 if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
780 if (Entry.Imm2Limit) {
781 unsigned Imm = MI->getOperand(2).getImm();
782 unsigned Limit = (1 << Entry.Imm2Limit) - 1;
786 unsigned Reg2 = MI->getOperand(2).getReg();
787 if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
791 // Check if it's possible / necessary to transfer the predicate.
792 const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
793 unsigned PredReg = 0;
794 ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
795 bool SkipPred = false;
796 if (Pred != ARMCC::AL) {
797 if (!NewMCID.isPredicable())
798 // Can't transfer predicate, fail.
801 SkipPred = !NewMCID.isPredicable();
806 const MCInstrDesc &MCID = MI->getDesc();
807 if (MCID.hasOptionalDef()) {
808 unsigned NumOps = MCID.getNumOperands();
809 HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
810 if (HasCC && MI->getOperand(NumOps-1).isDead())
813 if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
816 // Avoid adding a false dependency on partial flag update by some 16-bit
817 // instructions which has the 's' bit set.
818 if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
819 canAddPseudoFlagDep(MI, IsSelfLoop))
822 // Add the 16-bit instruction.
823 DebugLoc dl = MI->getDebugLoc();
824 MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
825 MIB.add(MI->getOperand(0));
826 if (NewMCID.hasOptionalDef())
827 MIB.add(HasCC ? t1CondCodeOp(CCDead) : condCodeOp());
829 // Transfer the rest of operands.
830 unsigned NumOps = MCID.getNumOperands();
831 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
832 if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
834 if (SkipPred && MCID.OpInfo[i].isPredicate())
836 MIB.add(MI->getOperand(i));
839 // Transfer MI flags.
840 MIB.setMIFlags(MI->getFlags());
842 LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
843 << " to 16-bit: " << *MIB);
851 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
852 const ReduceEntry &Entry,
853 bool LiveCPSR, bool IsSelfLoop) {
854 if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
857 if (!OptimizeSize && Entry.AvoidMovs && STI->avoidMOVsShifterOperand())
858 // Don't issue movs with shifter operand for some CPUs unless we
859 // are optimizing for size.
862 unsigned Limit = ~0U;
864 Limit = (1 << Entry.Imm1Limit) - 1;
866 const MCInstrDesc &MCID = MI->getDesc();
867 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
868 if (MCID.OpInfo[i].isPredicate())
870 const MachineOperand &MO = MI->getOperand(i);
872 unsigned Reg = MO.getReg();
873 if (!Reg || Reg == ARM::CPSR)
875 if (Entry.LowRegs1 && !isARMLowRegister(Reg))
877 } else if (MO.isImm() &&
878 !MCID.OpInfo[i].isPredicate()) {
879 if (((unsigned)MO.getImm()) > Limit)
884 // Check if it's possible / necessary to transfer the predicate.
885 const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
886 unsigned PredReg = 0;
887 ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
888 bool SkipPred = false;
889 if (Pred != ARMCC::AL) {
890 if (!NewMCID.isPredicable())
891 // Can't transfer predicate, fail.
894 SkipPred = !NewMCID.isPredicable();
899 if (MCID.hasOptionalDef()) {
900 unsigned NumOps = MCID.getNumOperands();
901 HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
902 if (HasCC && MI->getOperand(NumOps-1).isDead())
905 if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
908 // Avoid adding a false dependency on partial flag update by some 16-bit
909 // instructions which has the 's' bit set.
910 if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
911 canAddPseudoFlagDep(MI, IsSelfLoop))
914 // Add the 16-bit instruction.
915 DebugLoc dl = MI->getDebugLoc();
916 MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
918 // TEQ is special in that it doesn't define a register but we're converting
919 // it into an EOR which does. So add the first operand as a def and then
921 if (MCID.getOpcode() == ARM::t2TEQrr) {
922 MIB.add(MI->getOperand(0));
923 MIB->getOperand(0).setIsKill(false);
924 MIB->getOperand(0).setIsDef(true);
925 MIB->getOperand(0).setIsDead(true);
927 if (NewMCID.hasOptionalDef())
928 MIB.add(HasCC ? t1CondCodeOp(CCDead) : condCodeOp());
929 MIB.add(MI->getOperand(0));
931 MIB.add(MI->getOperand(0));
932 if (NewMCID.hasOptionalDef())
933 MIB.add(HasCC ? t1CondCodeOp(CCDead) : condCodeOp());
936 // Transfer the rest of operands.
937 unsigned NumOps = MCID.getNumOperands();
938 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
939 if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
941 if ((MCID.getOpcode() == ARM::t2RSBSri ||
942 MCID.getOpcode() == ARM::t2RSBri ||
943 MCID.getOpcode() == ARM::t2SXTB ||
944 MCID.getOpcode() == ARM::t2SXTH ||
945 MCID.getOpcode() == ARM::t2UXTB ||
946 MCID.getOpcode() == ARM::t2UXTH) && i == 2)
947 // Skip the zero immediate operand, it's now implicit.
949 bool isPred = (i < NumOps && MCID.OpInfo[i].isPredicate());
950 if (SkipPred && isPred)
952 const MachineOperand &MO = MI->getOperand(i);
953 if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
954 // Skip implicit def of CPSR. Either it's modeled as an optional
955 // def now or it's already an implicit def on the new instruction.
959 if (!MCID.isPredicable() && NewMCID.isPredicable())
960 MIB.add(predOps(ARMCC::AL));
962 // Transfer MI flags.
963 MIB.setMIFlags(MI->getFlags());
965 LLVM_DEBUG(errs() << "Converted 32-bit: " << *MI
966 << " to 16-bit: " << *MIB);
973 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
975 for (const MachineOperand &MO : MI.operands()) {
976 if (!MO.isReg() || MO.isUndef() || MO.isUse())
978 if (MO.getReg() != ARM::CPSR)
986 return HasDef || LiveCPSR;
989 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
990 for (const MachineOperand &MO : MI.operands()) {
991 if (!MO.isReg() || MO.isUndef() || MO.isDef())
993 if (MO.getReg() != ARM::CPSR)
995 assert(LiveCPSR && "CPSR liveness tracking is wrong!");
1005 bool Thumb2SizeReduce::ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
1006 bool LiveCPSR, bool IsSelfLoop) {
1007 unsigned Opcode = MI->getOpcode();
1008 DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
1009 if (OPI == ReduceOpcodeMap.end())
1011 const ReduceEntry &Entry = ReduceTable[OPI->second];
1013 // Don't attempt normal reductions on "special" cases for now.
1015 return ReduceSpecial(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
1017 // Try to transform to a 16-bit two-address instruction.
1018 if (Entry.NarrowOpc2 &&
1019 ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
1022 // Try to transform to a 16-bit non-two-address instruction.
1023 if (Entry.NarrowOpc1 &&
1024 ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
1030 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
1031 bool Modified = false;
1033 // Yes, CPSR could be livein.
1034 bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
1035 MachineInstr *BundleMI = nullptr;
1038 HighLatencyCPSR = false;
1040 // Check predecessors for the latest CPSRDef.
1041 for (auto *Pred : MBB.predecessors()) {
1042 const MBBInfo &PInfo = BlockInfo[Pred->getNumber()];
1043 if (!PInfo.Visited) {
1044 // Since blocks are visited in RPO, this must be a back-edge.
1047 if (PInfo.HighLatencyCPSR) {
1048 HighLatencyCPSR = true;
1053 // If this BB loops back to itself, conservatively avoid narrowing the
1054 // first instruction that does partial flag update.
1055 bool IsSelfLoop = MBB.isSuccessor(&MBB);
1056 MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),E = MBB.instr_end();
1057 MachineBasicBlock::instr_iterator NextMII;
1058 for (; MII != E; MII = NextMII) {
1059 NextMII = std::next(MII);
1061 MachineInstr *MI = &*MII;
1062 if (MI->isBundle()) {
1066 if (MI->isDebugInstr())
1069 LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
1071 // Does NextMII belong to the same bundle as MI?
1072 bool NextInSameBundle = NextMII != E && NextMII->isBundledWithPred();
1074 if (ReduceMI(MBB, MI, LiveCPSR, IsSelfLoop)) {
1076 MachineBasicBlock::instr_iterator I = std::prev(NextMII);
1078 // Removing and reinserting the first instruction in a bundle will break
1079 // up the bundle. Fix the bundling if it was broken.
1080 if (NextInSameBundle && !NextMII->isBundledWithPred())
1081 NextMII->bundleWithPred();
1084 if (BundleMI && !NextInSameBundle && MI->isInsideBundle()) {
1085 // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
1086 // marker is only on the BUNDLE instruction. Process the BUNDLE
1087 // instruction as we finish with the bundled instruction to work around
1088 // the inconsistency.
1089 if (BundleMI->killsRegister(ARM::CPSR))
1091 MachineOperand *MO = BundleMI->findRegisterDefOperand(ARM::CPSR);
1092 if (MO && !MO->isDead())
1094 MO = BundleMI->findRegisterUseOperand(ARM::CPSR);
1095 if (MO && !MO->isKill())
1099 bool DefCPSR = false;
1100 LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
1102 // Calls don't really set CPSR.
1104 HighLatencyCPSR = false;
1106 } else if (DefCPSR) {
1107 // This is the last CPSR defining instruction.
1109 HighLatencyCPSR = isHighLatencyCPSR(CPSRDef);
1114 MBBInfo &Info = BlockInfo[MBB.getNumber()];
1115 Info.HighLatencyCPSR = HighLatencyCPSR;
1116 Info.Visited = true;
1120 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
1121 if (PredicateFtor && !PredicateFtor(MF.getFunction()))
1124 STI = &static_cast<const ARMSubtarget &>(MF.getSubtarget());
1125 if (STI->isThumb1Only() || STI->prefers32BitThumb())
1128 TII = static_cast<const Thumb2InstrInfo *>(STI->getInstrInfo());
1130 // Optimizing / minimizing size? Minimizing size implies optimizing for size.
1131 OptimizeSize = MF.getFunction().optForSize();
1132 MinimizeSize = MF.getFunction().optForMinSize();
1135 BlockInfo.resize(MF.getNumBlockIDs());
1137 // Visit blocks in reverse post-order so LastCPSRDef is known for all
1139 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
1140 bool Modified = false;
1141 for (ReversePostOrderTraversal<MachineFunction*>::rpo_iterator
1142 I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
1143 Modified |= ReduceMBB(**I);
1147 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
1149 FunctionPass *llvm::createThumb2SizeReductionPass(
1150 std::function<bool(const Function &)> Ftor) {
1151 return new Thumb2SizeReduce(std::move(Ftor));