LLVM 24.0.0git
RISCVOptWInstrs.cpp
Go to the documentation of this file.
1//===- RISCVOptWInstrs.cpp - MI W instruction optimizations ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===---------------------------------------------------------------------===//
8//
9// This pass does some optimizations for *W instructions at the MI level.
10//
11// First it removes unneeded sext.w instructions. Either because the sign
12// extended bits aren't consumed or because the input was already sign extended
13// by an earlier instruction.
14//
15// Then:
16// 1. Unless explicit disabled or the target prefers instructions with W suffix,
17// it removes the -w suffix from opw instructions whenever all users are
18// dependent only on the lower word of the result of the instruction.
19// The cases handled are:
20// * addw because c.add has a larger register encoding than c.addw.
21// * addiw because it helps reduce test differences between RV32 and RV64
22// w/o being a pessimization.
23// * mulw because c.mulw doesn't exist but c.mul does (w/ zcb)
24// * slliw because c.slliw doesn't exist and c.slli does
25//
26// 2. Or if explicit enabled or the target prefers instructions with W suffix,
27// it adds the W suffix to the instruction whenever all users are dependent
28// only on the lower word of the result of the instruction.
29// The cases handled are:
30// * add/addi/sub/mul.
31// * slli with imm < 32.
32// * ld/lwu.
33//===---------------------------------------------------------------------===//
34
35#include "RISCV.h"
37#include "RISCVSubtarget.h"
38#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/Statistic.h"
42
43using namespace llvm;
44
45#define DEBUG_TYPE "riscv-opt-w-instrs"
46#define RISCV_OPT_W_INSTRS_NAME "RISC-V Optimize W Instructions"
47
48STATISTIC(NumRemovedSExtW, "Number of removed sign-extensions");
49STATISTIC(NumTransformedToWInstrs,
50 "Number of instructions transformed to W-ops");
51STATISTIC(NumTransformedToNonWInstrs,
52 "Number of instructions transformed to non-W-ops");
53
54static cl::opt<bool> DisableSExtWRemoval("riscv-disable-sextw-removal",
55 cl::desc("Disable removal of sext.w"),
56 cl::init(false), cl::Hidden);
57static cl::opt<bool> DisableStripWSuffix("riscv-disable-strip-w-suffix",
58 cl::desc("Disable strip W suffix"),
59 cl::init(false), cl::Hidden);
60
61namespace {
62
63class RISCVOptWInstrsImpl {
64public:
65 bool run(MachineFunction &MF);
66
67private:
68 bool removeSExtWInstrs(MachineFunction &MF, const RISCVInstrInfo &TII,
69 const RISCVSubtarget &ST, MachineRegisterInfo &MRI);
70 bool canonicalizeWSuffixes(MachineFunction &MF, const RISCVInstrInfo &TII,
71 const RISCVSubtarget &ST,
73};
74
75class RISCVOptWInstrsLegacy : public MachineFunctionPass {
76public:
77 static char ID;
78
79 RISCVOptWInstrsLegacy() : MachineFunctionPass(ID) {}
80
81 bool runOnMachineFunction(MachineFunction &MF) override;
82
83 void getAnalysisUsage(AnalysisUsage &AU) const override {
84 AU.setPreservesCFG();
86 }
87
88 StringRef getPassName() const override { return RISCV_OPT_W_INSTRS_NAME; }
89};
90
91} // end anonymous namespace
92
93char RISCVOptWInstrsLegacy::ID = 0;
95 false, false)
96
98 return new RISCVOptWInstrsLegacy();
99}
100
102 unsigned Bits) {
103 const MachineInstr &MI = *UserOp.getParent();
104 unsigned MCOpcode = RISCV::getRVVMCOpcode(MI.getOpcode());
105
106 if (!MCOpcode)
107 return false;
108
109 const MCInstrDesc &MCID = MI.getDesc();
110 const uint64_t TSFlags = MCID.TSFlags;
111 if (!RISCVII::hasSEWOp(TSFlags))
112 return false;
113 assert(RISCVII::hasVLOp(TSFlags));
114 const unsigned Log2SEW = MI.getOperand(RISCVII::getSEWOpNum(MCID)).getImm();
115
116 if (UserOp.getOperandNo() == RISCVII::getVLOpNum(MCID))
117 return false;
118
119 auto NumDemandedBits =
120 RISCV::getVectorLowDemandedScalarBits(MCOpcode, Log2SEW);
121 return NumDemandedBits && Bits >= *NumDemandedBits;
122}
123
124// Checks if all users only demand the lower \p OrigBits of the original
125// instruction's result.
126// TODO: handle multiple interdependent transformations
127static bool hasAllNBitUsers(const MachineInstr &OrigMI,
128 const RISCVSubtarget &ST,
129 const MachineRegisterInfo &MRI, unsigned OrigBits) {
130
133
134 Worklist.emplace_back(&OrigMI, OrigBits);
135
136 while (!Worklist.empty()) {
137 auto P = Worklist.pop_back_val();
138 const MachineInstr *MI = P.first;
139 unsigned Bits = P.second;
140
141 if (!Visited.insert(P).second)
142 continue;
143
144 // Only handle instructions with one def.
145 if (MI->getNumExplicitDefs() != 1)
146 return false;
147
148 Register DestReg = MI->getOperand(0).getReg();
149 if (!DestReg.isVirtual())
150 return false;
151
152 for (auto &UserOp : MRI.use_nodbg_operands(DestReg)) {
153 const MachineInstr *UserMI = UserOp.getParent();
154 unsigned OpIdx = UserOp.getOperandNo();
155
156 switch (UserMI->getOpcode()) {
157 default:
158 if (vectorPseudoHasAllNBitUsers(UserOp, Bits))
159 break;
160 return false;
161
162 case RISCV::ADDIW:
163 case RISCV::ADDW:
164 case RISCV::DIVUW:
165 case RISCV::DIVW:
166 case RISCV::MULW:
167 case RISCV::REMUW:
168 case RISCV::REMW:
169 case RISCV::SLLW:
170 case RISCV::SRAIW:
171 case RISCV::SRAW:
172 case RISCV::SRLIW:
173 case RISCV::SRLW:
174 case RISCV::SUBW:
175 case RISCV::ROLW:
176 case RISCV::RORW:
177 case RISCV::RORIW:
178 case RISCV::CLSW:
179 case RISCV::CLZW:
180 case RISCV::CTZW:
181 case RISCV::CPOPW:
182 case RISCV::SLLI_UW:
183 case RISCV::ABSW:
184 case RISCV::FMV_W_X:
185 case RISCV::FCVT_H_W:
186 case RISCV::FCVT_H_W_INX:
187 case RISCV::FCVT_H_WU:
188 case RISCV::FCVT_H_WU_INX:
189 case RISCV::FCVT_S_W:
190 case RISCV::FCVT_S_W_INX:
191 case RISCV::FCVT_S_WU:
192 case RISCV::FCVT_S_WU_INX:
193 case RISCV::FCVT_D_W:
194 case RISCV::FCVT_D_W_INX:
195 case RISCV::FCVT_D_WU:
196 case RISCV::FCVT_D_WU_INX:
197 if (Bits >= 32)
198 break;
199 return false;
200
201 case RISCV::SEXT_B:
202 case RISCV::PACKH:
203 if (Bits >= 8)
204 break;
205 return false;
206 case RISCV::SEXT_H:
207 case RISCV::FMV_H_X:
208 case RISCV::ZEXT_H_RV32:
209 case RISCV::ZEXT_H_RV64:
210 case RISCV::PACKW:
211 if (Bits >= 16)
212 break;
213 return false;
214
215 case RISCV::PACK:
216 if (Bits >= (ST.getXLen() / 2))
217 break;
218 return false;
219
220 case RISCV::SRLI: {
221 // If we are shifting right by less than Bits, and users don't demand
222 // any bits that were shifted into [Bits-1:0], then we can consider this
223 // as an N-Bit user.
224 unsigned ShAmt = UserMI->getOperand(2).getImm();
225 if (Bits > ShAmt) {
226 Worklist.emplace_back(UserMI, Bits - ShAmt);
227 break;
228 }
229 return false;
230 }
231
232 // these overwrite higher input bits, otherwise the lower word of output
233 // depends only on the lower word of input. So check their uses read W.
234 case RISCV::SLLI: {
235 unsigned ShAmt = UserMI->getOperand(2).getImm();
236 if (Bits >= (ST.getXLen() - ShAmt))
237 break;
238 Worklist.emplace_back(UserMI, Bits + ShAmt);
239 break;
240 }
241 case RISCV::SLLIW: {
242 unsigned ShAmt = UserMI->getOperand(2).getImm();
243 if (Bits >= 32 - ShAmt)
244 break;
245 Worklist.emplace_back(UserMI, Bits + ShAmt);
246 break;
247 }
248
249 case RISCV::ANDI: {
250 uint64_t Imm = UserMI->getOperand(2).getImm();
251 if (Bits >= (unsigned)llvm::bit_width(Imm))
252 break;
253 Worklist.emplace_back(UserMI, Bits);
254 break;
255 }
256 case RISCV::ORI: {
257 uint64_t Imm = UserMI->getOperand(2).getImm();
258 if (Bits >= (unsigned)llvm::bit_width<uint64_t>(~Imm))
259 break;
260 Worklist.emplace_back(UserMI, Bits);
261 break;
262 }
263
264 case RISCV::SLL:
265 case RISCV::BSET:
266 case RISCV::BCLR:
267 case RISCV::BINV:
268 // Operand 2 is the shift amount which uses log2(xlen) bits.
269 if (OpIdx == 2) {
270 if (Bits >= Log2_32(ST.getXLen()))
271 break;
272 return false;
273 }
274 Worklist.emplace_back(UserMI, Bits);
275 break;
276
277 case RISCV::SRA:
278 case RISCV::SRL:
279 case RISCV::ROL:
280 case RISCV::ROR:
281 // Operand 2 is the shift amount which uses 6 bits.
282 if (OpIdx == 2 && Bits >= Log2_32(ST.getXLen()))
283 break;
284 return false;
285
286 case RISCV::ADD_UW:
287 case RISCV::SH1ADD_UW:
288 case RISCV::SH2ADD_UW:
289 case RISCV::SH3ADD_UW:
290 // Operand 1 is implicitly zero extended.
291 if (OpIdx == 1 && Bits >= 32)
292 break;
293 Worklist.emplace_back(UserMI, Bits);
294 break;
295
296 case RISCV::BEXTI:
297 if (UserMI->getOperand(2).getImm() >= Bits)
298 return false;
299 break;
300
301 case RISCV::SB:
302 // The first argument is the value to store.
303 if (OpIdx == 0 && Bits >= 8)
304 break;
305 return false;
306 case RISCV::SH:
307 // The first argument is the value to store.
308 if (OpIdx == 0 && Bits >= 16)
309 break;
310 return false;
311 case RISCV::SW:
312 // The first argument is the value to store.
313 if (OpIdx == 0 && Bits >= 32)
314 break;
315 return false;
316
317 // For these, lower word of output in these operations, depends only on
318 // the lower word of input. So, we check all uses only read lower word.
319 case RISCV::COPY:
320 case RISCV::PHI:
321
322 case RISCV::ADD:
323 case RISCV::ADDI:
324 case RISCV::AND:
325 case RISCV::MUL:
326 case RISCV::OR:
327 case RISCV::SUB:
328 case RISCV::XOR:
329 case RISCV::XORI:
330
331 case RISCV::ANDN:
332 case RISCV::CLMUL:
333 case RISCV::ORN:
334 case RISCV::SH1ADD:
335 case RISCV::SH2ADD:
336 case RISCV::SH3ADD:
337 case RISCV::XNOR:
338 case RISCV::BSETI:
339 case RISCV::BCLRI:
340 case RISCV::BINVI:
341 Worklist.emplace_back(UserMI, Bits);
342 break;
343
344 case RISCV::BREV8:
345 case RISCV::ORC_B:
346 // BREV8 and ORC_B work on bytes. Round Bits down to the nearest byte.
347 Worklist.emplace_back(UserMI, alignDown(Bits, 8));
348 break;
349
350 case RISCV::PseudoCCMOVGPR:
351 case RISCV::PseudoCCMOVGPRNoX0:
352 // Either operand 1 or operand 2 is returned by this instruction. If
353 // only the lower word of the result is used, then only the lower word
354 // of operand 1 and 2 is used.
355 if (OpIdx != 1 && OpIdx != 2)
356 return false;
357 Worklist.emplace_back(UserMI, Bits);
358 break;
359
360 case RISCV::CZERO_EQZ:
361 case RISCV::CZERO_NEZ:
362 case RISCV::VT_MASKC:
363 case RISCV::VT_MASKCN:
364 if (OpIdx != 1)
365 return false;
366 Worklist.emplace_back(UserMI, Bits);
367 break;
368 case RISCV::TH_EXT:
369 case RISCV::TH_EXTU:
370 unsigned Msb = UserMI->getOperand(2).getImm();
371 unsigned Lsb = UserMI->getOperand(3).getImm();
372 // Behavior of Msb < Lsb is not well documented.
373 if (Msb >= Lsb && Bits > Msb)
374 break;
375 return false;
376 }
377 }
378 }
379
380 return true;
381}
382
383static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST,
384 const MachineRegisterInfo &MRI) {
385 return hasAllNBitUsers(OrigMI, ST, MRI, 32);
386}
387
388// This function returns true if the machine instruction always outputs a value
389// where bits 63:32 match bit 31.
390static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo) {
391 uint64_t TSFlags = MI.getDesc().TSFlags;
392
393 // Instructions that can be determined from opcode are marked in tablegen.
395 return true;
396
397 // Special cases that require checking operands.
398 switch (MI.getOpcode()) {
399 // shifting right sufficiently makes the value 32-bit sign-extended
400 case RISCV::SRAI:
401 return MI.getOperand(2).getImm() >= 32;
402 case RISCV::SRLI:
403 return MI.getOperand(2).getImm() > 32;
404 // The LI pattern ADDI rd, X0, imm is sign extended.
405 case RISCV::ADDI:
406 return MI.getOperand(1).isReg() && MI.getOperand(1).getReg() == RISCV::X0;
407 // An ANDI with an 11 bit immediate will zero bits 63:11.
408 case RISCV::ANDI:
409 return isUInt<11>(MI.getOperand(2).getImm());
410 // An ORI with an >11 bit immediate (negative 12-bit) will set bits 63:11.
411 case RISCV::ORI:
412 return !isUInt<11>(MI.getOperand(2).getImm());
413 // A bseti with X0 is sign extended if the immediate is less than 31.
414 case RISCV::BSETI:
415 return MI.getOperand(2).getImm() < 31 &&
416 MI.getOperand(1).getReg() == RISCV::X0;
417 // Copying from X0 produces zero.
418 case RISCV::COPY:
419 return MI.getOperand(1).getReg() == RISCV::X0;
420 // Ignore the scratch register destination.
421 case RISCV::PseudoAtomicLoadNand32:
422 return OpNo == 0;
423 case RISCV::PseudoVMV_X_S: {
424 // vmv.x.s has at least 33 sign bits if log2(sew) <= 5.
425 int64_t Log2SEW = MI.getOperand(2).getImm();
426 assert(Log2SEW >= 3 && Log2SEW <= 6 && "Unexpected Log2SEW");
427 return Log2SEW <= 5;
428 }
429 case RISCV::TH_EXT: {
430 unsigned Msb = MI.getOperand(2).getImm();
431 unsigned Lsb = MI.getOperand(3).getImm();
432 return Msb >= Lsb && (Msb - Lsb + 1) <= 32;
433 }
434 case RISCV::TH_EXTU: {
435 unsigned Msb = MI.getOperand(2).getImm();
436 unsigned Lsb = MI.getOperand(3).getImm();
437 return Msb >= Lsb && (Msb - Lsb + 1) < 32;
438 }
439 case RISCV::SATI_RV64:
440 // Saturates to signed range [-2^(imm-1), 2^(imm-1)-1].
441 // If imm <= 32, result fits in 32-bit signed range, thus sign-extended.
442 return MI.getOperand(2).getImm() <= 32;
443 case RISCV::USATI_RV64:
444 // Saturates to unsigned range [0, 2^imm-1].
445 // If imm < 32, result has bit 31 clear, thus sign-extended.
446 return MI.getOperand(2).getImm() < 32;
447 }
448
449 return false;
450}
451
452static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST,
453 const MachineRegisterInfo &MRI,
455 SmallSet<Register, 4> Visited;
457
458 auto AddRegToWorkList = [&](Register SrcReg) {
459 if (!SrcReg.isVirtual())
460 return false;
461 Worklist.push_back(SrcReg);
462 return true;
463 };
464
465 if (!AddRegToWorkList(SrcReg))
466 return false;
467
468 while (!Worklist.empty()) {
469 Register Reg = Worklist.pop_back_val();
470
471 // If we already visited this register, we don't need to check it again.
472 if (!Visited.insert(Reg).second)
473 continue;
474
476 if (!MI)
477 continue;
478
479 int OpNo = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
480 assert(OpNo != -1 && "Couldn't find register");
481
482 // If this is a sign extending operation we don't need to look any further.
483 if (isSignExtendingOpW(*MI, OpNo))
484 continue;
485
486 // Is this an instruction that propagates sign extend?
487 switch (MI->getOpcode()) {
488 default:
489 // Unknown opcode, give up.
490 return false;
491 case RISCV::COPY: {
492 const MachineFunction *MF = MI->getMF();
493 const RISCVMachineFunctionInfo *RVFI =
495
496 // If this is the entry block and the register is livein, see if we know
497 // it is sign extended.
498 if (MI->getParent() == &MF->front()) {
499 Register VReg = MI->getOperand(0).getReg();
500 if (MF->getRegInfo().isLiveIn(VReg) && RVFI->isSExt32Register(VReg))
501 continue;
502 }
503
504 Register CopySrcReg = MI->getOperand(1).getReg();
505 if (CopySrcReg == RISCV::X10) {
506 // For a method return value, we check the ZExt/SExt flags in attribute.
507 // We assume the following code sequence for method call.
508 // PseudoCALL @bar, ...
509 // ADJCALLSTACKUP 0, 0, implicit-def dead $x2, implicit $x2
510 // %0:gpr = COPY $x10
511 //
512 // We use the PseudoCall to look up the IR function being called to find
513 // its return attributes.
514 const MachineBasicBlock *MBB = MI->getParent();
515 auto II = MI->getIterator();
516 if (II == MBB->instr_begin() ||
517 (--II)->getOpcode() != RISCV::ADJCALLSTACKUP)
518 return false;
519
520 const MachineInstr &CallMI = *(--II);
521 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
522 return false;
523
524 auto *CalleeFn =
526 if (!CalleeFn)
527 return false;
528
529 auto *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
530 if (!IntTy)
531 return false;
532
533 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
534 unsigned BitWidth = IntTy->getBitWidth();
535 if ((BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
536 (BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
537 continue;
538 }
539
540 if (!AddRegToWorkList(CopySrcReg))
541 return false;
542
543 break;
544 }
545
546 // For these, we just need to check if the 1st operand is sign extended.
547 case RISCV::BCLRI:
548 case RISCV::BINVI:
549 case RISCV::BSETI:
550 if (MI->getOperand(2).getImm() >= 31)
551 return false;
552 [[fallthrough]];
553 case RISCV::REM:
554 case RISCV::ANDI:
555 case RISCV::ORI:
556 case RISCV::XORI:
557 case RISCV::SRAI:
558 // |Remainder| is always <= |Dividend|. If D is 32-bit, then so is R.
559 // DIV doesn't work because of the edge case 0xf..f 8000 0000 / (long)-1
560 // Logical operations use a sign extended 12-bit immediate.
561 // Arithmetic shift right can only increase the number of sign bits.
562 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
563 return false;
564
565 break;
566 case RISCV::PseudoCCADDW:
567 case RISCV::PseudoCCADDIW:
568 case RISCV::PseudoCCSUBW:
569 case RISCV::PseudoCCSLLW:
570 case RISCV::PseudoCCSRLW:
571 case RISCV::PseudoCCSRAW:
572 case RISCV::PseudoCCSLLIW:
573 case RISCV::PseudoCCSRLIW:
574 case RISCV::PseudoCCSRAIW:
575 // Returns operand 1 or an ADDW/SUBW/etc. of operands 2 and 3. We only
576 // need to check if operand 1 is sign extended.
577 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
578 return false;
579 break;
580 case RISCV::REMU:
581 case RISCV::AND:
582 case RISCV::OR:
583 case RISCV::XOR:
584 case RISCV::ANDN:
585 case RISCV::ORN:
586 case RISCV::XNOR:
587 case RISCV::MAX:
588 case RISCV::MAXU:
589 case RISCV::MIN:
590 case RISCV::MINU:
591 case RISCV::PseudoCCMOVGPR:
592 case RISCV::PseudoCCMOVGPRNoX0:
593 case RISCV::PseudoCCAND:
594 case RISCV::PseudoCCOR:
595 case RISCV::PseudoCCXOR:
596 case RISCV::PseudoCCANDN:
597 case RISCV::PseudoCCORN:
598 case RISCV::PseudoCCXNOR:
599 case RISCV::PHI:
600 case RISCV::MERGE:
601 case RISCV::MVM:
602 case RISCV::MVMN: {
603 // If all incoming values are sign-extended, the output of AND, OR, XOR,
604 // MIN, MAX, PHI, or bitwise merge instructions is also sign-extended.
605
606 // The input registers for PHI are operand 1, 3, ...
607 // The input registers for PseudoCCMOVGPR(NoX0) are 1 and 2.
608 // The input registers for PseudoCCAND/OR/XOR are 1, 2, and 3.
609 // The input registers for MERGE/MVM/MVMN are 1, 2, and 3.
610 // The input registers for others are operand 1 and 2.
611 unsigned B = 1, E = 3, D = 1;
612 switch (MI->getOpcode()) {
613 case RISCV::PHI:
614 E = MI->getNumOperands();
615 D = 2;
616 break;
617 case RISCV::PseudoCCMOVGPR:
618 case RISCV::PseudoCCMOVGPRNoX0:
619 B = 1;
620 E = 3;
621 break;
622 case RISCV::PseudoCCAND:
623 case RISCV::PseudoCCOR:
624 case RISCV::PseudoCCXOR:
625 case RISCV::PseudoCCANDN:
626 case RISCV::PseudoCCORN:
627 case RISCV::PseudoCCXNOR:
628 B = 1;
629 E = 4;
630 break;
631 case RISCV::MERGE:
632 case RISCV::MVM:
633 case RISCV::MVMN:
634 B = 1;
635 E = 4;
636 break;
637 }
638
639 for (unsigned I = B; I != E; I += D) {
640 if (!MI->getOperand(I).isReg())
641 return false;
642
643 if (!AddRegToWorkList(MI->getOperand(I).getReg()))
644 return false;
645 }
646
647 break;
648 }
649
650 case RISCV::CZERO_EQZ:
651 case RISCV::CZERO_NEZ:
652 case RISCV::VT_MASKC:
653 case RISCV::VT_MASKCN:
654 // Instructions return zero or operand 1. Result is sign extended if
655 // operand 1 is sign extended.
656 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
657 return false;
658 break;
659
660 case RISCV::ADDI: {
661 if (MI->getOperand(1).isReg() && MI->getOperand(1).getReg().isVirtual()) {
662 if (MachineInstr *SrcMI = MRI.getVRegDef(MI->getOperand(1).getReg())) {
663 if (SrcMI->getOpcode() == RISCV::LUI &&
664 SrcMI->getOperand(1).isImm()) {
665 uint64_t Imm = SrcMI->getOperand(1).getImm();
666 Imm = SignExtend64<32>(Imm << 12);
667 Imm += (uint64_t)MI->getOperand(2).getImm();
668 if (isInt<32>(Imm))
669 continue;
670 }
671 }
672 }
673
674 if (hasAllWUsers(*MI, ST, MRI)) {
675 FixableDef.insert(MI);
676 break;
677 }
678 return false;
679 }
680
681 case RISCV::LD:
682 case RISCV::LXD: {
683 if (MI->hasOneMemOperand() && !(*MI->memoperands_begin())->isVolatile() &&
684 hasAllWUsers(*MI, ST, MRI)) {
685 FixableDef.insert(MI);
686 break;
687 }
688 return false;
689 }
690
691 // With these opcode, we can "fix" them with the W-version
692 // if we know all users of the result only rely on bits 31:0
693 case RISCV::SLLI:
694 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits
695 if (MI->getOperand(2).getImm() >= 32)
696 return false;
697 [[fallthrough]];
698 case RISCV::ADD:
699 case RISCV::LWU:
700 case RISCV::LXWU:
701 case RISCV::MUL:
702 case RISCV::SUB:
703 if (hasAllWUsers(*MI, ST, MRI)) {
704 FixableDef.insert(MI);
705 break;
706 }
707 return false;
708 }
709 }
710
711 // If we get here, then every node we visited produces a sign extended value
712 // or propagated sign extended values. So the result must be sign extended.
713 return true;
714}
715
716static unsigned getWOp(unsigned Opcode) {
717 switch (Opcode) {
718 case RISCV::ADDI:
719 return RISCV::ADDIW;
720 case RISCV::ADD:
721 return RISCV::ADDW;
722 case RISCV::LD:
723 case RISCV::LWU:
724 return RISCV::LW;
725 case RISCV::LXD:
726 case RISCV::LXWU:
727 return RISCV::LXW;
728 case RISCV::MUL:
729 return RISCV::MULW;
730 case RISCV::SLLI:
731 return RISCV::SLLIW;
732 case RISCV::SUB:
733 return RISCV::SUBW;
734 default:
735 llvm_unreachable("Unexpected opcode for replacement with W variant");
736 }
737}
738
739bool RISCVOptWInstrsImpl::removeSExtWInstrs(MachineFunction &MF,
740 const RISCVInstrInfo &TII,
741 const RISCVSubtarget &ST,
742 MachineRegisterInfo &MRI) {
744 return false;
745
746 bool MadeChange = false;
747 for (MachineBasicBlock &MBB : MF) {
748 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
749 // We're looking for the sext.w pattern ADDIW rd, rs1, 0.
750 if (!RISCVInstrInfo::isSEXT_W(MI))
751 continue;
752
753 Register SrcReg = MI.getOperand(1).getReg();
754
755 SmallPtrSet<MachineInstr *, 4> FixableDefs;
756
757 // If all users only use the lower bits, this sext.w is redundant.
758 // Or if all definitions reaching MI sign-extend their output,
759 // then sext.w is redundant.
760 if (!hasAllWUsers(MI, ST, MRI) &&
761 !isSignExtendedW(SrcReg, ST, MRI, FixableDefs))
762 continue;
763
764 Register DstReg = MI.getOperand(0).getReg();
765 if (!MRI.constrainRegClass(SrcReg, MRI.getRegClass(DstReg)))
766 continue;
767
768 // Convert Fixable instructions to their W versions.
769 for (MachineInstr *Fixable : FixableDefs) {
770 LLVM_DEBUG(dbgs() << "Replacing " << *Fixable);
771 Fixable->setDesc(TII.get(getWOp(Fixable->getOpcode())));
772 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
773 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
774 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
775 LLVM_DEBUG(dbgs() << " with " << *Fixable);
776 ++NumTransformedToWInstrs;
777 }
778
779 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
780 MRI.replaceRegWith(DstReg, SrcReg);
781 MRI.clearKillFlags(SrcReg);
782 MI.eraseFromParent();
783 ++NumRemovedSExtW;
784 MadeChange = true;
785 }
786 }
787
788 return MadeChange;
789}
790
791// Strips or adds W suffixes to eligible instructions depending on the
792// subtarget preferences.
793bool RISCVOptWInstrsImpl::canonicalizeWSuffixes(MachineFunction &MF,
794 const RISCVInstrInfo &TII,
795 const RISCVSubtarget &ST,
796 MachineRegisterInfo &MRI) {
797 bool ShouldStripW = !(DisableStripWSuffix || ST.preferWInst());
798 bool ShouldPreferW = ST.preferWInst();
799 bool MadeChange = false;
800
801 for (MachineBasicBlock &MBB : MF) {
802 for (MachineInstr &MI : MBB) {
803 std::optional<unsigned> WOpc;
804 std::optional<unsigned> NonWOpc;
805 unsigned OrigOpc = MI.getOpcode();
806 switch (OrigOpc) {
807 default:
808 continue;
809 case RISCV::ADDW:
810 NonWOpc = RISCV::ADD;
811 break;
812 case RISCV::ADDIW:
813 NonWOpc = RISCV::ADDI;
814 break;
815 case RISCV::MULW:
816 NonWOpc = RISCV::MUL;
817 break;
818 case RISCV::SLLIW:
819 NonWOpc = RISCV::SLLI;
820 break;
821 case RISCV::SUBW:
822 NonWOpc = RISCV::SUB;
823 break;
824 case RISCV::ADD:
825 WOpc = RISCV::ADDW;
826 break;
827 case RISCV::ADDI:
828 WOpc = RISCV::ADDIW;
829 break;
830 case RISCV::SUB:
831 WOpc = RISCV::SUBW;
832 break;
833 case RISCV::MUL:
834 WOpc = RISCV::MULW;
835 break;
836 case RISCV::SLLI:
837 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits.
838 if (MI.getOperand(2).getImm() >= 32)
839 continue;
840 WOpc = RISCV::SLLIW;
841 break;
842 case RISCV::LD:
843 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
844 continue;
845 WOpc = RISCV::LW;
846 break;
847 case RISCV::LWU:
848 WOpc = RISCV::LW;
849 break;
850 case RISCV::LXD:
851 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
852 continue;
853 WOpc = RISCV::LXW;
854 break;
855 case RISCV::LXWU:
856 WOpc = RISCV::LXW;
857 break;
858 }
859
860 if (ShouldStripW && NonWOpc.has_value() && hasAllWUsers(MI, ST, MRI)) {
861 LLVM_DEBUG(dbgs() << "Replacing " << MI);
862 MI.setDesc(TII.get(NonWOpc.value()));
863 LLVM_DEBUG(dbgs() << " with " << MI);
864 ++NumTransformedToNonWInstrs;
865 MadeChange = true;
866 continue;
867 }
868 // LWU is always converted to LW when possible as 1) LW is compressible
869 // and 2) it helps minimise differences vs RV32.
870 if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
871 hasAllWUsers(MI, ST, MRI)) {
872 LLVM_DEBUG(dbgs() << "Replacing " << MI);
873 MI.setDesc(TII.get(WOpc.value()));
874 MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
875 MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
876 MI.clearFlag(MachineInstr::MIFlag::IsExact);
877 LLVM_DEBUG(dbgs() << " with " << MI);
878 ++NumTransformedToWInstrs;
879 MadeChange = true;
880 continue;
881 }
882 }
883 }
884 return MadeChange;
885}
886
887bool RISCVOptWInstrsImpl::run(MachineFunction &MF) {
888 MachineRegisterInfo &MRI = MF.getRegInfo();
889 const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
890 const RISCVInstrInfo &TII = *ST.getInstrInfo();
891
892 if (!ST.is64Bit())
893 return false;
894
895 bool MadeChange = false;
896 MadeChange |= removeSExtWInstrs(MF, TII, ST, MRI);
897 MadeChange |= canonicalizeWSuffixes(MF, TII, ST, MRI);
898 return MadeChange;
899}
900
901bool RISCVOptWInstrsLegacy::runOnMachineFunction(MachineFunction &MF) {
902 if (skipFunction(MF.getFunction()))
903 return false;
904 return RISCVOptWInstrsImpl().run(MF);
905}
906
907PreservedAnalyses
910 bool Changed = RISCVOptWInstrsImpl().run(MF);
911 if (!Changed)
912 return PreservedAnalyses::all();
913
916 return PA;
917}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock & MBB
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static cl::opt< bool > DisableSExtWRemoval("loongarch-disable-sextw-removal", cl::desc("Disable removal of sign-extend insn"), cl::init(false), cl::Hidden)
static bool hasAllWUsers(const MachineInstr &OrigMI, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendedW(Register SrcReg, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static unsigned getWOp(unsigned Opcode)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo)
static cl::opt< bool > DisableStripWSuffix("riscv-disable-strip-w-suffix", cl::desc("Disable strip W suffix"), cl::init(false), cl::Hidden)
static bool hasAllNBitUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
#define RISCV_OPT_W_INSTRS_NAME
static bool vectorPseudoHasAllNBitUsers(const MachineOperand &UserOp, unsigned Bits)
static cl::opt< bool > DisableSExtWRemoval("riscv-disable-sextw-removal", cl::desc("Disable removal of sext.w"), cl::init(false), cl::Hidden)
static unsigned getWOp(unsigned Opcode)
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:407
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Describe properties that are true of each instruction in the target description file.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
const GlobalValue * getGlobal() const
int64_t getImm() const
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
LLVM_ABI bool isLiveIn(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getVLOpNum(const MCInstrDesc &Desc)
static bool hasVLOp(uint64_t TSFlags)
static unsigned getSEWOpNum(const MCInstrDesc &Desc)
static bool hasSEWOp(uint64_t TSFlags)
unsigned getRVVMCOpcode(unsigned RVVPseudoOpcode)
std::optional< unsigned > getVectorLowDemandedScalarBits(unsigned Opcode, unsigned Log2SEW)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionPass * createRISCVOptWInstrsLegacyPass()
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:541
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
constexpr unsigned BitWidth
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567