LLVM 24.0.0git
LoongArchOptWInstrs.cpp
Go to the documentation of this file.
1//===- LoongArchOptWInstrs.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(addi.w rd, rs, 0) instructions. Either
12// because the sign extended bits aren't consumed or because the input was
13// already sign extended 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// * addi.w because it helps reduce test differences between LA32 and LA64
21// w/o being a pessimization.
22//
23// 2. Or if explicit enabled or the target prefers instructions with W suffix,
24// it adds the W suffix to the instruction whenever all users are dependent
25// only on the lower word of the result of the instruction.
26// The cases handled are:
27// * add.d/addi.d/sub.d/mul.d.
28// * slli.d with imm < 32.
29// * ld.d/ld.wu.
30//===---------------------------------------------------------------------===//
31
32#include "LoongArch.h"
34#include "LoongArchSubtarget.h"
35#include "llvm/ADT/SmallSet.h"
36#include "llvm/ADT/Statistic.h"
41#include "llvm/IR/Analysis.h"
42
43using namespace llvm;
44
45#define DEBUG_TYPE "loongarch-opt-w-instrs"
46#define LOONGARCH_OPT_W_INSTRS_NAME "LoongArch Optimize W Instructions"
47
48STATISTIC(NumRemovedSExtW, "Number of removed sign-extensions");
49STATISTIC(NumTransformedToWInstrs,
50 "Number of instructions transformed to W-ops");
51
52static cl::opt<bool>
53 DisableSExtWRemoval("loongarch-disable-sextw-removal",
54 cl::desc("Disable removal of sign-extend insn"),
55 cl::init(false), cl::Hidden);
56static cl::opt<bool>
57 DisableCvtToDSuffix("loongarch-disable-cvt-to-d-suffix",
58 cl::desc("Disable convert to D suffix"),
59 cl::init(false), cl::Hidden);
60
61namespace {
62
63class LoongArchOptWInstrsLegacy : public MachineFunctionPass {
64public:
65 static char ID;
66
67 LoongArchOptWInstrsLegacy() : MachineFunctionPass(ID) {}
68
69 bool runOnMachineFunction(MachineFunction &MF) override;
70
71 void getAnalysisUsage(AnalysisUsage &AU) const override {
72 AU.setPreservesCFG();
74 }
75
76 StringRef getPassName() const override { return LOONGARCH_OPT_W_INSTRS_NAME; }
77};
78
79} // end anonymous namespace
80
81char LoongArchOptWInstrsLegacy::ID = 0;
82INITIALIZE_PASS(LoongArchOptWInstrsLegacy, DEBUG_TYPE,
83 LOONGARCH_OPT_W_INSTRS_NAME, false, false)
84
86 return new LoongArchOptWInstrsLegacy();
87}
88
89// Checks if all users only demand the lower \p OrigBits of the original
90// instruction's result.
91// TODO: handle multiple interdependent transformations
92static bool hasAllNBitUsers(const MachineInstr &OrigMI,
93 const LoongArchSubtarget &ST,
94 const MachineRegisterInfo &MRI, unsigned OrigBits) {
95
98
99 Worklist.push_back(std::make_pair(&OrigMI, OrigBits));
100
101 while (!Worklist.empty()) {
102 auto P = Worklist.pop_back_val();
103 const MachineInstr *MI = P.first;
104 unsigned Bits = P.second;
105
106 if (!Visited.insert(P).second)
107 continue;
108
109 // Only handle instructions with one def.
110 if (MI->getNumExplicitDefs() != 1)
111 return false;
112
113 Register DestReg = MI->getOperand(0).getReg();
114 if (!DestReg.isVirtual())
115 return false;
116
117 for (auto &UserOp : MRI.use_nodbg_operands(DestReg)) {
118 const MachineInstr *UserMI = UserOp.getParent();
119 unsigned OpIdx = UserOp.getOperandNo();
120
121 switch (UserMI->getOpcode()) {
122 default:
123 return false;
124
125 case LoongArch::ADD_W:
126 case LoongArch::ADDI_W:
127 case LoongArch::SUB_W:
128 case LoongArch::ALSL_W:
129 case LoongArch::ALSL_WU:
130 case LoongArch::MUL_W:
131 case LoongArch::MULH_W:
132 case LoongArch::MULH_WU:
133 case LoongArch::MULW_D_W:
134 case LoongArch::MULW_D_WU:
135 case LoongArch::SLL_W:
136 case LoongArch::SLLI_W:
137 case LoongArch::SRL_W:
138 case LoongArch::SRLI_W:
139 case LoongArch::SRA_W:
140 case LoongArch::SRAI_W:
141 case LoongArch::ROTR_W:
142 case LoongArch::ROTRI_W:
143 case LoongArch::CLO_W:
144 case LoongArch::CLZ_W:
145 case LoongArch::CTO_W:
146 case LoongArch::CTZ_W:
147 case LoongArch::BYTEPICK_W:
148 case LoongArch::REVB_2H:
149 case LoongArch::BITREV_4B:
150 case LoongArch::BITREV_W:
151 case LoongArch::BSTRINS_W:
152 case LoongArch::BSTRPICK_W:
153 case LoongArch::CRC_W_W_W:
154 case LoongArch::CRCC_W_W_W:
155 case LoongArch::MOVGR2FCSR:
156 case LoongArch::MOVGR2FRH_W:
157 case LoongArch::MOVGR2FR_W_64:
158 case LoongArch::VINSGR2VR_W:
159 case LoongArch::XVINSGR2VR_W:
160 case LoongArch::VREPLGR2VR_W:
161 case LoongArch::XVREPLGR2VR_W:
162 if (Bits >= 32)
163 break;
164 return false;
165 // {DIV,MOD}.W{U} consumes the upper 32 bits if the div32
166 // feature is not enabled.
167 case LoongArch::DIV_W:
168 case LoongArch::DIV_WU:
169 case LoongArch::MOD_W:
170 case LoongArch::MOD_WU:
171 if (Bits >= 32 && ST.hasDiv32())
172 break;
173 return false;
174 case LoongArch::MOVGR2CF:
175 case LoongArch::VREPLVE_D:
176 case LoongArch::XVREPLVE_D:
177 if (Bits >= 1)
178 break;
179 return false;
180 case LoongArch::VREPLVE_W:
181 case LoongArch::XVREPLVE_W:
182 if (Bits >= 2)
183 break;
184 return false;
185 case LoongArch::VREPLVE_H:
186 case LoongArch::XVREPLVE_H:
187 if (Bits >= 3)
188 break;
189 return false;
190 case LoongArch::VREPLVE_B:
191 case LoongArch::XVREPLVE_B:
192 if (Bits >= 4)
193 break;
194 return false;
195 case LoongArch::EXT_W_B:
196 case LoongArch::VINSGR2VR_B:
197 case LoongArch::VREPLGR2VR_B:
198 case LoongArch::XVREPLGR2VR_B:
199 if (Bits >= 8)
200 break;
201 return false;
202 case LoongArch::EXT_W_H:
203 case LoongArch::VINSGR2VR_H:
204 case LoongArch::VREPLGR2VR_H:
205 case LoongArch::XVREPLGR2VR_H:
206 if (Bits >= 16)
207 break;
208 return false;
209
210 case LoongArch::SRLI_D: {
211 // If we are shifting right by less than Bits, and users don't demand
212 // any bits that were shifted into [Bits-1:0], then we can consider this
213 // as an N-Bit user.
214 unsigned ShAmt = UserMI->getOperand(2).getImm();
215 if (Bits > ShAmt) {
216 Worklist.push_back(std::make_pair(UserMI, Bits - ShAmt));
217 break;
218 }
219 return false;
220 }
221
222 // these overwrite higher input bits, otherwise the lower word of output
223 // depends only on the lower word of input. So check their uses read W.
224 case LoongArch::SLLI_D:
225 if (Bits >= (ST.getGRLen() - UserMI->getOperand(2).getImm()))
226 break;
227 Worklist.push_back(std::make_pair(UserMI, Bits));
228 break;
229 case LoongArch::ANDI: {
230 uint64_t Imm = UserMI->getOperand(2).getImm();
231 if (Bits >= (unsigned)llvm::bit_width(Imm))
232 break;
233 Worklist.push_back(std::make_pair(UserMI, Bits));
234 break;
235 }
236 case LoongArch::ORI: {
237 uint64_t Imm = UserMI->getOperand(2).getImm();
238 if (Bits >= (unsigned)llvm::bit_width<uint64_t>(~Imm))
239 break;
240 Worklist.push_back(std::make_pair(UserMI, Bits));
241 break;
242 }
243
244 case LoongArch::SLL_D:
245 // Operand 2 is the shift amount which uses log2(grlen) bits.
246 if (OpIdx == 2) {
247 if (Bits >= Log2_32(ST.getGRLen()))
248 break;
249 return false;
250 }
251 Worklist.push_back(std::make_pair(UserMI, Bits));
252 break;
253
254 case LoongArch::SRA_D:
255 case LoongArch::SRL_D:
256 case LoongArch::ROTR_D:
257 // Operand 2 is the shift amount which uses 6 bits.
258 if (OpIdx == 2 && Bits >= Log2_32(ST.getGRLen()))
259 break;
260 return false;
261
262 case LoongArch::ST_B:
263 case LoongArch::STX_B:
264 case LoongArch::STGT_B:
265 case LoongArch::STLE_B:
266 case LoongArch::IOCSRWR_B:
267 // The first argument is the value to store.
268 if (OpIdx == 0 && Bits >= 8)
269 break;
270 return false;
271 case LoongArch::ST_H:
272 case LoongArch::STX_H:
273 case LoongArch::STGT_H:
274 case LoongArch::STLE_H:
275 case LoongArch::IOCSRWR_H:
276 // The first argument is the value to store.
277 if (OpIdx == 0 && Bits >= 16)
278 break;
279 return false;
280 case LoongArch::ST_W:
281 case LoongArch::STX_W:
282 case LoongArch::SCREL_W:
283 case LoongArch::STPTR_W:
284 case LoongArch::STGT_W:
285 case LoongArch::STLE_W:
286 case LoongArch::IOCSRWR_W:
287 // The first argument is the value to store.
288 if (OpIdx == 0 && Bits >= 32)
289 break;
290 return false;
291
292 case LoongArch::CRC_W_B_W:
293 case LoongArch::CRCC_W_B_W:
294 if ((OpIdx == 1 && Bits >= 8) || (OpIdx == 2 && Bits >= 32))
295 break;
296 return false;
297 case LoongArch::CRC_W_H_W:
298 case LoongArch::CRCC_W_H_W:
299 if ((OpIdx == 1 && Bits >= 16) || (OpIdx == 2 && Bits >= 32))
300 break;
301 return false;
302 case LoongArch::CRC_W_D_W:
303 case LoongArch::CRCC_W_D_W:
304 if (OpIdx == 2 && Bits >= 32)
305 break;
306 return false;
307
308 // For these, lower word of output in these operations, depends only on
309 // the lower word of input. So, we check all uses only read lower word.
310 case LoongArch::COPY:
311 case LoongArch::PHI:
312 case LoongArch::ADD_D:
313 case LoongArch::ADDI_D:
314 case LoongArch::SUB_D:
315 case LoongArch::MUL_D:
316 case LoongArch::AND:
317 case LoongArch::OR:
318 case LoongArch::NOR:
319 case LoongArch::XOR:
320 case LoongArch::XORI:
321 case LoongArch::ANDN:
322 case LoongArch::ORN:
323 Worklist.push_back(std::make_pair(UserMI, Bits));
324 break;
325
326 case LoongArch::MASKNEZ:
327 case LoongArch::MASKEQZ:
328 if (OpIdx != 1)
329 return false;
330 Worklist.push_back(std::make_pair(UserMI, Bits));
331 break;
332 }
333 }
334 }
335
336 return true;
337}
338
339static bool hasAllWUsers(const MachineInstr &OrigMI,
340 const LoongArchSubtarget &ST,
341 const MachineRegisterInfo &MRI) {
342 return hasAllNBitUsers(OrigMI, ST, MRI, 32);
343}
344
345// This function returns true if the machine instruction always outputs a value
346// where bits 63:32 match bit 31.
348 const MachineRegisterInfo &MRI, unsigned OpNo) {
349 switch (MI.getOpcode()) {
350 // Normal cases
351 case LoongArch::ADD_W:
352 case LoongArch::SUB_W:
353 case LoongArch::ADDI_W:
354 case LoongArch::ALSL_W:
355 case LoongArch::LU12I_W:
356 case LoongArch::SLT:
357 case LoongArch::SLTU:
358 case LoongArch::SLTI:
359 case LoongArch::SLTUI:
360 case LoongArch::ANDI:
361 case LoongArch::MUL_W:
362 case LoongArch::MULH_W:
363 case LoongArch::MULH_WU:
364 case LoongArch::DIV_W:
365 case LoongArch::MOD_W:
366 case LoongArch::DIV_WU:
367 case LoongArch::MOD_WU:
368 case LoongArch::SLL_W:
369 case LoongArch::SRL_W:
370 case LoongArch::SRA_W:
371 case LoongArch::ROTR_W:
372 case LoongArch::SLLI_W:
373 case LoongArch::SRLI_W:
374 case LoongArch::SRAI_W:
375 case LoongArch::ROTRI_W:
376 case LoongArch::EXT_W_B:
377 case LoongArch::EXT_W_H:
378 case LoongArch::CLO_W:
379 case LoongArch::CLZ_W:
380 case LoongArch::CTO_W:
381 case LoongArch::CTZ_W:
382 case LoongArch::BYTEPICK_W:
383 case LoongArch::REVB_2H:
384 case LoongArch::BITREV_4B:
385 case LoongArch::BITREV_W:
386 case LoongArch::BSTRINS_W:
387 case LoongArch::BSTRPICK_W:
388 case LoongArch::LD_B:
389 case LoongArch::LD_H:
390 case LoongArch::LD_W:
391 case LoongArch::LD_BU:
392 case LoongArch::LD_HU:
393 case LoongArch::LL_W:
394 case LoongArch::LLACQ_W:
395 case LoongArch::RDTIMEL_W:
396 case LoongArch::RDTIMEH_W:
397 case LoongArch::CPUCFG:
398 case LoongArch::LDX_B:
399 case LoongArch::LDX_H:
400 case LoongArch::LDX_W:
401 case LoongArch::LDX_BU:
402 case LoongArch::LDX_HU:
403 case LoongArch::LDPTR_W:
404 case LoongArch::LDGT_B:
405 case LoongArch::LDGT_H:
406 case LoongArch::LDGT_W:
407 case LoongArch::LDLE_B:
408 case LoongArch::LDLE_H:
409 case LoongArch::LDLE_W:
410 case LoongArch::AMSWAP_B:
411 case LoongArch::AMSWAP_H:
412 case LoongArch::AMSWAP_W:
413 case LoongArch::AMADD_B:
414 case LoongArch::AMADD_H:
415 case LoongArch::AMADD_W:
416 case LoongArch::AMAND_W:
417 case LoongArch::AMOR_W:
418 case LoongArch::AMXOR_W:
419 case LoongArch::AMMAX_W:
420 case LoongArch::AMMIN_W:
421 case LoongArch::AMMAX_WU:
422 case LoongArch::AMMIN_WU:
423 case LoongArch::AMSWAP__DB_B:
424 case LoongArch::AMSWAP__DB_H:
425 case LoongArch::AMSWAP__DB_W:
426 case LoongArch::AMADD__DB_B:
427 case LoongArch::AMADD__DB_H:
428 case LoongArch::AMADD__DB_W:
429 case LoongArch::AMAND__DB_W:
430 case LoongArch::AMOR__DB_W:
431 case LoongArch::AMXOR__DB_W:
432 case LoongArch::AMMAX__DB_W:
433 case LoongArch::AMMIN__DB_W:
434 case LoongArch::AMMAX__DB_WU:
435 case LoongArch::AMMIN__DB_WU:
436 case LoongArch::AMCAS_B:
437 case LoongArch::AMCAS_H:
438 case LoongArch::AMCAS_W:
439 case LoongArch::AMCAS__DB_B:
440 case LoongArch::AMCAS__DB_H:
441 case LoongArch::AMCAS__DB_W:
442 case LoongArch::CRC_W_B_W:
443 case LoongArch::CRC_W_H_W:
444 case LoongArch::CRC_W_W_W:
445 case LoongArch::CRC_W_D_W:
446 case LoongArch::CRCC_W_B_W:
447 case LoongArch::CRCC_W_H_W:
448 case LoongArch::CRCC_W_W_W:
449 case LoongArch::CRCC_W_D_W:
450 case LoongArch::IOCSRRD_B:
451 case LoongArch::IOCSRRD_H:
452 case LoongArch::IOCSRRD_W:
453 case LoongArch::MOVFR2GR_S:
454 case LoongArch::MOVFCSR2GR:
455 case LoongArch::MOVCF2GR:
456 case LoongArch::MOVFRH2GR_S:
457 case LoongArch::MOVFR2GR_S_64:
458 case LoongArch::VPICKVE2GR_W:
459 case LoongArch::XVPICKVE2GR_W:
460 return true;
461 // Special cases that require checking operands.
462 // shifting right sufficiently makes the value 32-bit sign-extended
463 case LoongArch::SRAI_D:
464 return MI.getOperand(2).getImm() >= 32;
465 case LoongArch::SRLI_D:
466 return MI.getOperand(2).getImm() > 32;
467 // The LI pattern ADDI rd, R0, imm and ORI rd, R0, imm are sign extended.
468 case LoongArch::ADDI_D:
469 case LoongArch::ORI:
470 return MI.getOperand(1).isReg() &&
471 MI.getOperand(1).getReg() == LoongArch::R0;
472 // A bits extract is sign extended if the msb is less than 31.
473 case LoongArch::BSTRPICK_D:
474 return MI.getOperand(2).getImm() < 31;
475 // Copying from R0 produces zero.
476 case LoongArch::COPY:
477 return MI.getOperand(1).getReg() == LoongArch::R0;
478 // Ignore the scratch register destination.
479 case LoongArch::PseudoMaskedAtomicSwap32:
480 case LoongArch::PseudoAtomicSwap32:
481 case LoongArch::PseudoMaskedAtomicLoadAdd32:
482 case LoongArch::PseudoMaskedAtomicLoadSub32:
483 case LoongArch::PseudoAtomicLoadNand32:
484 case LoongArch::PseudoMaskedAtomicLoadNand32:
485 case LoongArch::PseudoAtomicLoadAdd32:
486 case LoongArch::PseudoAtomicLoadSub32:
487 case LoongArch::PseudoAtomicLoadAnd32:
488 case LoongArch::PseudoAtomicLoadOr32:
489 case LoongArch::PseudoAtomicLoadXor32:
490 case LoongArch::PseudoMaskedAtomicLoadUMax32:
491 case LoongArch::PseudoMaskedAtomicLoadUMin32:
492 case LoongArch::PseudoCmpXchg32:
493 case LoongArch::PseudoMaskedCmpXchg32:
494 case LoongArch::PseudoMaskedAtomicLoadMax32:
495 case LoongArch::PseudoMaskedAtomicLoadMin32:
496 return OpNo == 0;
497 }
498
499 return false;
500}
501
502static bool isSignExtendedW(Register SrcReg, const LoongArchSubtarget &ST,
505 SmallSet<Register, 4> Visited;
507
508 auto AddRegToWorkList = [&](Register SrcReg) {
509 if (!SrcReg.isVirtual())
510 return false;
511 Worklist.push_back(SrcReg);
512 return true;
513 };
514
515 if (!AddRegToWorkList(SrcReg))
516 return false;
517
518 while (!Worklist.empty()) {
519 Register Reg = Worklist.pop_back_val();
520
521 // If we already visited this register, we don't need to check it again.
522 if (!Visited.insert(Reg).second)
523 continue;
524
525 MachineInstr *MI = MRI.getVRegDef(Reg);
526 if (!MI)
527 continue;
528
529 int OpNo = MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr);
530 assert(OpNo != -1 && "Couldn't find register");
531
532 // If this is a sign extending operation we don't need to look any further.
533 if (isSignExtendingOpW(*MI, MRI, OpNo))
534 continue;
535
536 // Is this an instruction that propagates sign extend?
537 switch (MI->getOpcode()) {
538 default:
539 // Unknown opcode, give up.
540 return false;
541 case LoongArch::COPY: {
542 const MachineFunction *MF = MI->getMF();
543 const LoongArchMachineFunctionInfo *LAFI =
545
546 // If this is the entry block and the register is livein, see if we know
547 // it is sign extended.
548 if (MI->getParent() == &MF->front()) {
549 Register VReg = MI->getOperand(0).getReg();
550 if (MF->getRegInfo().isLiveIn(VReg) && LAFI->isSExt32Register(VReg))
551 continue;
552 }
553
554 Register CopySrcReg = MI->getOperand(1).getReg();
555 if (CopySrcReg == LoongArch::R4) {
556 // For a method return value, we check the ZExt/SExt flags in attribute.
557 // We assume the following code sequence for method call.
558 // PseudoCALL_SMALL @bar, ...
559 // ADJCALLSTACKUP 0, 0, implicit-def dead $r3, implicit $r3
560 // %0:gpr = COPY $r4
561 //
562 // We use the PseudoCall to look up the IR function being called to find
563 // its return attributes.
564 const MachineBasicBlock *MBB = MI->getParent();
565 auto II = MI->getIterator();
566 if (II == MBB->instr_begin() ||
567 (--II)->getOpcode() != LoongArch::ADJCALLSTACKUP)
568 return false;
569
570 const MachineInstr &CallMI = *(--II);
571 if (!CallMI.isCall() || !CallMI.getOperand(0).isGlobal())
572 return false;
573
574 auto *CalleeFn =
576 if (!CalleeFn)
577 return false;
578
579 auto *IntTy = dyn_cast<IntegerType>(CalleeFn->getReturnType());
580 if (!IntTy)
581 return false;
582
583 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
584 unsigned BitWidth = IntTy->getBitWidth();
585 if ((BitWidth <= 32 && Attrs.hasAttribute(Attribute::SExt)) ||
586 (BitWidth < 32 && Attrs.hasAttribute(Attribute::ZExt)))
587 continue;
588 }
589
590 if (!AddRegToWorkList(CopySrcReg))
591 return false;
592
593 break;
594 }
595
596 // For these, we just need to check if the 1st operand is sign extended.
597 case LoongArch::MOD_D:
598 case LoongArch::ANDI:
599 case LoongArch::ORI:
600 case LoongArch::XORI:
601 // |Remainder| is always <= |Dividend|. If D is 32-bit, then so is R.
602 // DIV doesn't work because of the edge case 0xf..f 8000 0000 / (long)-1
603 // Logical operations use a sign extended 12-bit immediate.
604 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
605 return false;
606
607 break;
608 case LoongArch::MOD_DU:
609 case LoongArch::AND:
610 case LoongArch::OR:
611 case LoongArch::XOR:
612 case LoongArch::ANDN:
613 case LoongArch::ORN:
614 case LoongArch::PHI: {
615 // If all incoming values are sign-extended, the output of AND, OR, XOR,
616 // or PHI is also sign-extended.
617
618 // The input registers for PHI are operand 1, 3, ...
619 // The input registers for others are operand 1 and 2.
620 unsigned B = 1, E = 3, D = 1;
621 switch (MI->getOpcode()) {
622 case LoongArch::PHI:
623 E = MI->getNumOperands();
624 D = 2;
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 LoongArch::MASKEQZ:
640 case LoongArch::MASKNEZ:
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 // With these opcode, we can "fix" them with the W-version
648 // if we know all users of the result only rely on bits 31:0
649 case LoongArch::SLLI_D:
650 // SLLI_W reads the lowest 5 bits, while SLLI_D reads lowest 6 bits
651 if (MI->getOperand(2).getImm() >= 32)
652 return false;
653 [[fallthrough]];
654 case LoongArch::ADDI_D:
655 case LoongArch::ADD_D:
656 case LoongArch::LD_D:
657 case LoongArch::LD_WU:
658 case LoongArch::MUL_D:
659 case LoongArch::SUB_D:
660 if (hasAllWUsers(*MI, ST, MRI)) {
661 FixableDef.insert(MI);
662 break;
663 }
664 return false;
665 // If all incoming values are sign-extended and all users only use
666 // the lower 32 bits, then convert them to W versions.
667 case LoongArch::DIV_D: {
668 if (!AddRegToWorkList(MI->getOperand(1).getReg()))
669 return false;
670 if (!AddRegToWorkList(MI->getOperand(2).getReg()))
671 return false;
672 if (hasAllWUsers(*MI, ST, MRI)) {
673 FixableDef.insert(MI);
674 break;
675 }
676 return false;
677 }
678 }
679 }
680
681 // If we get here, then every node we visited produces a sign extended value
682 // or propagated sign extended values. So the result must be sign extended.
683 return true;
684}
685
686static unsigned getWOp(unsigned Opcode) {
687 switch (Opcode) {
688 case LoongArch::ADDI_D:
689 return LoongArch::ADDI_W;
690 case LoongArch::ADD_D:
691 return LoongArch::ADD_W;
692 case LoongArch::DIV_D:
693 return LoongArch::DIV_W;
694 case LoongArch::LD_D:
695 case LoongArch::LD_WU:
696 return LoongArch::LD_W;
697 case LoongArch::MUL_D:
698 return LoongArch::MUL_W;
699 case LoongArch::SLLI_D:
700 return LoongArch::SLLI_W;
701 case LoongArch::SUB_D:
702 return LoongArch::SUB_W;
703 default:
704 llvm_unreachable("Unexpected opcode for replacement with W variant");
705 }
706}
707
709 const LoongArchInstrInfo &TII,
710 const LoongArchSubtarget &ST,
713 return false;
714
715 bool MadeChange = false;
716 for (MachineBasicBlock &MBB : MF) {
718 // We're looking for the sext.w pattern ADDI.W rd, rs, 0.
720 continue;
721
722 Register SrcReg = MI.getOperand(1).getReg();
723
725
726 // If all users only use the lower bits, this sext.w is redundant.
727 // Or if all definitions reaching MI sign-extend their output,
728 // then sext.w is redundant.
729 if (!hasAllWUsers(MI, ST, MRI) &&
730 !isSignExtendedW(SrcReg, ST, MRI, FixableDefs))
731 continue;
732
733 Register DstReg = MI.getOperand(0).getReg();
734 if (!SrcReg.isVirtual() ||
735 !MRI.constrainRegClass(SrcReg, MRI.getRegClass(DstReg)))
736 continue;
737
738 // Convert Fixable instructions to their W versions.
739 for (MachineInstr *Fixable : FixableDefs) {
740 LLVM_DEBUG(dbgs() << "Replacing " << *Fixable);
741 Fixable->setDesc(TII.get(getWOp(Fixable->getOpcode())));
742 Fixable->clearFlag(MachineInstr::MIFlag::NoSWrap);
743 Fixable->clearFlag(MachineInstr::MIFlag::NoUWrap);
744 Fixable->clearFlag(MachineInstr::MIFlag::IsExact);
745 LLVM_DEBUG(dbgs() << " with " << *Fixable);
746 ++NumTransformedToWInstrs;
747 }
748
749 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
750 MRI.replaceRegWith(DstReg, SrcReg);
751 MI.eraseFromParent();
752 ++NumRemovedSExtW;
753 MadeChange = true;
754 }
755 }
756
757 return MadeChange;
758}
759
761 const LoongArchInstrInfo &TII,
762 const LoongArchSubtarget &ST,
764 bool MadeChange = false;
765 for (MachineBasicBlock &MBB : MF) {
766 for (MachineInstr &MI : MBB) {
767 unsigned Opc;
768 switch (MI.getOpcode()) {
769 default:
770 continue;
771 case LoongArch::ADDI_W:
772 Opc = LoongArch::ADDI_D;
773 break;
774 }
775
776 if (hasAllWUsers(MI, ST, MRI)) {
777 MI.setDesc(TII.get(Opc));
778 MadeChange = true;
779 }
780 }
781 }
782
783 return MadeChange;
784}
785
787 const LoongArchInstrInfo &TII,
788 const LoongArchSubtarget &ST,
790 bool MadeChange = false;
791 for (MachineBasicBlock &MBB : MF) {
792 for (MachineInstr &MI : MBB) {
793 unsigned WOpc;
794 // TODO: Add more?
795 switch (MI.getOpcode()) {
796 default:
797 continue;
798 case LoongArch::ADD_D:
799 WOpc = LoongArch::ADD_W;
800 break;
801 case LoongArch::ADDI_D:
802 WOpc = LoongArch::ADDI_W;
803 break;
804 case LoongArch::SUB_D:
805 WOpc = LoongArch::SUB_W;
806 break;
807 case LoongArch::MUL_D:
808 WOpc = LoongArch::MUL_W;
809 break;
810 case LoongArch::SLLI_D:
811 // SLLI.W reads the lowest 5 bits, while SLLI.D reads lowest 6 bits
812 if (MI.getOperand(2).getImm() >= 32)
813 continue;
814 WOpc = LoongArch::SLLI_W;
815 break;
816 case LoongArch::LD_D:
817 case LoongArch::LD_WU:
818 WOpc = LoongArch::LD_W;
819 break;
820 }
821
822 if (hasAllWUsers(MI, ST, MRI)) {
823 LLVM_DEBUG(dbgs() << "Replacing " << MI);
824 MI.setDesc(TII.get(WOpc));
828 LLVM_DEBUG(dbgs() << " with " << MI);
829 ++NumTransformedToWInstrs;
830 MadeChange = true;
831 }
832 }
833 }
834
835 return MadeChange;
836}
837
841 const LoongArchInstrInfo &TII = *ST.getInstrInfo();
842
843 if (!ST.is64Bit())
844 return false;
845
846 bool MadeChange = false;
847 MadeChange |= removeSExtWInstrs(MF, TII, ST, MRI);
848
849 if (!(DisableCvtToDSuffix || ST.preferWInst()))
850 MadeChange |= convertToDSuffixes(MF, TII, ST, MRI);
851
852 if (ST.preferWInst())
853 MadeChange |= convertToWSuffixes(MF, TII, ST, MRI);
854
855 return MadeChange;
856}
857
858bool LoongArchOptWInstrsLegacy::runOnMachineFunction(MachineFunction &MF) {
859 if (skipFunction(MF.getFunction()))
860 return false;
861 return optWInstrsInMF(MF);
862}
863
864PreservedAnalyses
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
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
unsigned Opc
static bool isSignExtendingOpW(const MachineInstr &MI, const MachineRegisterInfo &MRI, unsigned OpNo)
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 optWInstrsInMF(MachineFunction &MF)
static bool convertToWSuffixes(MachineFunction &MF, const LoongArchInstrInfo &TII, const LoongArchSubtarget &ST, MachineRegisterInfo &MRI)
static bool isSignExtendedW(Register SrcReg, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI, SmallPtrSetImpl< MachineInstr * > &FixableDef)
#define LOONGARCH_OPT_W_INSTRS_NAME
static bool removeSExtWInstrs(MachineFunction &MF, const LoongArchInstrInfo &TII, const LoongArchSubtarget &ST, MachineRegisterInfo &MRI)
static bool convertToDSuffixes(MachineFunction &MF, const LoongArchInstrInfo &TII, const LoongArchSubtarget &ST, MachineRegisterInfo &MRI)
static bool hasAllNBitUsers(const MachineInstr &OrigMI, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
static unsigned getWOp(unsigned Opcode)
static cl::opt< bool > DisableCvtToDSuffix("loongarch-disable-cvt-to-d-suffix", cl::desc("Disable convert to D suffix"), cl::init(false), cl::Hidden)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
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:170
#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:280
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
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:312
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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,...
LLVM_ABI bool isLiveIn(Register Reg) const
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
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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isSEXT_W(const MachineInstr &MI)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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
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
FunctionPass * createLoongArchOptWInstrsLegacyPass()
constexpr unsigned BitWidth