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