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 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "t2-reduce-size"
12 #include "ARMBaseInstrInfo.h"
13 #include "ARMSubtarget.h"
14 #include "MCTargetDesc/ARMAddressingModes.h"
15 #include "Thumb2InstrInfo.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/IR/Function.h" // To access Function attributes
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetMachine.h"
28 STATISTIC(NumNarrows, "Number of 32-bit instrs reduced to 16-bit ones");
29 STATISTIC(Num2Addrs, "Number of 32-bit instrs reduced to 2addr 16-bit ones");
30 STATISTIC(NumLdSts, "Number of 32-bit load / store reduced to 16-bit ones");
32 static cl::opt<int> ReduceLimit("t2-reduce-limit",
33 cl::init(-1), cl::Hidden);
34 static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
35 cl::init(-1), cl::Hidden);
36 static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
37 cl::init(-1), cl::Hidden);
40 /// ReduceTable - A static table with information on mapping from wide
43 uint16_t WideOpc; // Wide opcode
44 uint16_t NarrowOpc1; // Narrow opcode to transform to
45 uint16_t NarrowOpc2; // Narrow opcode when it's two-address
46 uint8_t Imm1Limit; // Limit of immediate field (bits)
47 uint8_t Imm2Limit; // Limit of immediate field when it's two-address
48 unsigned LowRegs1 : 1; // Only possible if low-registers are used
49 unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
50 unsigned PredCC1 : 2; // 0 - If predicated, cc is on and vice versa.
52 // 2 - Always set CPSR.
54 unsigned PartFlag : 1; // 16-bit instruction does partial flag update
55 unsigned Special : 1; // Needs to be dealt with specially
56 unsigned AvoidMovs: 1; // Avoid movs with shifter operand (for Swift)
59 static const ReduceEntry ReduceTable[] = {
60 // Wide, Narrow1, Narrow2, imm1,imm2, lo1, lo2, P/C,PF,S,AM
61 { ARM::t2ADCrr, 0, ARM::tADC, 0, 0, 0, 1, 0,0, 0,0,0 },
62 { ARM::t2ADDri, ARM::tADDi3, ARM::tADDi8, 3, 8, 1, 1, 0,0, 0,1,0 },
63 { ARM::t2ADDrr, ARM::tADDrr, ARM::tADDhirr, 0, 0, 1, 0, 0,1, 0,0,0 },
64 { ARM::t2ADDSri,ARM::tADDi3, ARM::tADDi8, 3, 8, 1, 1, 2,2, 0,1,0 },
65 { ARM::t2ADDSrr,ARM::tADDrr, 0, 0, 0, 1, 0, 2,0, 0,1,0 },
66 { ARM::t2ANDrr, 0, ARM::tAND, 0, 0, 0, 1, 0,0, 1,0,0 },
67 { ARM::t2ASRri, ARM::tASRri, 0, 5, 0, 1, 0, 0,0, 1,0,1 },
68 { ARM::t2ASRrr, 0, ARM::tASRrr, 0, 0, 0, 1, 0,0, 1,0,1 },
69 { ARM::t2BICrr, 0, ARM::tBIC, 0, 0, 0, 1, 0,0, 1,0,0 },
70 //FIXME: Disable CMN, as CCodes are backwards from compare expectations
71 //{ ARM::t2CMNrr, ARM::tCMN, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
72 { ARM::t2CMNzrr, ARM::tCMNz, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
73 { ARM::t2CMPri, ARM::tCMPi8, 0, 8, 0, 1, 0, 2,0, 0,0,0 },
74 { ARM::t2CMPrr, ARM::tCMPhir, 0, 0, 0, 0, 0, 2,0, 0,1,0 },
75 { ARM::t2EORrr, 0, ARM::tEOR, 0, 0, 0, 1, 0,0, 1,0,0 },
76 // FIXME: adr.n immediate offset must be multiple of 4.
77 //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
78 { ARM::t2LSLri, ARM::tLSLri, 0, 5, 0, 1, 0, 0,0, 1,0,1 },
79 { ARM::t2LSLrr, 0, ARM::tLSLrr, 0, 0, 0, 1, 0,0, 1,0,1 },
80 { ARM::t2LSRri, ARM::tLSRri, 0, 5, 0, 1, 0, 0,0, 1,0,1 },
81 { ARM::t2LSRrr, 0, ARM::tLSRrr, 0, 0, 0, 1, 0,0, 1,0,1 },
82 { ARM::t2MOVi, ARM::tMOVi8, 0, 8, 0, 1, 0, 0,0, 1,0,0 },
83 { ARM::t2MOVi16,ARM::tMOVi8, 0, 8, 0, 1, 0, 0,0, 1,1,0 },
84 // FIXME: Do we need the 16-bit 'S' variant?
85 { ARM::t2MOVr,ARM::tMOVr, 0, 0, 0, 0, 0, 1,0, 0,0,0 },
86 { ARM::t2MUL, 0, ARM::tMUL, 0, 0, 0, 1, 0,0, 1,0,0 },
87 { ARM::t2MVNr, ARM::tMVN, 0, 0, 0, 1, 0, 0,0, 0,0,0 },
88 { ARM::t2ORRrr, 0, ARM::tORR, 0, 0, 0, 1, 0,0, 1,0,0 },
89 { ARM::t2REV, ARM::tREV, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
90 { ARM::t2REV16, ARM::tREV16, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
91 { ARM::t2REVSH, ARM::tREVSH, 0, 0, 0, 1, 0, 1,0, 0,0,0 },
92 { ARM::t2RORrr, 0, ARM::tROR, 0, 0, 0, 1, 0,0, 1,0,0 },
93 { ARM::t2RSBri, ARM::tRSB, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
94 { ARM::t2RSBSri,ARM::tRSB, 0, 0, 0, 1, 0, 2,0, 0,1,0 },
95 { ARM::t2SBCrr, 0, ARM::tSBC, 0, 0, 0, 1, 0,0, 0,0,0 },
96 { ARM::t2SUBri, ARM::tSUBi3, ARM::tSUBi8, 3, 8, 1, 1, 0,0, 0,0,0 },
97 { ARM::t2SUBrr, ARM::tSUBrr, 0, 0, 0, 1, 0, 0,0, 0,0,0 },
98 { ARM::t2SUBSri,ARM::tSUBi3, ARM::tSUBi8, 3, 8, 1, 1, 2,2, 0,0,0 },
99 { ARM::t2SUBSrr,ARM::tSUBrr, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
100 { ARM::t2SXTB, ARM::tSXTB, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
101 { ARM::t2SXTH, ARM::tSXTH, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
102 { ARM::t2TSTrr, ARM::tTST, 0, 0, 0, 1, 0, 2,0, 0,0,0 },
103 { ARM::t2UXTB, ARM::tUXTB, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
104 { ARM::t2UXTH, ARM::tUXTH, 0, 0, 0, 1, 0, 1,0, 0,1,0 },
106 // FIXME: Clean this up after splitting each Thumb load / store opcode
107 // into multiple ones.
108 { ARM::t2LDRi12,ARM::tLDRi, ARM::tLDRspi, 5, 8, 1, 0, 0,0, 0,1,0 },
109 { ARM::t2LDRs, ARM::tLDRr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
110 { ARM::t2LDRBi12,ARM::tLDRBi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
111 { ARM::t2LDRBs, ARM::tLDRBr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
112 { ARM::t2LDRHi12,ARM::tLDRHi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
113 { ARM::t2LDRHs, ARM::tLDRHr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
114 { ARM::t2LDRSBs,ARM::tLDRSB, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
115 { ARM::t2LDRSHs,ARM::tLDRSH, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
116 { ARM::t2STRi12,ARM::tSTRi, ARM::tSTRspi, 5, 8, 1, 0, 0,0, 0,1,0 },
117 { ARM::t2STRs, ARM::tSTRr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
118 { ARM::t2STRBi12,ARM::tSTRBi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
119 { ARM::t2STRBs, ARM::tSTRBr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
120 { ARM::t2STRHi12,ARM::tSTRHi, 0, 5, 0, 1, 0, 0,0, 0,1,0 },
121 { ARM::t2STRHs, ARM::tSTRHr, 0, 0, 0, 1, 0, 0,0, 0,1,0 },
123 { ARM::t2LDMIA, ARM::tLDMIA, 0, 0, 0, 1, 1, 1,1, 0,1,0 },
124 { ARM::t2LDMIA_RET,0, ARM::tPOP_RET, 0, 0, 1, 1, 1,1, 0,1,0 },
125 { ARM::t2LDMIA_UPD,ARM::tLDMIA_UPD,ARM::tPOP,0, 0, 1, 1, 1,1, 0,1,0 },
126 // ARM::t2STM (with no basereg writeback) has no Thumb1 equivalent
127 { ARM::t2STMIA_UPD,ARM::tSTMIA_UPD, 0, 0, 0, 1, 1, 1,1, 0,1,0 },
128 { ARM::t2STMDB_UPD, 0, ARM::tPUSH, 0, 0, 1, 1, 1,1, 0,1,0 }
131 class Thumb2SizeReduce : public MachineFunctionPass {
136 const Thumb2InstrInfo *TII;
137 const ARMSubtarget *STI;
139 bool runOnMachineFunction(MachineFunction &MF) override;
141 const char *getPassName() const override {
142 return "Thumb2 instruction size reduction pass";
146 /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
147 DenseMap<unsigned, unsigned> ReduceOpcodeMap;
149 bool canAddPseudoFlagDep(MachineInstr *Use, bool IsSelfLoop);
151 bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
152 bool is2Addr, ARMCC::CondCodes Pred,
153 bool LiveCPSR, bool &HasCC, bool &CCDead);
155 bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
156 const ReduceEntry &Entry);
158 bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
159 const ReduceEntry &Entry, bool LiveCPSR, bool IsSelfLoop);
161 /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
163 bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
164 const ReduceEntry &Entry, bool LiveCPSR,
167 /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
168 /// non-two-address instruction.
169 bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
170 const ReduceEntry &Entry, bool LiveCPSR,
173 /// ReduceMI - Attempt to reduce MI, return true on success.
174 bool ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
175 bool LiveCPSR, bool IsSelfLoop);
177 /// ReduceMBB - Reduce width of instructions in the specified basic block.
178 bool ReduceMBB(MachineBasicBlock &MBB);
183 // Last instruction to define CPSR in the current block.
184 MachineInstr *CPSRDef;
185 // Was CPSR last defined by a high latency instruction?
186 // When CPSRDef is null, this refers to CPSR defs in predecessors.
187 bool HighLatencyCPSR;
190 // The flags leaving this block have high latency.
191 bool HighLatencyCPSR;
192 // Has this block been visited yet?
195 MBBInfo() : HighLatencyCPSR(false), Visited(false) {}
198 SmallVector<MBBInfo, 8> BlockInfo;
200 char Thumb2SizeReduce::ID = 0;
203 Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(ID) {
204 OptimizeSize = MinimizeSize = false;
205 for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
206 unsigned FromOpc = ReduceTable[i].WideOpc;
207 if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
208 assert(false && "Duplicated entries?");
212 static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
213 for (const uint16_t *Regs = MCID.getImplicitDefs(); *Regs; ++Regs)
214 if (*Regs == ARM::CPSR)
219 // Check for a likely high-latency flag def.
220 static bool isHighLatencyCPSR(MachineInstr *Def) {
221 switch(Def->getOpcode()) {
229 /// canAddPseudoFlagDep - For A9 (and other out-of-order) implementations,
230 /// the 's' 16-bit instruction partially update CPSR. Abort the
231 /// transformation to avoid adding false dependency on last CPSR setting
232 /// instruction which hurts the ability for out-of-order execution engine
233 /// to do register renaming magic.
234 /// This function checks if there is a read-of-write dependency between the
235 /// last instruction that defines the CPSR and the current instruction. If there
236 /// is, then there is no harm done since the instruction cannot be retired
237 /// before the CPSR setting instruction anyway.
238 /// Note, we are not doing full dependency analysis here for the sake of compile
239 /// time. We're not looking for cases like:
241 /// r1 = add.w r0, ...
244 /// In this case it would have been ok to narrow the mul.w to muls since there
245 /// are indirect RAW dependency between the muls and the mul.w
247 Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Use, bool FirstInSelfLoop) {
248 // Disable the check for -Oz (aka OptimizeForSizeHarder).
249 if (MinimizeSize || !STI->avoidCPSRPartialUpdate())
253 // If this BB loops back to itself, conservatively avoid narrowing the
254 // first instruction that does partial flag update.
255 return HighLatencyCPSR || FirstInSelfLoop;
257 SmallSet<unsigned, 2> Defs;
258 for (const MachineOperand &MO : CPSRDef->operands()) {
259 if (!MO.isReg() || MO.isUndef() || MO.isUse())
261 unsigned Reg = MO.getReg();
262 if (Reg == 0 || Reg == ARM::CPSR)
267 for (const MachineOperand &MO : Use->operands()) {
268 if (!MO.isReg() || MO.isUndef() || MO.isDef())
270 unsigned Reg = MO.getReg();
275 // If the current CPSR has high latency, try to avoid the false dependency.
279 // tMOVi8 usually doesn't start long dependency chains, and there are a lot
280 // of them, so always shrink them when CPSR doesn't have high latency.
281 if (Use->getOpcode() == ARM::t2MOVi ||
282 Use->getOpcode() == ARM::t2MOVi16)
285 // No read-after-write dependency. The narrowing will add false dependency.
290 Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
291 bool is2Addr, ARMCC::CondCodes Pred,
292 bool LiveCPSR, bool &HasCC, bool &CCDead) {
293 if ((is2Addr && Entry.PredCC2 == 0) ||
294 (!is2Addr && Entry.PredCC1 == 0)) {
295 if (Pred == ARMCC::AL) {
296 // Not predicated, must set CPSR.
298 // Original instruction was not setting CPSR, but CPSR is not
299 // currently live anyway. It's ok to set it. The CPSR def is
309 // Predicated, must not set CPSR.
313 } else if ((is2Addr && Entry.PredCC2 == 2) ||
314 (!is2Addr && Entry.PredCC1 == 2)) {
315 /// Old opcode has an optional def of CPSR.
318 // If old opcode does not implicitly define CPSR, then it's not ok since
319 // these new opcodes' CPSR def is not meant to be thrown away. e.g. CMP.
320 if (!HasImplicitCPSRDef(MI->getDesc()))
324 // 16-bit instruction does not set CPSR.
332 static bool VerifyLowRegs(MachineInstr *MI) {
333 unsigned Opc = MI->getOpcode();
334 bool isPCOk = (Opc == ARM::t2LDMIA_RET || Opc == ARM::t2LDMIA ||
335 Opc == ARM::t2LDMDB || Opc == ARM::t2LDMIA_UPD ||
336 Opc == ARM::t2LDMDB_UPD);
337 bool isLROk = (Opc == ARM::t2STMIA_UPD || Opc == ARM::t2STMDB_UPD);
338 bool isSPOk = isPCOk || isLROk;
339 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
340 const MachineOperand &MO = MI->getOperand(i);
341 if (!MO.isReg() || MO.isImplicit())
343 unsigned Reg = MO.getReg();
344 if (Reg == 0 || Reg == ARM::CPSR)
346 if (isPCOk && Reg == ARM::PC)
348 if (isLROk && Reg == ARM::LR)
350 if (Reg == ARM::SP) {
353 if (i == 1 && (Opc == ARM::t2LDRi12 || Opc == ARM::t2STRi12))
354 // Special case for these ldr / str with sp as base register.
357 if (!isARMLowRegister(Reg))
364 Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
365 const ReduceEntry &Entry) {
366 if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
370 bool HasImmOffset = false;
371 bool HasShift = false;
372 bool HasOffReg = true;
373 bool isLdStMul = false;
374 unsigned Opc = Entry.NarrowOpc1;
375 unsigned OpNum = 3; // First 'rest' of operands.
376 uint8_t ImmLimit = Entry.Imm1Limit;
378 switch (Entry.WideOpc) {
380 llvm_unreachable("Unexpected Thumb2 load / store opcode!");
383 if (MI->getOperand(1).getReg() == ARM::SP) {
384 Opc = Entry.NarrowOpc2;
385 ImmLimit = Entry.Imm2Limit;
417 unsigned BaseReg = MI->getOperand(0).getReg();
418 if (!isARMLowRegister(BaseReg) || Entry.WideOpc != ARM::t2LDMIA)
421 // For the non-writeback version (this one), the base register must be
422 // one of the registers being loaded.
424 for (unsigned i = 4; i < MI->getNumOperands(); ++i) {
425 if (MI->getOperand(i).getReg() == BaseReg) {
438 case ARM::t2LDMIA_RET: {
439 unsigned BaseReg = MI->getOperand(1).getReg();
440 if (BaseReg != ARM::SP)
442 Opc = Entry.NarrowOpc2; // tPOP_RET
447 case ARM::t2LDMIA_UPD:
448 case ARM::t2LDMDB_UPD:
449 case ARM::t2STMIA_UPD:
450 case ARM::t2STMDB_UPD: {
453 unsigned BaseReg = MI->getOperand(1).getReg();
454 if (BaseReg == ARM::SP &&
455 (Entry.WideOpc == ARM::t2LDMIA_UPD ||
456 Entry.WideOpc == ARM::t2STMDB_UPD)) {
457 Opc = Entry.NarrowOpc2; // tPOP or tPUSH
459 } else if (!isARMLowRegister(BaseReg) ||
460 (Entry.WideOpc != ARM::t2LDMIA_UPD &&
461 Entry.WideOpc != ARM::t2STMIA_UPD)) {
470 unsigned OffsetReg = 0;
471 bool OffsetKill = false;
473 OffsetReg = MI->getOperand(2).getReg();
474 OffsetKill = MI->getOperand(2).isKill();
476 if (MI->getOperand(3).getImm())
477 // Thumb1 addressing mode doesn't support shift.
481 unsigned OffsetImm = 0;
483 OffsetImm = MI->getOperand(2).getImm();
484 unsigned MaxOffset = ((1 << ImmLimit) - 1) * Scale;
486 if ((OffsetImm & (Scale - 1)) || OffsetImm > MaxOffset)
487 // Make sure the immediate field fits.
491 // Add the 16-bit load / store instruction.
492 DebugLoc dl = MI->getDebugLoc();
493 MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, TII->get(Opc));
495 MIB.addOperand(MI->getOperand(0));
496 MIB.addOperand(MI->getOperand(1));
499 MIB.addImm(OffsetImm / Scale);
501 assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
504 MIB.addReg(OffsetReg, getKillRegState(OffsetKill));
507 // Transfer the rest of operands.
508 for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
509 MIB.addOperand(MI->getOperand(OpNum));
511 // Transfer memoperands.
512 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
514 // Transfer MI flags.
515 MIB.setMIFlags(MI->getFlags());
517 DEBUG(errs() << "Converted 32-bit: " << *MI << " to 16-bit: " << *MIB);
525 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
526 const ReduceEntry &Entry,
527 bool LiveCPSR, bool IsSelfLoop) {
528 unsigned Opc = MI->getOpcode();
529 if (Opc == ARM::t2ADDri) {
530 // If the source register is SP, try to reduce to tADDrSPi, otherwise
531 // it's a normal reduce.
532 if (MI->getOperand(1).getReg() != ARM::SP) {
533 if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
535 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
537 // Try to reduce to tADDrSPi.
538 unsigned Imm = MI->getOperand(2).getImm();
539 // The immediate must be in range, the destination register must be a low
540 // reg, the predicate must be "always" and the condition flags must not
542 if (Imm & 3 || Imm > 1020)
544 if (!isARMLowRegister(MI->getOperand(0).getReg()))
546 if (MI->getOperand(3).getImm() != ARMCC::AL)
548 const MCInstrDesc &MCID = MI->getDesc();
549 if (MCID.hasOptionalDef() &&
550 MI->getOperand(MCID.getNumOperands()-1).getReg() == ARM::CPSR)
553 MachineInstrBuilder MIB = BuildMI(MBB, MI, MI->getDebugLoc(),
554 TII->get(ARM::tADDrSPi))
555 .addOperand(MI->getOperand(0))
556 .addOperand(MI->getOperand(1))
557 .addImm(Imm / 4); // The tADDrSPi has an implied scale by four.
560 // Transfer MI flags.
561 MIB.setMIFlags(MI->getFlags());
563 DEBUG(errs() << "Converted 32-bit: " << *MI << " to 16-bit: " <<*MIB);
570 if (Entry.LowRegs1 && !VerifyLowRegs(MI))
573 if (MI->mayLoad() || MI->mayStore())
574 return ReduceLoadStore(MBB, MI, Entry);
579 case ARM::t2ADDSrr: {
580 unsigned PredReg = 0;
581 if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
584 case ARM::t2ADDSri: {
585 if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
590 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
601 if (MI->getOperand(2).getImm() == 0)
602 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
605 // Can convert only 'pure' immediate operands, not immediates obtained as
606 // globals' addresses.
607 if (MI->getOperand(1).isImm())
608 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
611 // Try to reduce to the lo-reg only version first. Why there are two
612 // versions of the instruction is a mystery.
613 // It would be nice to just have two entries in the master table that
614 // are prioritized, but the table assumes a unique entry for each
615 // source insn opcode. So for now, we hack a local entry record to use.
616 static const ReduceEntry NarrowEntry =
617 { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1,0 };
618 if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, IsSelfLoop))
620 return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
627 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
628 const ReduceEntry &Entry,
629 bool LiveCPSR, bool IsSelfLoop) {
631 if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
634 if (!MinimizeSize && !OptimizeSize && Entry.AvoidMovs &&
635 STI->avoidMOVsShifterOperand())
636 // Don't issue movs with shifter operand for some CPUs unless we
637 // are optimizing / minimizing for size.
640 unsigned Reg0 = MI->getOperand(0).getReg();
641 unsigned Reg1 = MI->getOperand(1).getReg();
642 // t2MUL is "special". The tied source operand is second, not first.
643 if (MI->getOpcode() == ARM::t2MUL) {
644 unsigned Reg2 = MI->getOperand(2).getReg();
645 // Early exit if the regs aren't all low regs.
646 if (!isARMLowRegister(Reg0) || !isARMLowRegister(Reg1)
647 || !isARMLowRegister(Reg2))
650 // If the other operand also isn't the same as the destination, we
654 // Try to commute the operands to make it a 2-address instruction.
655 MachineInstr *CommutedMI = TII->commuteInstruction(MI);
659 } else if (Reg0 != Reg1) {
660 // Try to commute the operands to make it a 2-address instruction.
661 unsigned CommOpIdx1, CommOpIdx2;
662 if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
663 CommOpIdx1 != 1 || MI->getOperand(CommOpIdx2).getReg() != Reg0)
665 MachineInstr *CommutedMI = TII->commuteInstruction(MI);
669 if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
671 if (Entry.Imm2Limit) {
672 unsigned Imm = MI->getOperand(2).getImm();
673 unsigned Limit = (1 << Entry.Imm2Limit) - 1;
677 unsigned Reg2 = MI->getOperand(2).getReg();
678 if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
682 // Check if it's possible / necessary to transfer the predicate.
683 const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc2);
684 unsigned PredReg = 0;
685 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
686 bool SkipPred = false;
687 if (Pred != ARMCC::AL) {
688 if (!NewMCID.isPredicable())
689 // Can't transfer predicate, fail.
692 SkipPred = !NewMCID.isPredicable();
697 const MCInstrDesc &MCID = MI->getDesc();
698 if (MCID.hasOptionalDef()) {
699 unsigned NumOps = MCID.getNumOperands();
700 HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
701 if (HasCC && MI->getOperand(NumOps-1).isDead())
704 if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
707 // Avoid adding a false dependency on partial flag update by some 16-bit
708 // instructions which has the 's' bit set.
709 if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
710 canAddPseudoFlagDep(MI, IsSelfLoop))
713 // Add the 16-bit instruction.
714 DebugLoc dl = MI->getDebugLoc();
715 MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
716 MIB.addOperand(MI->getOperand(0));
717 if (NewMCID.hasOptionalDef()) {
719 AddDefaultT1CC(MIB, CCDead);
724 // Transfer the rest of operands.
725 unsigned NumOps = MCID.getNumOperands();
726 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
727 if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
729 if (SkipPred && MCID.OpInfo[i].isPredicate())
731 MIB.addOperand(MI->getOperand(i));
734 // Transfer MI flags.
735 MIB.setMIFlags(MI->getFlags());
737 DEBUG(errs() << "Converted 32-bit: " << *MI << " to 16-bit: " << *MIB);
745 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
746 const ReduceEntry &Entry,
747 bool LiveCPSR, bool IsSelfLoop) {
748 if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
751 if (!MinimizeSize && !OptimizeSize && Entry.AvoidMovs &&
752 STI->avoidMOVsShifterOperand())
753 // Don't issue movs with shifter operand for some CPUs unless we
754 // are optimizing / minimizing for size.
757 unsigned Limit = ~0U;
759 Limit = (1 << Entry.Imm1Limit) - 1;
761 const MCInstrDesc &MCID = MI->getDesc();
762 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
763 if (MCID.OpInfo[i].isPredicate())
765 const MachineOperand &MO = MI->getOperand(i);
767 unsigned Reg = MO.getReg();
768 if (!Reg || Reg == ARM::CPSR)
770 if (Entry.LowRegs1 && !isARMLowRegister(Reg))
772 } else if (MO.isImm() &&
773 !MCID.OpInfo[i].isPredicate()) {
774 if (((unsigned)MO.getImm()) > Limit)
779 // Check if it's possible / necessary to transfer the predicate.
780 const MCInstrDesc &NewMCID = TII->get(Entry.NarrowOpc1);
781 unsigned PredReg = 0;
782 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
783 bool SkipPred = false;
784 if (Pred != ARMCC::AL) {
785 if (!NewMCID.isPredicable())
786 // Can't transfer predicate, fail.
789 SkipPred = !NewMCID.isPredicable();
794 if (MCID.hasOptionalDef()) {
795 unsigned NumOps = MCID.getNumOperands();
796 HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
797 if (HasCC && MI->getOperand(NumOps-1).isDead())
800 if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
803 // Avoid adding a false dependency on partial flag update by some 16-bit
804 // instructions which has the 's' bit set.
805 if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
806 canAddPseudoFlagDep(MI, IsSelfLoop))
809 // Add the 16-bit instruction.
810 DebugLoc dl = MI->getDebugLoc();
811 MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
812 MIB.addOperand(MI->getOperand(0));
813 if (NewMCID.hasOptionalDef()) {
815 AddDefaultT1CC(MIB, CCDead);
820 // Transfer the rest of operands.
821 unsigned NumOps = MCID.getNumOperands();
822 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
823 if (i < NumOps && MCID.OpInfo[i].isOptionalDef())
825 if ((MCID.getOpcode() == ARM::t2RSBSri ||
826 MCID.getOpcode() == ARM::t2RSBri ||
827 MCID.getOpcode() == ARM::t2SXTB ||
828 MCID.getOpcode() == ARM::t2SXTH ||
829 MCID.getOpcode() == ARM::t2UXTB ||
830 MCID.getOpcode() == ARM::t2UXTH) && i == 2)
831 // Skip the zero immediate operand, it's now implicit.
833 bool isPred = (i < NumOps && MCID.OpInfo[i].isPredicate());
834 if (SkipPred && isPred)
836 const MachineOperand &MO = MI->getOperand(i);
837 if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
838 // Skip implicit def of CPSR. Either it's modeled as an optional
839 // def now or it's already an implicit def on the new instruction.
843 if (!MCID.isPredicable() && NewMCID.isPredicable())
846 // Transfer MI flags.
847 MIB.setMIFlags(MI->getFlags());
849 DEBUG(errs() << "Converted 32-bit: " << *MI << " to 16-bit: " << *MIB);
856 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR, bool &DefCPSR) {
858 for (const MachineOperand &MO : MI.operands()) {
859 if (!MO.isReg() || MO.isUndef() || MO.isUse())
861 if (MO.getReg() != ARM::CPSR)
869 return HasDef || LiveCPSR;
872 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
873 for (const MachineOperand &MO : MI.operands()) {
874 if (!MO.isReg() || MO.isUndef() || MO.isDef())
876 if (MO.getReg() != ARM::CPSR)
878 assert(LiveCPSR && "CPSR liveness tracking is wrong!");
888 bool Thumb2SizeReduce::ReduceMI(MachineBasicBlock &MBB, MachineInstr *MI,
889 bool LiveCPSR, bool IsSelfLoop) {
890 unsigned Opcode = MI->getOpcode();
891 DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
892 if (OPI == ReduceOpcodeMap.end())
894 const ReduceEntry &Entry = ReduceTable[OPI->second];
896 // Don't attempt normal reductions on "special" cases for now.
898 return ReduceSpecial(MBB, MI, Entry, LiveCPSR, IsSelfLoop);
900 // Try to transform to a 16-bit two-address instruction.
901 if (Entry.NarrowOpc2 &&
902 ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
905 // Try to transform to a 16-bit non-two-address instruction.
906 if (Entry.NarrowOpc1 &&
907 ReduceToNarrow(MBB, MI, Entry, LiveCPSR, IsSelfLoop))
913 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
914 bool Modified = false;
916 // Yes, CPSR could be livein.
917 bool LiveCPSR = MBB.isLiveIn(ARM::CPSR);
918 MachineInstr *BundleMI = 0;
921 HighLatencyCPSR = false;
923 // Check predecessors for the latest CPSRDef.
924 for (auto *Pred : MBB.predecessors()) {
925 const MBBInfo &PInfo = BlockInfo[Pred->getNumber()];
926 if (!PInfo.Visited) {
927 // Since blocks are visited in RPO, this must be a back-edge.
930 if (PInfo.HighLatencyCPSR) {
931 HighLatencyCPSR = true;
936 // If this BB loops back to itself, conservatively avoid narrowing the
937 // first instruction that does partial flag update.
938 bool IsSelfLoop = MBB.isSuccessor(&MBB);
939 MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),E = MBB.instr_end();
940 MachineBasicBlock::instr_iterator NextMII;
941 for (; MII != E; MII = NextMII) {
942 NextMII = std::next(MII);
944 MachineInstr *MI = &*MII;
945 if (MI->isBundle()) {
949 if (MI->isDebugValue())
952 LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
954 // Does NextMII belong to the same bundle as MI?
955 bool NextInSameBundle = NextMII != E && NextMII->isBundledWithPred();
957 if (ReduceMI(MBB, MI, LiveCPSR, IsSelfLoop)) {
959 MachineBasicBlock::instr_iterator I = std::prev(NextMII);
961 // Removing and reinserting the first instruction in a bundle will break
962 // up the bundle. Fix the bundling if it was broken.
963 if (NextInSameBundle && !NextMII->isBundledWithPred())
964 NextMII->bundleWithPred();
967 if (!NextInSameBundle && MI->isInsideBundle()) {
968 // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
969 // marker is only on the BUNDLE instruction. Process the BUNDLE
970 // instruction as we finish with the bundled instruction to work around
971 // the inconsistency.
972 if (BundleMI->killsRegister(ARM::CPSR))
974 MachineOperand *MO = BundleMI->findRegisterDefOperand(ARM::CPSR);
975 if (MO && !MO->isDead())
977 MO = BundleMI->findRegisterUseOperand(ARM::CPSR);
978 if (MO && !MO->isKill())
982 bool DefCPSR = false;
983 LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
985 // Calls don't really set CPSR.
987 HighLatencyCPSR = false;
989 } else if (DefCPSR) {
990 // This is the last CPSR defining instruction.
992 HighLatencyCPSR = isHighLatencyCPSR(CPSRDef);
997 MBBInfo &Info = BlockInfo[MBB.getNumber()];
998 Info.HighLatencyCPSR = HighLatencyCPSR;
1003 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
1004 const TargetMachine &TM = MF.getTarget();
1005 TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
1006 STI = &TM.getSubtarget<ARMSubtarget>();
1008 // Optimizing / minimizing size?
1009 AttributeSet FnAttrs = MF.getFunction()->getAttributes();
1010 OptimizeSize = FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1011 Attribute::OptimizeForSize);
1012 MinimizeSize = STI->isMinSize();
1015 BlockInfo.resize(MF.getNumBlockIDs());
1017 // Visit blocks in reverse post-order so LastCPSRDef is known for all
1019 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
1020 bool Modified = false;
1021 for (ReversePostOrderTraversal<MachineFunction*>::rpo_iterator
1022 I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
1023 Modified |= ReduceMBB(**I);
1027 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
1029 FunctionPass *llvm::createThumb2SizeReductionPass() {
1030 return new Thumb2SizeReduce();