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> EnableSExtWRemoval("riscv-sextw-removal",
55 cl::desc("Enable removal of sext.w"),
56 cl::init(true), cl::Hidden);
57static cl::opt<bool> EnableStripWSuffix("riscv-strip-w-suffix",
58 cl::desc("Enable strip W suffix"),
59 cl::init(true), 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
101static bool vectorPseudoHasAllNBitUsers(const MachineInstr &MI, unsigned OpIdx,
102 unsigned Bits) {
103 unsigned MCOpcode = RISCV::getRVVMCOpcode(MI.getOpcode());
104
105 if (!MCOpcode)
106 return false;
107
108 const MCInstrDesc &MCID = MI.getDesc();
109 const uint64_t TSFlags = MCID.TSFlags;
110 if (!RISCVII::hasSEWOp(TSFlags))
111 return false;
112 assert(RISCVII::hasVLOp(TSFlags));
113 const unsigned Log2SEW = MI.getOperand(RISCVII::getSEWOpNum(MCID)).getImm();
114
115 if (OpIdx == RISCVII::getVLOpNum(MCID))
116 return false;
117
118 auto NumDemandedBits =
119 RISCV::getVectorLowDemandedScalarBits(MCOpcode, Log2SEW);
120 return NumDemandedBits && Bits >= *NumDemandedBits;
121}
122
123// Checks if all users only demand the lower \p OrigBits of the original
124// instruction's result.
125// TODO: handle multiple interdependent transformations
126static bool hasAllNBitUsers(const MachineInstr &OrigMI,
127 const RISCVSubtarget &ST,
128 const MachineRegisterInfo &MRI, unsigned OrigBits) {
129
132
133 Worklist.emplace_back(&OrigMI, OrigBits);
134
135 while (!Worklist.empty()) {
136 auto P = Worklist.pop_back_val();
137 const MachineInstr *MI = P.first;
138 unsigned Bits = P.second;
139
140 if (!Visited.insert(P).second)
141 continue;
142
143 // Only handle instructions with one def.
144 if (MI->getNumExplicitDefs() != 1)
145 return false;
146
147 Register DestReg = MI->getOperand(0).getReg();
148 if (!DestReg.isVirtual())
149 return false;
150
151 for (auto &UserOp : MRI.use_nodbg_operands(DestReg)) {
152 const MachineInstr *UserMI = UserOp.getParent();
153 unsigned OpIdx = UserOp.getOperandNo();
154
155 switch (UserMI->getOpcode()) {
156 default:
157 if (vectorPseudoHasAllNBitUsers(*UserMI, OpIdx, Bits))
158 break;
159 return false;
160
161 case RISCV::ADDIW:
162 case RISCV::ADDW:
163 case RISCV::DIVUW:
164 case RISCV::DIVW:
165 case RISCV::MULW:
166 case RISCV::REMUW:
167 case RISCV::REMW:
168 case RISCV::SLLW:
169 case RISCV::SRAIW:
170 case RISCV::SRAW:
171 case RISCV::SRLIW:
172 case RISCV::SRLW:
173 case RISCV::SUBW:
174 case RISCV::ROLW:
175 case RISCV::RORW:
176 case RISCV::RORIW:
177 case RISCV::CLSW:
178 case RISCV::CLZW:
179 case RISCV::CTZW:
180 case RISCV::CPOPW:
181 case RISCV::SLLI_UW:
182 case RISCV::ABSW:
183 case RISCV::FMV_W_X:
184 case RISCV::FCVT_H_W:
185 case RISCV::FCVT_H_W_INX:
186 case RISCV::FCVT_H_WU:
187 case RISCV::FCVT_H_WU_INX:
188 case RISCV::FCVT_S_W:
189 case RISCV::FCVT_S_W_INX:
190 case RISCV::FCVT_S_WU:
191 case RISCV::FCVT_S_WU_INX:
192 case RISCV::FCVT_D_W:
193 case RISCV::FCVT_D_W_INX:
194 case RISCV::FCVT_D_WU:
195 case RISCV::FCVT_D_WU_INX:
196 if (Bits >= 32)
197 break;
198 return false;
199
200 case RISCV::SEXT_B:
201 case RISCV::PACKH:
202 if (Bits >= 8)
203 break;
204 return false;
205 case RISCV::SEXT_H:
206 case RISCV::FMV_H_X:
207 case RISCV::ZEXT_H_RV32:
208 case RISCV::ZEXT_H_RV64:
209 case RISCV::PACKW:
210 if (Bits >= 16)
211 break;
212 return false;
213
214 case RISCV::PACK:
215 if (Bits >= (ST.getXLen() / 2))
216 break;
217 return false;
218
219 case RISCV::SRLI: {
220 // If we are shifting right by less than Bits, and users don't demand
221 // any bits that were shifted into [Bits-1:0], then we can consider this
222 // as an N-Bit user.
223 unsigned ShAmt = UserMI->getOperand(2).getImm();
224 if (Bits > ShAmt) {
225 Worklist.emplace_back(UserMI, Bits - ShAmt);
226 break;
227 }
228 return false;
229 }
230
231 // these overwrite higher input bits, otherwise the lower word of output
232 // depends only on the lower word of input. So check their uses read W.
233 case RISCV::SLLI: {
234 unsigned ShAmt = UserMI->getOperand(2).getImm();
235 if (Bits >= (ST.getXLen() - ShAmt))
236 break;
237 Worklist.emplace_back(UserMI, Bits + ShAmt);
238 break;
239 }
240 case RISCV::SLLIW: {
241 unsigned ShAmt = UserMI->getOperand(2).getImm();
242 if (Bits >= 32 - ShAmt)
243 break;
244 Worklist.emplace_back(UserMI, Bits + ShAmt);
245 break;
246 }
247
248 case RISCV::ANDI: {
249 uint64_t Imm = UserMI->getOperand(2).getImm();
250 if (Bits >= (unsigned)llvm::bit_width(Imm))
251 break;
252 Worklist.emplace_back(UserMI, Bits);
253 break;
254 }
255 case RISCV::ORI: {
256 uint64_t Imm = UserMI->getOperand(2).getImm();
257 if (Bits >= (unsigned)llvm::bit_width<uint64_t>(~Imm))
258 break;
259 Worklist.emplace_back(UserMI, Bits);
260 break;
261 }
262
263 case RISCV::SLL:
264 case RISCV::BSET:
265 case RISCV::BCLR:
266 case RISCV::BINV:
267 // Operand 2 is the shift amount which uses log2(xlen) bits.
268 if (OpIdx == 2) {
269 if (Bits >= Log2_32(ST.getXLen()))
270 break;
271 return false;
272 }
273 Worklist.emplace_back(UserMI, Bits);
274 break;
275
276 case RISCV::SRA:
277 case RISCV::SRL:
278 case RISCV::ROL:
279 case RISCV::ROR:
280 case RISCV::BEXT:
281 // Operand 2 is the shift amount or bit index, using log2(XLEN) 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 if (OpIdx != 1)
363 return false;
364 Worklist.emplace_back(UserMI, Bits);
365 break;
366 case RISCV::TH_EXT:
367 case RISCV::TH_EXTU:
368 unsigned Msb = UserMI->getOperand(2).getImm();
369 unsigned Lsb = UserMI->getOperand(3).getImm();
370 // Behavior of Msb < Lsb is not well documented.
371 if (Msb >= Lsb && Bits > Msb)
372 break;
373 return false;
374 }
375 }
376 }
377
378 return true;
379}
380
381static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST,
382 const MachineRegisterInfo &MRI) {
383 return hasAllNBitUsers(OrigMI, ST, MRI, 32);
384}
385
386// This function returns true if the machine instruction always outputs a value
387// where bits 63:32 match bit 31.
388static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo) {
389 uint64_t TSFlags = MI.getDesc().TSFlags;
390
391 // Instructions that can be determined from opcode are marked in tablegen.
393 return true;
394
395 // Special cases that require checking operands.
396 switch (MI.getOpcode()) {
397 // shifting right sufficiently makes the value 32-bit sign-extended
398 case RISCV::SRAI:
399 return MI.getOperand(2).getImm() >= 32;
400 case RISCV::SRLI:
401 return MI.getOperand(2).getImm() > 32;
402 // The LI pattern ADDI rd, X0, imm is sign extended.
403 case RISCV::ADDI:
404 return MI.getOperand(1).isReg() && MI.getOperand(1).getReg() == RISCV::X0;
405 // An ANDI with an 11 bit immediate will zero bits 63:11.
406 case RISCV::ANDI:
407 return isUInt<11>(MI.getOperand(2).getImm());
408 // An ORI with an >11 bit immediate (negative 12-bit) will set bits 63:11.
409 case RISCV::ORI:
410 return !isUInt<11>(MI.getOperand(2).getImm());
411 // A bseti with X0 is sign extended if the immediate is less than 31.
412 case RISCV::BSETI:
413 return MI.getOperand(2).getImm() < 31 &&
414 MI.getOperand(1).getReg() == RISCV::X0;
415 // Copying from X0 produces zero.
416 case RISCV::COPY:
417 return MI.getOperand(1).getReg() == RISCV::X0;
418 // Ignore the scratch register destination.
419 case RISCV::PseudoAtomicLoadNand32:
420 return OpNo == 0;
421 case RISCV::PseudoVMV_X_S: {
422 // vmv.x.s has at least 33 sign bits if log2(sew) <= 5.
423 int64_t Log2SEW = MI.getOperand(2).getImm();
424 assert(Log2SEW >= 3 && Log2SEW <= 6 && "Unexpected Log2SEW");
425 return Log2SEW <= 5;
426 }
427 case RISCV::TH_EXT: {
428 unsigned Msb = MI.getOperand(2).getImm();
429 unsigned Lsb = MI.getOperand(3).getImm();
430 return Msb >= Lsb && (Msb - Lsb + 1) <= 32;
431 }
432 case RISCV::TH_EXTU: {
433 unsigned Msb = MI.getOperand(2).getImm();
434 unsigned Lsb = MI.getOperand(3).getImm();
435 return Msb >= Lsb && (Msb - Lsb + 1) < 32;
436 }
437 case RISCV::SATI_RV64:
438 // Saturates to signed range [-2^(imm-1), 2^(imm-1)-1].
439 // If imm <= 32, result fits in 32-bit signed range, thus sign-extended.
440 return MI.getOperand(2).getImm() <= 32;
441 case RISCV::USATI_RV64:
442 // Saturates to unsigned range [0, 2^imm-1].
443 // If imm < 32, result has bit 31 clear, thus sign-extended.
444 return MI.getOperand(2).getImm() < 32;
445 }
446
447 return false;
448}
449
450static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST,
451 const MachineRegisterInfo &MRI,
453 SmallSet<Register, 4> Visited;
455
456 auto AddRegToWorkList = [&](Register SrcReg) {
457 if (!SrcReg.isVirtual())
458 return false;
459 Worklist.push_back(SrcReg);
460 return true;
461 };
462
463 if (!AddRegToWorkList(SrcReg))
464 return false;
465
466 while (!Worklist.empty()) {
467 Register Reg = Worklist.pop_back_val();
468
469 // If we already visited this register, we don't need to check it again.
470 if (!Visited.insert(Reg).second)
471 continue;
472
474 if (!MI)
475 continue;
476
477 int OpNo = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
478 assert(OpNo != -1 && "Couldn't find register");
479
480 // If this is a sign extending operation we don't need to look any further.
481 if (isSignExtendingOpW(*MI, OpNo))
482 continue;
483
484 // Is this an instruction that propagates sign extend?
485 switch (MI->getOpcode()) {
486 default:
487 // Unknown opcode, give up.
488 return false;
489 case RISCV::COPY: {
490 const MachineFunction *MF = MI->getMF();
491 const RISCVMachineFunctionInfo *RVFI =
493
494 // If this is the entry block, see if we know the copied argument register
495 // is sign extended.
496 if (MI->getParent() == &MF->front() &&
497 RVFI->isSExt32Register(MI->getOperand(0).getReg()))
498 continue;
499
500 Register CopySrcReg = MI->getOperand(1).getReg();
501 if (CopySrcReg == RISCV::X10) {
502 // For a method return value, we check the ZExt/SExt flags in attribute.
503 // We assume the following code sequence for method call.
504 // PseudoCALL @bar, ...
505 // ADJCALLSTACKUP 0, 0, implicit-def dead $x2, implicit $x2
506 // %0:gpr = COPY $x10
507 //
508 // We use the PseudoCall to look up the IR function being called to find
509 // its return attributes.
510 const MachineBasicBlock *MBB = MI->getParent();
511 auto II = MI->getIterator();
512 if (II == MBB->instr_begin() ||
513 (--II)->getOpcode() != RISCV::ADJCALLSTACKUP)
514 return false;
515
516 const MachineInstr &CallMI = *(--II);
517 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
518 return false;
519
520 auto *CalleeFn =
522 if (!CalleeFn)
523 return false;
524
525 auto *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
526 if (!IntTy)
527 return false;
528
529 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
530 unsigned BitWidth = IntTy->getBitWidth();
531 if ((BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
532 (BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
533 continue;
534 }
535
536 if (!AddRegToWorkList(CopySrcReg))
537 return false;
538
539 break;
540 }
541
542 // For these, we just need to check if the 1st operand is sign extended.
543 case RISCV::BCLRI:
544 case RISCV::BINVI:
545 case RISCV::BSETI:
546 if (MI->getOperand(2).getImm() >= 31)
547 return false;
548 [[fallthrough]];
549 case RISCV::REM:
550 case RISCV::ANDI:
551 case RISCV::ORI:
552 case RISCV::XORI:
553 case RISCV::SRAI:
554 // |Remainder| is always <= |Dividend|. If D is 32-bit, then so is R.
555 // DIV doesn't work because of the edge case 0xf..f 8000 0000 / (long)-1
556 // Logical operations use a sign extended 12-bit immediate.
557 // Arithmetic shift right can only increase the number of sign bits.
558 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
559 return false;
560
561 break;
562 case RISCV::PseudoCCADDW:
563 case RISCV::PseudoCCADDIW:
564 case RISCV::PseudoCCSUBW:
565 case RISCV::PseudoCCSLLW:
566 case RISCV::PseudoCCSRLW:
567 case RISCV::PseudoCCSRAW:
568 case RISCV::PseudoCCSLLIW:
569 case RISCV::PseudoCCSRLIW:
570 case RISCV::PseudoCCSRAIW:
571 // Returns operand 1 or an ADDW/SUBW/etc. of operands 2 and 3. We only
572 // need to check if operand 1 is sign extended.
573 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
574 return false;
575 break;
576 case RISCV::REMU:
577 case RISCV::AND:
578 case RISCV::OR:
579 case RISCV::XOR:
580 case RISCV::ANDN:
581 case RISCV::ORN:
582 case RISCV::XNOR:
583 case RISCV::MAX:
584 case RISCV::MAXU:
585 case RISCV::MIN:
586 case RISCV::MINU:
587 case RISCV::PseudoCCMOVGPR:
588 case RISCV::PseudoCCMOVGPRNoX0:
589 case RISCV::PseudoCCAND:
590 case RISCV::PseudoCCOR:
591 case RISCV::PseudoCCXOR:
592 case RISCV::PseudoCCANDN:
593 case RISCV::PseudoCCORN:
594 case RISCV::PseudoCCXNOR:
595 case RISCV::PHI:
596 case RISCV::MERGE:
597 case RISCV::MVM:
598 case RISCV::MVMN: {
599 // If all incoming values are sign-extended, the output of AND, OR, XOR,
600 // MIN, MAX, PHI, or bitwise merge instructions is also sign-extended.
601
602 // The input registers for PHI are operand 1, 3, ...
603 // The input registers for PseudoCCMOVGPR(NoX0) are 1 and 2.
604 // The input registers for PseudoCCAND/OR/XOR are 1, 2, and 3.
605 // The input registers for MERGE/MVM/MVMN are 1, 2, and 3.
606 // The input registers for others are operand 1 and 2.
607 unsigned B = 1, E = 3, D = 1;
608 switch (MI->getOpcode()) {
609 case RISCV::PHI:
610 E = MI->getNumOperands();
611 D = 2;
612 break;
613 case RISCV::PseudoCCMOVGPR:
614 case RISCV::PseudoCCMOVGPRNoX0:
615 B = 1;
616 E = 3;
617 break;
618 case RISCV::PseudoCCAND:
619 case RISCV::PseudoCCOR:
620 case RISCV::PseudoCCXOR:
621 case RISCV::PseudoCCANDN:
622 case RISCV::PseudoCCORN:
623 case RISCV::PseudoCCXNOR:
624 B = 1;
625 E = 4;
626 break;
627 case RISCV::MERGE:
628 case RISCV::MVM:
629 case RISCV::MVMN:
630 B = 1;
631 E = 4;
632 break;
633 }
634
635 for (unsigned I = B; I != E; I += D) {
636 if (!MI->getOperand(I).isReg())
637 return false;
638
639 if (!AddRegToWorkList(MI->getOperand(I).getReg()))
640 return false;
641 }
642
643 break;
644 }
645
646 case RISCV::CZERO_EQZ:
647 case RISCV::CZERO_NEZ:
648 // Instructions return zero or operand 1. Result is sign extended if
649 // operand 1 is sign extended.
650 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
651 return false;
652 break;
653
654 case RISCV::ADDI: {
655 if (MI->getOperand(1).isReg() && MI->getOperand(1).getReg().isVirtual()) {
656 if (MachineInstr *SrcMI = MRI.getVRegDef(MI->getOperand(1).getReg())) {
657 if (SrcMI->getOpcode() == RISCV::LUI &&
658 SrcMI->getOperand(1).isImm()) {
659 uint64_t Imm = SrcMI->getOperand(1).getImm();
660 Imm = SignExtend64<32>(Imm << 12);
661 Imm += (uint64_t)MI->getOperand(2).getImm();
662 if (isInt<32>(Imm))
663 continue;
664 }
665 }
666 }
667
668 if (hasAllWUsers(*MI, ST, MRI)) {
669 FixableDef.insert(MI);
670 break;
671 }
672 return false;
673 }
674
675 case RISCV::LD:
676 case RISCV::LXD: {
677 if (MI->hasOneMemOperand() && !(*MI->memoperands_begin())->isVolatile() &&
678 hasAllWUsers(*MI, ST, MRI)) {
679 FixableDef.insert(MI);
680 break;
681 }
682 return false;
683 }
684
685 // With these opcode, we can "fix" them with the W-version
686 // if we know all users of the result only rely on bits 31:0
687 case RISCV::SLLI:
688 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits
689 if (MI->getOperand(2).getImm() >= 32)
690 return false;
691 [[fallthrough]];
692 case RISCV::ADD:
693 case RISCV::LWU:
694 case RISCV::LXWU:
695 case RISCV::MUL:
696 case RISCV::SUB:
697 if (hasAllWUsers(*MI, ST, MRI)) {
698 FixableDef.insert(MI);
699 break;
700 }
701 return false;
702 case RISCV::ADD_UW:
703 // ZEXT.W is fixable to SEXT.W.
704 // TODO: In some cases it is better to delete the ZEXT.W and fix something
705 // earlier in the graph.
706 if (!MI->getOperand(2).isReg() || MI->getOperand(2).getReg() != RISCV::X0)
707 return false;
708
709 if (hasAllWUsers(*MI, ST, MRI)) {
710 FixableDef.insert(MI);
711 break;
712 }
713 return false;
714 }
715 }
716
717 // If we get here, then every node we visited produces a sign extended value
718 // or propagated sign extended values. So the result must be sign extended.
719 return true;
720}
721
722static unsigned getWOp(unsigned Opcode) {
723 switch (Opcode) {
724 case RISCV::ADDI:
725 return RISCV::ADDIW;
726 case RISCV::ADD:
727 return RISCV::ADDW;
728 case RISCV::LD:
729 case RISCV::LWU:
730 return RISCV::LW;
731 case RISCV::LXD:
732 case RISCV::LXWU:
733 return RISCV::LXW;
734 case RISCV::MUL:
735 return RISCV::MULW;
736 case RISCV::SLLI:
737 return RISCV::SLLIW;
738 case RISCV::SUB:
739 return RISCV::SUBW;
740 default:
741 llvm_unreachable("Unexpected opcode for replacement with W variant");
742 }
743}
744
745bool RISCVOptWInstrsImpl::removeSExtWInstrs(MachineFunction &MF,
746 const RISCVInstrInfo &TII,
747 const RISCVSubtarget &ST,
748 MachineRegisterInfo &MRI) {
750 return false;
751
752 bool MadeChange = false;
753 for (MachineBasicBlock &MBB : MF) {
754 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
755 // We're looking for the sext.w pattern ADDIW rd, rs1, 0.
756 if (!RISCVInstrInfo::isSEXT_W(MI))
757 continue;
758
759 Register SrcReg = MI.getOperand(1).getReg();
760
761 SmallPtrSet<MachineInstr *, 4> FixableDefs;
762
763 // If all users only use the lower bits, this sext.w is redundant.
764 // Or if all definitions reaching MI sign-extend their output,
765 // then sext.w is redundant.
766 if (!hasAllWUsers(MI, ST, MRI) &&
767 !isSignExtendedW(SrcReg, ST, MRI, FixableDefs))
768 continue;
769
770 Register DstReg = MI.getOperand(0).getReg();
771 if (!MRI.constrainRegClass(SrcReg, MRI.getRegClass(DstReg)))
772 continue;
773
774 // Convert Fixable instructions to their W versions.
775 for (MachineInstr *Fixable : FixableDefs) {
776 LLVM_DEBUG(dbgs() << "Replacing " << *Fixable);
777 // Convert zext.w to sext.w.
778 if (Fixable->getOpcode() == RISCV::ADD_UW) {
779 assert(Fixable->getOperand(2).isReg() &&
780 Fixable->getOperand(2).getReg() == RISCV::X0 &&
781 "Unexpected ADD_UW operand.");
782 Fixable->setDesc(TII.get(RISCV::ADDIW));
783 Fixable->getOperand(2).ChangeToImmediate(0);
784 } else {
785 Fixable->setDesc(TII.get(getWOp(Fixable->getOpcode())));
786 }
787 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
788 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
789 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
790 LLVM_DEBUG(dbgs() << " with " << *Fixable);
791 ++NumTransformedToWInstrs;
792 }
793
794 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
795 MRI.replaceRegWith(DstReg, SrcReg);
796 MRI.clearKillFlags(SrcReg);
797 MI.eraseFromParent();
798 ++NumRemovedSExtW;
799 MadeChange = true;
800 }
801 }
802
803 return MadeChange;
804}
805
806// Strips or adds W suffixes to eligible instructions depending on the
807// subtarget preferences.
808bool RISCVOptWInstrsImpl::canonicalizeWSuffixes(MachineFunction &MF,
809 const RISCVInstrInfo &TII,
810 const RISCVSubtarget &ST,
811 MachineRegisterInfo &MRI) {
812 bool ShouldStripW = EnableStripWSuffix && !ST.preferWInst();
813 bool ShouldPreferW = ST.preferWInst();
814 bool MadeChange = false;
815
816 for (MachineBasicBlock &MBB : MF) {
817 for (MachineInstr &MI : MBB) {
818 std::optional<unsigned> WOpc;
819 std::optional<unsigned> NonWOpc;
820 unsigned OrigOpc = MI.getOpcode();
821 switch (OrigOpc) {
822 default:
823 continue;
824 case RISCV::ADDW:
825 NonWOpc = RISCV::ADD;
826 break;
827 case RISCV::ADDIW:
828 NonWOpc = RISCV::ADDI;
829 break;
830 case RISCV::MULW:
831 NonWOpc = RISCV::MUL;
832 break;
833 case RISCV::SLLIW:
834 NonWOpc = RISCV::SLLI;
835 break;
836 case RISCV::SUBW:
837 NonWOpc = RISCV::SUB;
838 break;
839 case RISCV::ADD:
840 WOpc = RISCV::ADDW;
841 break;
842 case RISCV::ADDI:
843 WOpc = RISCV::ADDIW;
844 break;
845 case RISCV::SUB:
846 WOpc = RISCV::SUBW;
847 break;
848 case RISCV::MUL:
849 WOpc = RISCV::MULW;
850 break;
851 case RISCV::SLLI:
852 // SLLIW reads the lowest 5 bits, while SLLI reads lowest 6 bits.
853 if (MI.getOperand(2).getImm() >= 32)
854 continue;
855 WOpc = RISCV::SLLIW;
856 break;
857 case RISCV::LD:
858 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
859 continue;
860 WOpc = RISCV::LW;
861 break;
862 case RISCV::LWU:
863 WOpc = RISCV::LW;
864 break;
865 case RISCV::LXD:
866 if (!MI.hasOneMemOperand() || (*MI.memoperands_begin())->isVolatile())
867 continue;
868 WOpc = RISCV::LXW;
869 break;
870 case RISCV::LXWU:
871 WOpc = RISCV::LXW;
872 break;
873 }
874
875 if (ShouldStripW && NonWOpc.has_value() && hasAllWUsers(MI, ST, MRI)) {
876 LLVM_DEBUG(dbgs() << "Replacing " << MI);
877 MI.setDesc(TII.get(NonWOpc.value()));
878 LLVM_DEBUG(dbgs() << " with " << MI);
879 ++NumTransformedToNonWInstrs;
880 MadeChange = true;
881 continue;
882 }
883 // LWU is always converted to LW when possible as 1) LW is compressible
884 // and 2) it helps minimise differences vs RV32.
885 if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
886 hasAllWUsers(MI, ST, MRI)) {
887 LLVM_DEBUG(dbgs() << "Replacing " << MI);
888 MI.setDesc(TII.get(WOpc.value()));
889 MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
890 MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
891 MI.clearFlag(MachineInstr::MIFlag::IsExact);
892 LLVM_DEBUG(dbgs() << " with " << MI);
893 ++NumTransformedToWInstrs;
894 MadeChange = true;
895 continue;
896 }
897 }
898 }
899 return MadeChange;
900}
901
902bool RISCVOptWInstrsImpl::run(MachineFunction &MF) {
903 MachineRegisterInfo &MRI = MF.getRegInfo();
904 const RISCVSubtarget &ST = MF.getSubtarget<RISCVSubtarget>();
905 const RISCVInstrInfo &TII = *ST.getInstrInfo();
906
907 if (!ST.is64Bit())
908 return false;
909
910 bool MadeChange = false;
911 MadeChange |= removeSExtWInstrs(MF, TII, ST, MRI);
912 MadeChange |= canonicalizeWSuffixes(MF, TII, ST, MRI);
913 return MadeChange;
914}
915
916bool RISCVOptWInstrsLegacy::runOnMachineFunction(MachineFunction &MF) {
917 if (skipFunction(MF.getFunction()))
918 return false;
919 return RISCVOptWInstrsImpl().run(MF);
920}
921
922PreservedAnalyses
925 bool Changed = RISCVOptWInstrsImpl().run(MF);
926 if (!Changed)
927 return PreservedAnalyses::all();
928
931 return PA;
932}
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 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 vectorPseudoHasAllNBitUsers(const MachineInstr &MI, unsigned OpIdx, unsigned Bits)
static cl::opt< bool > EnableStripWSuffix("riscv-strip-w-suffix", cl::desc("Enable strip W suffix"), cl::init(true), cl::Hidden)
static bool isSignExtendedW(Register SrcReg, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
static cl::opt< bool > EnableSExtWRemoval("riscv-sextw-removal", cl::desc("Enable removal of sext.w"), cl::init(true), cl::Hidden)
static bool hasAllWUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI)
static bool isSignExtendingOpW(const MachineInstr &MI, unsigned OpNo)
static bool hasAllNBitUsers(const MachineInstr &OrigMI, const RISCVSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
#define RISCV_OPT_W_INSTRS_NAME
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:278
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
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
const GlobalValue * getGlobal() const
int64_t getImm() const
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 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:649
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