LLVM 24.0.0git
RISCVInstructionSelector.cpp
Go to the documentation of this file.
1//===-- RISCVInstructionSelector.cpp -----------------------------*- C++ -*-==//
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/// \file
9/// This file implements the targeting of the InstructionSelector class for
10/// RISC-V.
11/// \todo This should be generated by TableGen.
12//===----------------------------------------------------------------------===//
13
17#include "RISCVSubtarget.h"
18#include "RISCVTargetMachine.h"
26#include "llvm/IR/IntrinsicsRISCV.h"
27#include "llvm/Support/Debug.h"
28
29#define DEBUG_TYPE "riscv-isel"
30
31using namespace llvm;
32using namespace MIPatternMatch;
33
34#define GET_GLOBALISEL_PREDICATE_BITSET
35#include "RISCVGenGlobalISel.inc"
36#undef GET_GLOBALISEL_PREDICATE_BITSET
37
38namespace {
39
40class RISCVInstructionSelector : public InstructionSelector {
41public:
42 RISCVInstructionSelector(const RISCVTargetMachine &TM,
43 const RISCVSubtarget &STI,
44 const RISCVRegisterBankInfo &RBI);
45
46 bool select(MachineInstr &MI) override;
47
48 void setupMF(MachineFunction &MF, GISelValueTracking *VT,
49 CodeGenCoverage *CoverageInfo, ProfileSummaryInfo *PSI,
50 BlockFrequencyInfo *BFI) override {
51 InstructionSelector::setupMF(MF, VT, CoverageInfo, PSI, BFI);
52 MRI = &MF.getRegInfo();
53 }
54
55 static const char *getName() { return DEBUG_TYPE; }
56
57private:
58 static constexpr unsigned MaxRecursionDepth = 6;
59
60 bool hasAllNBitUsers(const MachineInstr &MI, unsigned Bits,
61 const unsigned Depth = 0) const;
62 bool hasAllHUsers(const MachineInstr &MI) const {
63 return hasAllNBitUsers(MI, 16);
64 }
65 bool hasAllWUsers(const MachineInstr &MI) const {
66 return hasAllNBitUsers(MI, 32);
67 }
68
69 bool isRegInGprb(Register Reg) const;
70 bool isRegInFprb(Register Reg) const;
71 bool isWorthFoldingAdd(Register AddResult) const;
72
73 // tblgen-erated 'select' implementation, used as the initial selector for
74 // the patterns that don't require complex C++.
75 bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
76
77 // A lowering phase that runs before any selection attempts.
78 // Returns true if the instruction was modified.
79 void preISelLower(MachineInstr &MI);
80
81 bool replacePtrWithInt(MachineInstr &MI, unsigned OpIdx);
82
83 // Custom selection methods
84 bool selectCopy(MachineInstr &MI) const;
85 bool selectImplicitDef(MachineInstr &MI) const;
86 bool materializeImm(Register Reg, int64_t Imm, MachineInstr &MI) const;
87 // Emit a constant-materialization instruction sequence.
88 bool materializeInstSeq(Register DstReg, const RISCVMatInt::InstSeq &Seq,
89 MachineInstr &MI) const;
90 bool selectAddr(MachineInstr &MI, bool IsLocal = true,
91 bool IsExternWeak = false) const;
92 bool selectSelect(MachineInstr &MI) const;
93 bool selectFPCompare(MachineInstr &MI) const;
94 void emitFence(AtomicOrdering FenceOrdering, SyncScope::ID FenceSSID,
95 MachineInstr &MI) const;
98 void addVectorLoadStoreOperands(MachineInstr &I,
100 unsigned &CurOp, bool IsMasked,
101 bool IsStridedOrIndexed,
102 LLT *IndexVT = nullptr) const;
103 bool selectIntrinsicWithSideEffects(MachineInstr &I) const;
104 bool selectIntrinsic(MachineInstr &I) const;
105 bool selectExtractSubvector(MachineInstr &MI) const;
106 bool selectSplatVector(MachineInstr &MI);
107 bool selectInsertSubVector(MachineInstr &I) const;
108 ComplexRendererFns selectShiftMask(MachineOperand &Root,
109 unsigned ShiftWidth) const;
110 ComplexRendererFns selectShiftMaskXLen(MachineOperand &Root) const {
111 return selectShiftMask(Root, STI.getXLen());
112 }
113 ComplexRendererFns selectShiftMask32(MachineOperand &Root) const {
114 return selectShiftMask(Root, 32);
115 }
116 ComplexRendererFns selectAddrRegImm(MachineOperand &Root) const;
117 ComplexRendererFns selectBrindRegImm(MachineOperand &Root) const;
118 ComplexRendererFns selectAddrRegImmLsb00000(MachineOperand &Root) const;
119
120 // Plan for materializing a constant address as (Hi materialization, Lo12
121 // offset). Lo12 is a simm12 that, for prefetch (IsPrefetch), must be
122 // a multiple of 32.
123 struct ConstAddrPlan {
124 enum { X0, LUI, InstSeq } Kind = X0;
125 int64_t Hi20 = 0;
127 int64_t Lo12 = 0;
128 };
129 ComplexRendererFns computeConstAddr(int64_t CVal, bool IsPrefetch,
130 Register OrigBase) const;
131 // Materialize the high part of Plan into a register. If OrigBase is valid,
132 // ADD it to the materialized high part (for G_PTR_ADD + large constant).
133 Register materializeConstBase(MachineInstrBuilder &MIB,
134 const ConstAddrPlan &Plan,
135 Register OrigBase) const;
136
137 ComplexRendererFns selectSExtBits(MachineOperand &Root, unsigned Bits) const;
138 template <unsigned Bits>
139 ComplexRendererFns selectSExtBits(MachineOperand &Root) const {
140 return selectSExtBits(Root, Bits);
141 }
142
143 ComplexRendererFns selectZExtBits(MachineOperand &Root, unsigned Bits) const;
144 template <unsigned Bits>
145 ComplexRendererFns selectZExtBits(MachineOperand &Root) const {
146 return selectZExtBits(Root, Bits);
147 }
148
149 ComplexRendererFns selectSHXADDOp(MachineOperand &Root, unsigned ShAmt) const;
150 template <unsigned ShAmt>
151 ComplexRendererFns selectSHXADDOp(MachineOperand &Root) const {
152 return selectSHXADDOp(Root, ShAmt);
153 }
154
155 ComplexRendererFns selectSHXADD_UWOp(MachineOperand &Root,
156 unsigned ShAmt) const;
157 template <unsigned ShAmt>
158 ComplexRendererFns selectSHXADD_UWOp(MachineOperand &Root) const {
159 return selectSHXADD_UWOp(Root, ShAmt);
160 }
161
162 ComplexRendererFns renderVLOp(MachineOperand &Root) const;
163 ComplexRendererFns renderAddiPair(Register BaseReg, int64_t AddiImm,
164 int64_t OffsetImm) const;
165 // Custom renderers for tablegen
166 void renderNegImm(MachineInstrBuilder &MIB, const MachineInstr &MI,
167 int OpIdx) const;
168 void renderImmSubFromXLen(MachineInstrBuilder &MIB, const MachineInstr &MI,
169 int OpIdx) const;
170 void renderImmSubFrom32(MachineInstrBuilder &MIB, const MachineInstr &MI,
171 int OpIdx) const;
172 void renderImmPlus1(MachineInstrBuilder &MIB, const MachineInstr &MI,
173 int OpIdx) const;
174
175 void renderTrailingZeros(MachineInstrBuilder &MIB, const MachineInstr &MI,
176 int OpIdx) const;
177 void renderXLenSubTrailingOnes(MachineInstrBuilder &MIB,
178 const MachineInstr &MI, int OpIdx) const;
179
180 void renderAddiPairImmLarge(MachineInstrBuilder &MIB, const MachineInstr &MI,
181 int OpIdx) const;
182 void renderAddiPairImmSmall(MachineInstrBuilder &MIB, const MachineInstr &MI,
183 int OpIdx) const;
184
185 const RISCVSubtarget &STI;
186 const RISCVInstrInfo &TII;
187 const RISCVRegisterInfo &TRI;
188 const RISCVRegisterBankInfo &RBI;
189 const RISCVTargetMachine &TM;
190
191 MachineRegisterInfo *MRI = nullptr;
192
193 // FIXME: This is necessary because DAGISel uses "Subtarget->" and GlobalISel
194 // uses "STI." in the code generated by TableGen. We need to unify the name of
195 // Subtarget variable.
196 const RISCVSubtarget *Subtarget = &STI;
197
198#define GET_GLOBALISEL_PREDICATES_DECL
199#include "RISCVGenGlobalISel.inc"
200#undef GET_GLOBALISEL_PREDICATES_DECL
201
202#define GET_GLOBALISEL_TEMPORARIES_DECL
203#include "RISCVGenGlobalISel.inc"
204#undef GET_GLOBALISEL_TEMPORARIES_DECL
205};
206
207} // end anonymous namespace
208
209#define GET_GLOBALISEL_IMPL
210#include "RISCVGenGlobalISel.inc"
211#undef GET_GLOBALISEL_IMPL
212
213RISCVInstructionSelector::RISCVInstructionSelector(
214 const RISCVTargetMachine &TM, const RISCVSubtarget &STI,
215 const RISCVRegisterBankInfo &RBI)
216 : STI(STI), TII(*STI.getInstrInfo()), TRI(*STI.getRegisterInfo()), RBI(RBI),
217 TM(TM),
218
220#include "RISCVGenGlobalISel.inc"
223#include "RISCVGenGlobalISel.inc"
225{
226}
227
228// Mimics optimizations in ISel and RISCVOptWInst Pass
229bool RISCVInstructionSelector::hasAllNBitUsers(const MachineInstr &MI,
230 unsigned Bits,
231 const unsigned Depth) const {
232
233 assert((MI.getOpcode() == TargetOpcode::G_ADD ||
234 MI.getOpcode() == TargetOpcode::G_SUB ||
235 MI.getOpcode() == TargetOpcode::G_MUL ||
236 MI.getOpcode() == TargetOpcode::G_SHL ||
237 MI.getOpcode() == TargetOpcode::G_LSHR ||
238 MI.getOpcode() == TargetOpcode::G_AND ||
239 MI.getOpcode() == TargetOpcode::G_OR ||
240 MI.getOpcode() == TargetOpcode::G_XOR ||
241 MI.getOpcode() == TargetOpcode::G_SEXT_INREG || Depth != 0) &&
242 "Unexpected opcode");
243
244 if (Depth >= RISCVInstructionSelector::MaxRecursionDepth)
245 return false;
246
247 auto DestReg = MI.getOperand(0).getReg();
248 for (auto &UserOp : MRI->use_nodbg_operands(DestReg)) {
249 assert(UserOp.getParent() && "UserOp must have a parent");
250 const MachineInstr &UserMI = *UserOp.getParent();
251 unsigned OpIdx = UserOp.getOperandNo();
252
253 switch (UserMI.getOpcode()) {
254 default:
255 return false;
256 case RISCV::ADDW:
257 case RISCV::ADDIW:
258 case RISCV::SUBW:
259 case RISCV::FCVT_D_W:
260 case RISCV::FCVT_S_W:
261 if (Bits >= 32)
262 break;
263 return false;
264 case RISCV::SLL:
265 case RISCV::SRA:
266 case RISCV::SRL:
267 // Shift amount operands only use log2(Xlen) bits.
268 if (OpIdx == 2 && Bits >= Log2_32(Subtarget->getXLen()))
269 break;
270 return false;
271 case RISCV::SLLI:
272 // SLLI only uses the lower (XLen - ShAmt) bits.
273 if (Bits >= Subtarget->getXLen() - UserMI.getOperand(2).getImm())
274 break;
275 return false;
276 case RISCV::ANDI:
277 if (Bits >= (unsigned)llvm::bit_width<uint64_t>(
278 (uint64_t)UserMI.getOperand(2).getImm()))
279 break;
280 goto RecCheck;
281 case RISCV::AND:
282 case RISCV::OR:
283 case RISCV::XOR:
284 RecCheck:
285 if (hasAllNBitUsers(UserMI, Bits, Depth + 1))
286 break;
287 return false;
288 case RISCV::SRLI: {
289 unsigned ShAmt = UserMI.getOperand(2).getImm();
290 // If we are shifting right by less than Bits, and users don't demand any
291 // bits that were shifted into [Bits-1:0], then we can consider this as an
292 // N-Bit user.
293 if (Bits > ShAmt && hasAllNBitUsers(UserMI, Bits - ShAmt, Depth + 1))
294 break;
295 return false;
296 }
297 }
298 }
299
300 return true;
301}
302
303InstructionSelector::ComplexRendererFns
304RISCVInstructionSelector::selectShiftMask(MachineOperand &Root,
305 unsigned ShiftWidth) const {
306 if (!Root.isReg())
307 return std::nullopt;
308
309 using namespace llvm::MIPatternMatch;
310
311 Register ShAmtReg = Root.getReg();
312 // Peek through zext.
313 Register ZExtSrcReg;
314 if (mi_match(ShAmtReg, *MRI, m_GZExt(m_Reg(ZExtSrcReg))))
315 ShAmtReg = ZExtSrcReg;
316
317 APInt AndMask;
318 Register AndSrcReg;
319 // Try to combine the following pattern (applicable to other shift
320 // instructions as well as 32-bit ones):
321 //
322 // %4:gprb(s64) = G_AND %3, %2
323 // %5:gprb(s64) = G_LSHR %1, %4(s64)
324 //
325 // According to RISC-V's ISA manual, SLL, SRL, and SRA ignore other bits than
326 // the lowest log2(XLEN) bits of register rs2. As for the above pattern, if
327 // the lowest log2(XLEN) bits of register rd and rs2 of G_AND are the same,
328 // then it can be eliminated. Given register rs1 or rs2 holding a constant
329 // (the and mask), there are two cases G_AND can be erased:
330 //
331 // 1. the lowest log2(XLEN) bits of the and mask are all set
332 // 2. the bits of the register being masked are already unset (zero set)
333 if (mi_match(ShAmtReg, *MRI, m_GAnd(m_Reg(AndSrcReg), m_ICst(AndMask)))) {
334 APInt ShMask(AndMask.getBitWidth(), ShiftWidth - 1);
335 if (ShMask.isSubsetOf(AndMask)) {
336 ShAmtReg = AndSrcReg;
337 } else {
338 // SimplifyDemandedBits may have optimized the mask so try restoring any
339 // bits that are known zero.
340 KnownBits Known = VT->getKnownBits(AndSrcReg);
341 if (ShMask.isSubsetOf(AndMask | Known.Zero))
342 ShAmtReg = AndSrcReg;
343 }
344 }
345
346 APInt Imm;
348 if (mi_match(ShAmtReg, *MRI, m_GAdd(m_Reg(Reg), m_ICst(Imm)))) {
349 if (Imm != 0 && Imm.urem(ShiftWidth) == 0)
350 // If we are shifting by X+N where N == 0 mod Size, then just shift by X
351 // to avoid the ADD.
352 ShAmtReg = Reg;
353 } else if (mi_match(ShAmtReg, *MRI, m_GSub(m_ICst(Imm), m_Reg(Reg)))) {
354 if (Imm != 0 && Imm.urem(ShiftWidth) == 0) {
355 // If we are shifting by N-X where N == 0 mod Size, then just shift by -X
356 // to generate a NEG instead of a SUB of a constant.
357 ShAmtReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
358 unsigned NegOpc = Subtarget->is64Bit() ? RISCV::SUBW : RISCV::SUB;
359 return {{[=](MachineInstrBuilder &MIB) {
360 MachineIRBuilder(*MIB.getInstr())
361 .buildInstr(NegOpc, {ShAmtReg}, {Register(RISCV::X0), Reg});
362 MIB.addReg(ShAmtReg);
363 }}};
364 }
365 if (Imm.urem(ShiftWidth) == ShiftWidth - 1) {
366 // If we are shifting by N-X where N == -1 mod Size, then just shift by ~X
367 // to generate a NOT instead of a SUB of a constant.
368 ShAmtReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
369 return {{[=](MachineInstrBuilder &MIB) {
370 MachineIRBuilder(*MIB.getInstr())
371 .buildInstr(RISCV::XORI, {ShAmtReg}, {Reg})
372 .addImm(-1);
373 MIB.addReg(ShAmtReg);
374 }}};
375 }
376 }
377
378 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(ShAmtReg); }}};
379}
380
381InstructionSelector::ComplexRendererFns
382RISCVInstructionSelector::selectSExtBits(MachineOperand &Root,
383 unsigned Bits) const {
384 if (!Root.isReg())
385 return std::nullopt;
386 Register RootReg = Root.getReg();
387
388 Register SrcReg;
389 if (mi_match(RootReg, *MRI,
390 m_GSExtInReg(m_Reg(SrcReg), m_SpecificImm(Bits)))) {
391 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(SrcReg); }}};
392 }
393
394 unsigned Size = MRI->getType(RootReg).getScalarSizeInBits();
395 if ((Size - VT->computeNumSignBits(RootReg)) < Bits)
396 return {{[=](MachineInstrBuilder &MIB) { MIB.add(Root); }}};
397
398 return std::nullopt;
399}
400
401InstructionSelector::ComplexRendererFns
402RISCVInstructionSelector::selectZExtBits(MachineOperand &Root,
403 unsigned Bits) const {
404 if (!Root.isReg())
405 return std::nullopt;
406 Register RootReg = Root.getReg();
407
408 Register RegX;
410 if (mi_match(RootReg, *MRI, m_GAnd(m_Reg(RegX), m_SpecificICst(Mask)))) {
411 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(RegX); }}};
412 }
413
414 if (mi_match(RootReg, *MRI, m_GZExt(m_Reg(RegX))) &&
415 MRI->getType(RegX).getScalarSizeInBits() == Bits)
416 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(RegX); }}};
417
418 unsigned Size = MRI->getType(RootReg).getScalarSizeInBits();
419 if (VT->maskedValueIsZero(RootReg, APInt::getBitsSetFrom(Size, Bits)))
420 return {{[=](MachineInstrBuilder &MIB) { MIB.add(Root); }}};
421
422 return std::nullopt;
423}
424
425InstructionSelector::ComplexRendererFns
426RISCVInstructionSelector::selectSHXADDOp(MachineOperand &Root,
427 unsigned ShAmt) const {
428 using namespace llvm::MIPatternMatch;
429
430 if (!Root.isReg())
431 return std::nullopt;
432 Register RootReg = Root.getReg();
433
434 const unsigned XLen = STI.getXLen();
435 APInt Mask;
436 int64_t C2;
437 Register RegY;
438 std::optional<bool> LeftShift;
439 // (and (shl y, c2), mask)
440 if (mi_match(RootReg, *MRI,
441 m_GAnd(m_GShl(m_Reg(RegY), m_ICst(C2)), m_ICst(Mask))))
442 LeftShift = true;
443 // (and (lshr y, c2), mask)
444 else if (mi_match(RootReg, *MRI,
445 m_GAnd(m_GLShr(m_Reg(RegY), m_ICst(C2)), m_ICst(Mask))))
446 LeftShift = false;
447
448 if (LeftShift.has_value()) {
449 assert(Mask.getBitWidth() == XLen && "Unexpected mask size!");
450 assert(C2 > 0 && C2 < XLen && "Unexpected shift amount!");
451 if (*LeftShift)
453 else
454 Mask &= maskTrailingOnes<uint64_t>(XLen - C2);
455
456 if (Mask.isShiftedMask()) {
457 unsigned Leading = XLen - Mask.getActiveBits();
458 unsigned Trailing = Mask.countr_zero();
459 // Given (and (shl y, c2), mask) in which mask has no leading zeros and
460 // c3 trailing zeros. We can use an SRLI by c3 - c2 followed by a SHXADD.
461 if (*LeftShift && Leading == 0 && C2 < Trailing && Trailing == ShAmt) {
462 Register DstReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
463 return {{[=](MachineInstrBuilder &MIB) {
464 MachineIRBuilder(*MIB.getInstr())
465 .buildInstr(RISCV::SRLI, {DstReg}, {RegY})
466 .addImm(Trailing - C2);
467 MIB.addReg(DstReg);
468 }}};
469 }
470
471 // Given (and (lshr y, c2), mask) in which mask has c2 leading zeros and
472 // c3 trailing zeros. We can use an SRLI by c2 + c3 followed by a SHXADD.
473 if (!*LeftShift && Leading == C2 && Trailing == ShAmt) {
474 Register DstReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
475 return {{[=](MachineInstrBuilder &MIB) {
476 MachineIRBuilder(*MIB.getInstr())
477 .buildInstr(RISCV::SRLI, {DstReg}, {RegY})
478 .addImm(Leading + Trailing);
479 MIB.addReg(DstReg);
480 }}};
481 }
482 }
483 }
484
485 LeftShift.reset();
486
487 // (shl (and y, mask), c2)
488 if (mi_match(RootReg, *MRI,
489 m_GShl(m_OneUse(m_GAnd(m_Reg(RegY), m_ICst(Mask))), m_ICst(C2))))
490 LeftShift = true;
491 // (lshr (and y, mask), c2)
492 else if (mi_match(RootReg, *MRI,
493 m_GLShr(m_OneUse(m_GAnd(m_Reg(RegY), m_ICst(Mask))),
494 m_ICst(C2))))
495 LeftShift = false;
496
497 if (LeftShift.has_value() && Mask.isShiftedMask()) {
498 unsigned Leading = XLen - Mask.getActiveBits();
499 unsigned Trailing = Mask.countr_zero();
500
501 // Given (shl (and y, mask), c2) in which mask has 32 leading zeros and
502 // c3 trailing zeros. If c1 + c3 == ShAmt, we can emit SRLIW + SHXADD.
503 bool Cond =
504 *LeftShift && Leading == 32 && Trailing > 0 && (Trailing + C2) == ShAmt;
505 if (!Cond)
506 // Given (lshr (and y, mask), c2) in which mask has 32 leading zeros and
507 // c3 trailing zeros. If c3 - c1 == ShAmt, we can emit SRLIW + SHXADD.
508 Cond = !*LeftShift && Leading == 32 && C2 < Trailing &&
509 (Trailing - C2) == ShAmt;
510
511 if (Cond) {
512 Register DstReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
513 return {{[=](MachineInstrBuilder &MIB) {
514 MachineIRBuilder(*MIB.getInstr())
515 .buildInstr(RISCV::SRLIW, {DstReg}, {RegY})
516 .addImm(Trailing);
517 MIB.addReg(DstReg);
518 }}};
519 }
520 }
521
522 return std::nullopt;
523}
524
525InstructionSelector::ComplexRendererFns
526RISCVInstructionSelector::selectSHXADD_UWOp(MachineOperand &Root,
527 unsigned ShAmt) const {
528 using namespace llvm::MIPatternMatch;
529
530 if (!Root.isReg())
531 return std::nullopt;
532 Register RootReg = Root.getReg();
533
534 // Given (and (shl x, c2), mask) in which mask is a shifted mask with
535 // 32 - ShAmt leading zeros and c2 trailing zeros. We can use SLLI by
536 // c2 - ShAmt followed by SHXADD_UW with ShAmt for x amount.
537 APInt Mask;
538 int64_t C2;
539 Register RegX;
540 if (mi_match(RootReg, *MRI,
542 m_ICst(Mask))))) {
543 assert(C2 > 0 && C2 < Mask.getBitWidth() && "Unexpected shift amount!");
545
546 if (Mask.isShiftedMask()) {
547 unsigned Leading = Mask.countl_zero();
548 unsigned Trailing = Mask.countr_zero();
549 if (Leading == 32 - ShAmt && C2 == Trailing && Trailing > ShAmt) {
550 Register DstReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
551 return {{[=](MachineInstrBuilder &MIB) {
552 MachineIRBuilder(*MIB.getInstr())
553 .buildInstr(RISCV::SLLI, {DstReg}, {RegX})
554 .addImm(C2 - ShAmt);
555 MIB.addReg(DstReg);
556 }}};
557 }
558 }
559 }
560
561 return std::nullopt;
562}
563
564InstructionSelector::ComplexRendererFns
565RISCVInstructionSelector::renderVLOp(MachineOperand &Root) const {
566 assert(Root.isReg() && "Expected operand to be a Register");
567 std::optional<ValueAndVReg> C;
568 if (mi_match(Root.getReg(), *MRI, m_GCst(C))) {
569 if (C->Value.isAllOnes())
570 // If the operand is a G_CONSTANT with value of all ones it is larger than
571 // VLMAX. We convert it to an immediate with value VLMaxSentinel. This is
572 // recognized specially by the vsetvli insertion pass.
573 return {{[=](MachineInstrBuilder &MIB) {
574 MIB.addImm(RISCV::VLMaxSentinel);
575 }}};
576
577 if (isUInt<5>(C->Value.getZExtValue())) {
578 uint64_t ZExtC = C->Value.getZExtValue();
579 return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(ZExtC); }}};
580 }
581 }
582 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Root.getReg()); }}};
583}
584
585InstructionSelector::ComplexRendererFns
586RISCVInstructionSelector::renderAddiPair(Register BaseReg, int64_t AddiImm,
587 int64_t OffsetImm) const {
588 return {{[=](MachineInstrBuilder &MIB) {
589 Register Tmp = MRI->createVirtualRegister(&RISCV::GPRRegClass);
590 MachineInstr *Addi =
591 BuildMI(*MIB->getParent(), *MIB.getInstr(), MIB->getDebugLoc(),
592 TII.get(RISCV::ADDI), Tmp)
593 .addReg(BaseReg)
594 .addImm(AddiImm);
596 MIB.addReg(Tmp);
597 },
598 [=](MachineInstrBuilder &MIB) { MIB.addImm(OffsetImm); }}};
599}
600
601InstructionSelector::ComplexRendererFns
602RISCVInstructionSelector::selectAddrRegImm(MachineOperand &Root) const {
603 if (!Root.isReg())
604 return std::nullopt;
605
606 Register RootReg = Root.getReg();
607
608 // Frame index.
609 int FI;
610 if (mi_match(RootReg, *MRI, m_GFrameIndex(FI))) {
611 return {{
612 [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(FI); },
613 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
614 }};
615 }
616
617 // base + constant offset (G_PTR_ADD).
619 int64_t RHSC;
620 if (mi_match(RootReg, *MRI, m_GPtrAdd(m_Reg(BaseReg), m_ICst(RHSC)))) {
621 if (isInt<12>(RHSC)) {
622 int BaseFI;
623 if (mi_match(BaseReg, *MRI, m_GFrameIndex(BaseFI)))
624 return {{
625 [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(BaseFI); },
626 [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); },
627 }};
628
629 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(BaseReg); },
630 [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); }}};
631 }
632
633 // Large constant offset. Fold a -2048/2047 adjustment so the whole
634 // constant can be split across an ADDI and the load/store offset.
635 if (RHSC >= -4096 && RHSC <= 4094) {
636 int64_t Adj = RHSC < 0 ? -2048 : 2047;
637 return renderAddiPair(BaseReg, Adj, RHSC - Adj);
638 }
639
640 if (isWorthFoldingAdd(RootReg))
641 if (auto Fns = computeConstAddr(RHSC, /*IsPrefetch=*/false, BaseReg))
642 return Fns;
643 }
644
645 // Bare constant address. IRTranslator lowers inttoptr(C) to
646 // G_INTTOPTR(G_CONSTANT); look through it to reach the constant.
647 int64_t CVal;
648 if (mi_match(RootReg, *MRI, m_GIntToPtr(m_ICst(CVal))) ||
649 mi_match(RootReg, *MRI, m_ICst(CVal))) {
650 if (auto Fns = computeConstAddr(CVal, /*IsPrefetch=*/false, Register()))
651 return Fns;
652 }
653
654 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(RootReg); },
655 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }}};
656}
657
658InstructionSelector::ComplexRendererFns
659RISCVInstructionSelector::selectBrindRegImm(MachineOperand &Root) const {
660 if (!Root.isReg())
661 return std::nullopt;
662
663 Register RootReg = Root.getReg();
664
665 // base + constant offset (G_PTR_ADD). Doesn't match a FrameIndex, unlike
666 // selectAddrRegImm, since the callers of this (e.g. indirect branches)
667 // can't take a FrameIndex or global address operand.
669 int64_t RHSC;
670 if (mi_match(RootReg, *MRI, m_GPtrAdd(m_Reg(BaseReg), m_ICst(RHSC))) &&
671 isInt<12>(RHSC)) {
672 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(BaseReg); },
673 [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); }}};
674 }
675
676 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(RootReg); },
677 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }}};
678}
679
680InstructionSelector::ComplexRendererFns
681RISCVInstructionSelector::selectAddrRegImmLsb00000(MachineOperand &Root) const {
682 if (!Root.isReg())
683 return std::nullopt;
684
685 Register RootReg = Root.getReg();
686
687 // Frame index.
688 int FI;
689 if (mi_match(RootReg, *MRI, m_GFrameIndex(FI))) {
690 return {{
691 [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(FI); },
692 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
693 }};
694 }
695
696 // base + constant offset (G_PTR_ADD).
698 int64_t RHSC;
699 if (mi_match(RootReg, *MRI, m_GPtrAdd(m_Reg(BaseReg), m_ICst(RHSC)))) {
700 if (isInt<12>(RHSC)) {
701 // Not a multiple of 32: can't encode, use the address as-is.
702 if ((RHSC & 0b11111) != 0) {
703 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(RootReg); },
704 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }}};
705 }
706 // Fold the offset.
707 int BaseFI;
708 if (mi_match(BaseReg, *MRI, m_GFrameIndex(BaseFI)))
709 return {{
710 [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(BaseFI); },
711 [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); },
712 }};
713 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(BaseReg); },
714 [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); }}};
715 }
716
717 // Large constant: fold a -2048/2016 adjustment to save an instruction.
718 if ((-2049 >= RHSC && RHSC >= -4096) || (4063 >= RHSC && RHSC >= 2017)) {
719 int64_t Adj = RHSC < 0 ? -2048 : 2016;
720 return renderAddiPair(BaseReg, RHSC - Adj, Adj);
721 }
722
723 // Otherwise split the constant into Hi (materialized + added to the base)
724 // and Lo12 (folded offset).
725 if (auto Fns = computeConstAddr(RHSC, /*IsPrefetch=*/true, BaseReg))
726 return Fns;
727 }
728
729 // Bare constant address. IRTranslator emits inttoptr(C) as
730 // G_INTTOPTR(G_CONSTANT); look through the G_INTTOPTR to reach the constant.
731 int64_t CVal;
732 if (mi_match(RootReg, *MRI, m_GIntToPtr(m_ICst(CVal))) ||
733 mi_match(RootReg, *MRI, m_ICst(CVal))) {
734 if (auto Fns = computeConstAddr(CVal, /*IsPrefetch=*/true, Register()))
735 return Fns;
736 }
737
738 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(RootReg); },
739 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }}};
740}
741
742/// Returns the RISCVCC::CondCode that corresponds to the CmpInst::Predicate CC.
743/// CC Must be an ICMP Predicate.
744static RISCVCC::CondCode getRISCVCCFromICmp(CmpInst::Predicate CC) {
745 switch (CC) {
746 default:
747 llvm_unreachable("Expected ICMP CmpInst::Predicate.");
748 case CmpInst::Predicate::ICMP_EQ:
749 return RISCVCC::COND_EQ;
750 case CmpInst::Predicate::ICMP_NE:
751 return RISCVCC::COND_NE;
752 case CmpInst::Predicate::ICMP_ULT:
753 return RISCVCC::COND_LTU;
754 case CmpInst::Predicate::ICMP_SLT:
755 return RISCVCC::COND_LT;
756 case CmpInst::Predicate::ICMP_UGE:
757 return RISCVCC::COND_GEU;
758 case CmpInst::Predicate::ICMP_SGE:
759 return RISCVCC::COND_GE;
760 }
761}
762
766 // Try to fold an ICmp. If that fails, use a NE compare with X0.
768 if (!mi_match(CondReg, MRI, m_GICmp(m_Pred(Pred), m_Reg(LHS), m_Reg(RHS)))) {
769 LHS = CondReg;
770 RHS = RISCV::X0;
772 return;
773 }
774
775 // We found an ICmp, do some canonicalization.
776
777 // Adjust comparisons to use comparison with 0 if possible.
779 switch (Pred) {
781 // Convert X > -1 to X >= 0
782 if (*Constant == -1) {
784 RHS = RISCV::X0;
785 return;
786 }
787 break;
789 // Convert X < 1 to 0 >= X
790 if (*Constant == 1) {
792 RHS = LHS;
793 LHS = RISCV::X0;
794 return;
795 }
796 break;
797 default:
798 break;
799 }
800 }
801
802 switch (Pred) {
803 default:
804 llvm_unreachable("Expected ICMP CmpInst::Predicate.");
811 // These CCs are supported directly by RISC-V branches.
812 break;
817 // These CCs are not supported directly by RISC-V branches, but changing the
818 // direction of the CC and swapping LHS and RHS are.
820 std::swap(LHS, RHS);
821 break;
822 }
823
824 CC = getRISCVCCFromICmp(Pred);
825}
826
827/// Select the RISC-V Zalasr opcode for the G_LOAD or G_STORE operation
828/// \p GenericOpc, appropriate for the GPR register bank and of memory access
829/// size \p OpSize.
830static unsigned selectZalasrLoadStoreOp(unsigned GenericOpc, unsigned OpSize) {
831 const bool IsStore = GenericOpc == TargetOpcode::G_STORE;
832 switch (OpSize) {
833 default:
834 llvm_unreachable("Unexpected memory size");
835 case 8:
836 return IsStore ? RISCV::SB_RL : RISCV::LB_AQ;
837 case 16:
838 return IsStore ? RISCV::SH_RL : RISCV::LH_AQ;
839 case 32:
840 return IsStore ? RISCV::SW_RL : RISCV::LW_AQ;
841 case 64:
842 return IsStore ? RISCV::SD_RL : RISCV::LD_AQ;
843 }
844}
845
846/// Select the RISC-V regimm opcode for the G_LOAD or G_STORE operation
847/// \p GenericOpc on \p STI, appropriate for the GPR register bank and of
848/// memory access size \p OpSize. \returns \p GenericOpc if the combination
849/// is unsupported.
850static unsigned selectRegImmLoadStoreOp(const RISCVSubtarget &STI,
851 unsigned GenericOpc, unsigned OpSize) {
852 const bool IsStore = GenericOpc == TargetOpcode::G_STORE;
853 switch (OpSize) {
854 case 8:
855 // Prefer unsigned due to no c.lb in Zcb.
856 return IsStore ? RISCV::SB : RISCV::LBU;
857 case 16:
858 return IsStore ? RISCV::SH : RISCV::LH;
859 case 32:
860 return IsStore ? RISCV::SW : RISCV::LW;
861 case 64:
862 // LD/SD are RV64-only. On RV32 a 64-bit access goes through an even/odd
863 // GPR pair, which Zilsd provides via the LD_RV32/SD_RV32 pseudos.
864 if (!STI.is64Bit() && STI.hasStdExtZilsd())
865 return IsStore ? RISCV::SD_RV32 : RISCV::LD_RV32;
866 return IsStore ? RISCV::SD : RISCV::LD;
867 }
868
869 return GenericOpc;
870}
871
872void RISCVInstructionSelector::addVectorLoadStoreOperands(
873 MachineInstr &I, SmallVectorImpl<Register> &SrcOps, unsigned &CurOp,
874 bool IsMasked, bool IsStridedOrIndexed, LLT *IndexVT) const {
875 // Base Pointer
876 auto PtrReg = I.getOperand(CurOp++).getReg();
877 SrcOps.push_back(PtrReg);
878
879 // Stride or Index
880 if (IsStridedOrIndexed) {
881 auto StrideReg = I.getOperand(CurOp++).getReg();
882 SrcOps.push_back(StrideReg);
883 if (IndexVT)
884 *IndexVT = MRI->getType(StrideReg);
885 }
886
887 // Mask
888 if (IsMasked) {
889 auto MaskReg = I.getOperand(CurOp++).getReg();
890 SrcOps.push_back(MaskReg);
891 }
892}
893
894bool RISCVInstructionSelector::selectIntrinsicWithSideEffects(
895 MachineInstr &I) const {
896 // Find the intrinsic ID.
897 unsigned IntrinID = cast<GIntrinsic>(I).getIntrinsicID();
898 // Select the instruction.
899 switch (IntrinID) {
900 default:
901 return false;
902 case Intrinsic::riscv_vlm:
903 case Intrinsic::riscv_vle:
904 case Intrinsic::riscv_vle_mask:
905 case Intrinsic::riscv_vlse:
906 case Intrinsic::riscv_vlse_mask: {
907 bool IsMasked = IntrinID == Intrinsic::riscv_vle_mask ||
908 IntrinID == Intrinsic::riscv_vlse_mask;
909 bool IsStrided = IntrinID == Intrinsic::riscv_vlse ||
910 IntrinID == Intrinsic::riscv_vlse_mask;
911 LLT VT = MRI->getType(I.getOperand(0).getReg());
912 unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
913
914 // Result vector
915 const Register DstReg = I.getOperand(0).getReg();
916
917 // Sources
918 bool HasPassthruOperand = IntrinID != Intrinsic::riscv_vlm;
919 unsigned CurOp = 2;
920 SmallVector<Register, 4> SrcOps; // Source registers.
921
922 // Passthru
923 if (HasPassthruOperand) {
924 auto PassthruReg = I.getOperand(CurOp++).getReg();
925 SrcOps.push_back(PassthruReg);
926 } else {
927 SrcOps.push_back(Register(RISCV::NoRegister));
928 }
929
930 addVectorLoadStoreOperands(I, SrcOps, CurOp, IsMasked, IsStrided);
931
933 const RISCV::VLEPseudo *P =
934 RISCV::getVLEPseudo(IsMasked, IsStrided, /*FF*/ false, Log2SEW,
935 static_cast<unsigned>(LMUL));
936
937 MachineInstrBuilder PseudoMI =
938 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(P->Pseudo), DstReg);
939 for (Register Reg : SrcOps)
940 PseudoMI.addReg(Reg);
941
942 // Select VL
943 auto VLOpFn = renderVLOp(I.getOperand(CurOp++));
944 for (auto &RenderFn : *VLOpFn)
945 RenderFn(PseudoMI);
946
947 // SEW
948 PseudoMI.addImm(Log2SEW);
949
950 // Policy
952 if (IsMasked)
953 Policy = I.getOperand(CurOp++).getImm();
954 PseudoMI.addImm(Policy);
955
956 // Memref
957 PseudoMI.cloneMemRefs(I);
958
959 I.eraseFromParent();
960 constrainSelectedInstRegOperands(*PseudoMI, TII, TRI, RBI);
961 return true;
962 }
963 case Intrinsic::riscv_vloxei:
964 case Intrinsic::riscv_vloxei_mask:
965 case Intrinsic::riscv_vluxei:
966 case Intrinsic::riscv_vluxei_mask: {
967 bool IsMasked = IntrinID == Intrinsic::riscv_vloxei_mask ||
968 IntrinID == Intrinsic::riscv_vluxei_mask;
969 bool IsOrdered = IntrinID == Intrinsic::riscv_vloxei ||
970 IntrinID == Intrinsic::riscv_vloxei_mask;
971 LLT VT = MRI->getType(I.getOperand(0).getReg());
972 unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
973
974 // Result vector
975 const Register DstReg = I.getOperand(0).getReg();
976
977 // Sources
978 bool HasPassthruOperand = IntrinID != Intrinsic::riscv_vlm;
979 unsigned CurOp = 2;
980 SmallVector<Register, 4> SrcOps; // Source registers.
981
982 // Passthru
983 if (HasPassthruOperand) {
984 auto PassthruReg = I.getOperand(CurOp++).getReg();
985 SrcOps.push_back(PassthruReg);
986 } else {
987 // Use NoRegister if there is no specified passthru.
988 SrcOps.push_back(Register());
989 }
990 LLT IndexVT;
991 addVectorLoadStoreOperands(I, SrcOps, CurOp, IsMasked, true, &IndexVT);
992
994 RISCVVType::VLMUL IndexLMUL =
996 unsigned IndexLog2EEW = Log2_32(IndexVT.getScalarSizeInBits());
997 if (IndexLog2EEW == 6 && !Subtarget->is64Bit()) {
998 reportFatalUsageError("The V extension does not support EEW=64 for index "
999 "values when XLEN=32");
1000 }
1001 const RISCV::VLX_VSXPseudo *P = RISCV::getVLXPseudo(
1002 IsMasked, IsOrdered, IndexLog2EEW, static_cast<unsigned>(LMUL),
1003 static_cast<unsigned>(IndexLMUL));
1004
1005 MachineInstrBuilder PseudoMI =
1006 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(P->Pseudo), DstReg);
1007 for (Register Reg : SrcOps)
1008 PseudoMI.addReg(Reg);
1009
1010 // Select VL
1011 auto VLOpFn = renderVLOp(I.getOperand(CurOp++));
1012 for (auto &RenderFn : *VLOpFn)
1013 RenderFn(PseudoMI);
1014
1015 // SEW
1016 PseudoMI.addImm(Log2SEW);
1017
1018 // Policy
1020 if (IsMasked)
1021 Policy = I.getOperand(CurOp++).getImm();
1022 PseudoMI.addImm(Policy);
1023
1024 // Memref
1025 PseudoMI.cloneMemRefs(I);
1026
1027 I.eraseFromParent();
1028 constrainSelectedInstRegOperands(*PseudoMI, TII, TRI, RBI);
1029 return true;
1030 }
1031 case Intrinsic::riscv_vsm:
1032 case Intrinsic::riscv_vse:
1033 case Intrinsic::riscv_vse_mask:
1034 case Intrinsic::riscv_vsse:
1035 case Intrinsic::riscv_vsse_mask: {
1036 bool IsMasked = IntrinID == Intrinsic::riscv_vse_mask ||
1037 IntrinID == Intrinsic::riscv_vsse_mask;
1038 bool IsStrided = IntrinID == Intrinsic::riscv_vsse ||
1039 IntrinID == Intrinsic::riscv_vsse_mask;
1040 LLT VT = MRI->getType(I.getOperand(1).getReg());
1041 unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1042
1043 // Sources
1044 unsigned CurOp = 1;
1045 SmallVector<Register, 4> SrcOps; // Source registers.
1046
1047 // Store value
1048 auto PassthruReg = I.getOperand(CurOp++).getReg();
1049 SrcOps.push_back(PassthruReg);
1050
1051 addVectorLoadStoreOperands(I, SrcOps, CurOp, IsMasked, IsStrided);
1052
1054 const RISCV::VSEPseudo *P = RISCV::getVSEPseudo(
1055 IsMasked, IsStrided, Log2SEW, static_cast<unsigned>(LMUL));
1056
1057 MachineInstrBuilder PseudoMI =
1058 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(P->Pseudo));
1059 for (Register Reg : SrcOps)
1060 PseudoMI.addReg(Reg);
1061
1062 // Select VL
1063 auto VLOpFn = renderVLOp(I.getOperand(CurOp++));
1064 for (auto &RenderFn : *VLOpFn)
1065 RenderFn(PseudoMI);
1066
1067 // SEW
1068 PseudoMI.addImm(Log2SEW);
1069
1070 // Memref
1071 PseudoMI.cloneMemRefs(I);
1072
1073 I.eraseFromParent();
1074 constrainSelectedInstRegOperands(*PseudoMI, TII, TRI, RBI);
1075 return true;
1076 }
1077 case Intrinsic::riscv_vsoxei:
1078 case Intrinsic::riscv_vsoxei_mask:
1079 case Intrinsic::riscv_vsuxei:
1080 case Intrinsic::riscv_vsuxei_mask: {
1081 bool IsMasked = IntrinID == Intrinsic::riscv_vsoxei_mask ||
1082 IntrinID == Intrinsic::riscv_vsuxei_mask;
1083 bool IsOrdered = IntrinID == Intrinsic::riscv_vsoxei ||
1084 IntrinID == Intrinsic::riscv_vsoxei_mask;
1085 LLT VT = MRI->getType(I.getOperand(1).getReg());
1086 unsigned Log2SEW = Log2_32(VT.getScalarSizeInBits());
1087
1088 // Sources
1089 unsigned CurOp = 1;
1090 SmallVector<Register, 4> SrcOps; // Source registers.
1091
1092 // Store value
1093 auto PassthruReg = I.getOperand(CurOp++).getReg();
1094 SrcOps.push_back(PassthruReg);
1095
1096 LLT IndexVT;
1097 addVectorLoadStoreOperands(I, SrcOps, CurOp, IsMasked, true, &IndexVT);
1098
1100 RISCVVType::VLMUL IndexLMUL =
1102 unsigned IndexLog2EEW = Log2_32(IndexVT.getScalarSizeInBits());
1103 if (IndexLog2EEW == 6 && !Subtarget->is64Bit()) {
1104 reportFatalUsageError("The V extension does not support EEW=64 for index "
1105 "values when XLEN=32");
1106 }
1107 const RISCV::VLX_VSXPseudo *P = RISCV::getVSXPseudo(
1108 IsMasked, IsOrdered, IndexLog2EEW, static_cast<unsigned>(LMUL),
1109 static_cast<unsigned>(IndexLMUL));
1110
1111 MachineInstrBuilder PseudoMI =
1112 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(P->Pseudo));
1113 for (Register Reg : SrcOps)
1114 PseudoMI.addReg(Reg);
1115
1116 // Select VL
1117 auto VLOpFn = renderVLOp(I.getOperand(CurOp++));
1118 for (auto &RenderFn : *VLOpFn)
1119 RenderFn(PseudoMI);
1120
1121 // SEW
1122 PseudoMI.addImm(Log2SEW);
1123
1124 // Memref
1125 PseudoMI.cloneMemRefs(I);
1126
1127 I.eraseFromParent();
1128 constrainSelectedInstRegOperands(*PseudoMI, TII, TRI, RBI);
1129 return true;
1130 }
1131 }
1132}
1133
1134bool RISCVInstructionSelector::selectIntrinsic(MachineInstr &I) const {
1135 // Find the intrinsic ID.
1136 unsigned IntrinID = cast<GIntrinsic>(I).getIntrinsicID();
1137 // Select the instruction.
1138 switch (IntrinID) {
1139 default:
1140 return false;
1141 case Intrinsic::riscv_vsetvli:
1142 case Intrinsic::riscv_vsetvlimax: {
1143
1144 bool VLMax = IntrinID == Intrinsic::riscv_vsetvlimax;
1145
1146 unsigned Offset = VLMax ? 2 : 3;
1147 unsigned SEW = RISCVVType::decodeVSEW(I.getOperand(Offset).getImm() & 0x7);
1148 RISCVVType::VLMUL VLMul =
1149 static_cast<RISCVVType::VLMUL>(I.getOperand(Offset + 1).getImm() & 0x7);
1150
1151 unsigned VTypeI = RISCVVType::encodeVTYPE(VLMul, SEW, /*TailAgnostic*/ true,
1152 /*MaskAgnostic*/ true);
1153
1154 Register DstReg = I.getOperand(0).getReg();
1155
1156 Register VLOperand;
1157 unsigned Opcode = RISCV::PseudoVSETVLI;
1158
1159 // Check if AVL is a constant that equals VLMAX.
1160 if (!VLMax) {
1161 Register AVLReg = I.getOperand(2).getReg();
1162 if (auto AVLConst = getIConstantVRegValWithLookThrough(AVLReg, *MRI)) {
1163 uint64_t AVL = AVLConst->Value.getZExtValue();
1164 if (auto VLEN = Subtarget->getRealVLen()) {
1165 if (*VLEN / RISCVVType::getSEWLMULRatio(SEW, VLMul) == AVL)
1166 VLMax = true;
1167 }
1168 }
1169
1170 if (mi_match(AVLReg, *MRI, m_AllOnes()))
1171 VLMax = true;
1172 }
1173
1174 if (VLMax) {
1175 VLOperand = Register(RISCV::X0);
1176 Opcode = RISCV::PseudoVSETVLIX0;
1177 } else {
1178 Register AVLReg = I.getOperand(2).getReg();
1179 VLOperand = AVLReg;
1180
1181 // Check if AVL is a small constant that can use PseudoVSETIVLI.
1182 if (auto AVLConst = getIConstantVRegValWithLookThrough(AVLReg, *MRI)) {
1183 uint64_t AVL = AVLConst->Value.getZExtValue();
1184 if (isUInt<5>(AVL)) {
1185 MachineInstr *PseudoMI =
1186 BuildMI(*I.getParent(), I, I.getDebugLoc(),
1187 TII.get(RISCV::PseudoVSETIVLI), DstReg)
1188 .addImm(AVL)
1189 .addImm(VTypeI);
1190 I.eraseFromParent();
1191 constrainSelectedInstRegOperands(*PseudoMI, TII, TRI, RBI);
1192 return true;
1193 }
1194 }
1195 }
1196
1197 MachineInstr *PseudoMI =
1198 BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcode), DstReg)
1199 .addReg(VLOperand)
1200 .addImm(VTypeI);
1201 I.eraseFromParent();
1202 constrainSelectedInstRegOperands(*PseudoMI, TII, TRI, RBI);
1203 return true;
1204 }
1205 }
1206}
1207
1208bool RISCVInstructionSelector::selectSplatVector(MachineInstr &MI) {
1209 Register DstReg = MI.getOperand(0).getReg();
1210 Register ScalarReg = MI.getOperand(1).getReg();
1211
1212 // Only integer splats for now. FP splats (scalar on FPRB) need vfmv.v.f.
1213 if (RBI.getRegBank(ScalarReg, *MRI, TRI)->getID() != RISCV::GPRBRegBankID)
1214 return false;
1215
1216 // Lower to G_VMV_V_X_VL with an undef passthru and VL = VLMAX, as
1217 // RISCVDAGToDAGISel::PreprocessISelDAG does for SPLAT_VECTOR.
1218 MachineIRBuilder MIB(MI);
1219 LLT VecTy = MRI->getType(DstReg);
1220 auto Passthru = MIB.buildUndef(VecTy);
1221 MRI->setRegBank(Passthru.getReg(0), RBI.getRegBank(RISCV::VRBRegBankID));
1222 auto VL = MIB.buildConstant(LLT::integer(STI.getXLen()), -1);
1223 MRI->setRegBank(VL.getReg(0), RBI.getRegBank(RISCV::GPRBRegBankID));
1224 auto Vmv =
1225 MIB.buildInstr(RISCV::G_VMV_V_X_VL, {DstReg}, {Passthru, ScalarReg, VL});
1226 MI.eraseFromParent();
1227
1228 // Select the splat while VL is still a G_CONSTANT, so renderVLOp turns it
1229 // into VLMAX. The constant is then unused and can be removed.
1230 if (!selectImpl(*Vmv.getInstr(), *CoverageInfo))
1231 return false;
1232 assert(MRI->use_nodbg_empty(VL.getReg(0)) && "Expected VL to become VLMAX");
1233 VL->eraseFromParent();
1234 return selectImplicitDef(*Passthru.getInstr());
1235}
1236
1237bool RISCVInstructionSelector::selectExtractSubvector(MachineInstr &MI) const {
1238 assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_SUBVECTOR);
1239
1240 Register DstReg = MI.getOperand(0).getReg();
1241 Register SrcReg = MI.getOperand(1).getReg();
1242
1243 LLT DstTy = MRI->getType(DstReg);
1244 LLT SrcTy = MRI->getType(SrcReg);
1245
1246 unsigned Idx = static_cast<unsigned>(MI.getOperand(2).getImm());
1247
1248 MVT DstMVT = getMVTForLLT(DstTy);
1249 MVT SrcMVT = getMVTForLLT(SrcTy);
1250
1251 unsigned SubRegIdx;
1252 std::tie(SubRegIdx, Idx) =
1254 SrcMVT, DstMVT, Idx, &TRI);
1255
1256 if (Idx != 0)
1257 return false;
1258
1259 unsigned DstRegClassID = RISCVTargetLowering::getRegClassIDForVecVT(DstMVT);
1260 const TargetRegisterClass *DstRC = TRI.getRegClass(DstRegClassID);
1261 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
1262 return false;
1263
1264 unsigned SrcRegClassID = RISCVTargetLowering::getRegClassIDForVecVT(SrcMVT);
1265 const TargetRegisterClass *SrcRC = TRI.getRegClass(SrcRegClassID);
1266 if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
1267 return false;
1268
1269 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII.get(TargetOpcode::COPY),
1270 DstReg)
1271 .addReg(SrcReg, {}, SubRegIdx);
1272
1273 MI.eraseFromParent();
1274 return true;
1275}
1276
1277bool RISCVInstructionSelector::selectInsertSubVector(MachineInstr &MI) const {
1278 assert(MI.getOpcode() == TargetOpcode::G_INSERT_SUBVECTOR);
1279
1280 Register DstReg = MI.getOperand(0).getReg();
1281 Register VecReg = MI.getOperand(1).getReg();
1282 Register SubVecReg = MI.getOperand(2).getReg();
1283
1284 LLT VecTy = MRI->getType(VecReg);
1285 LLT SubVecTy = MRI->getType(SubVecReg);
1286
1287 MVT VecMVT = getMVTForLLT(VecTy);
1288 MVT SubVecMVT = getMVTForLLT(SubVecTy);
1289
1290 unsigned Idx = static_cast<unsigned>(MI.getOperand(3).getImm());
1291
1292 unsigned SubRegIdx;
1293 std::tie(SubRegIdx, Idx) =
1295 VecMVT, SubVecMVT, Idx, &TRI);
1296
1297 // If the Idx hasn't been completely eliminated then this is a subvector
1298 // insert which doesn't naturally align to a vector register. These must
1299 // be handled using instructions to manipulate the vector registers.
1300 if (Idx != 0)
1301 return false;
1302
1303 // Constrain dst
1304 unsigned DstRegClassID = RISCVTargetLowering::getRegClassIDForVecVT(VecMVT);
1305 const TargetRegisterClass *DstRC = TRI.getRegClass(DstRegClassID);
1306 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
1307 return false;
1308
1309 // If we haven't set a SubRegIdx, then we must be going between
1310 // equally-sized LMUL groups (e.g. VR -> VR). This can be done as a copy.
1311 if (SubRegIdx == RISCV::NoSubRegister) {
1313 DstRegClassID &&
1314 "Unexpected subvector insert");
1315 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII.get(TargetOpcode::COPY),
1316 DstReg)
1317 .addReg(SubVecReg);
1318 MI.eraseFromParent();
1319 return true;
1320 }
1321
1322 // Use INSERT_SUBREG to insert the subvector into the vector at the
1323 // appropriate subregister index.
1324 MachineInstr *Ins = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1325 TII.get(TargetOpcode::INSERT_SUBREG), DstReg)
1326 .addReg(VecReg)
1327 .addReg(SubVecReg)
1328 .addImm(SubRegIdx);
1329
1330 MI.eraseFromParent();
1332 return true;
1333}
1334
1335bool RISCVInstructionSelector::select(MachineInstr &MI) {
1336 preISelLower(MI);
1337 const unsigned Opc = MI.getOpcode();
1338
1339 if (!MI.isPreISelOpcode() || Opc == TargetOpcode::G_PHI) {
1340 if (Opc == TargetOpcode::PHI || Opc == TargetOpcode::G_PHI) {
1341 const Register DefReg = MI.getOperand(0).getReg();
1342 const LLT DefTy = MRI->getType(DefReg);
1343
1344 const RegClassOrRegBank &RegClassOrBank =
1345 MRI->getRegClassOrRegBank(DefReg);
1346
1347 const TargetRegisterClass *DefRC =
1349 if (!DefRC) {
1350 if (!DefTy.isValid()) {
1351 LLVM_DEBUG(dbgs() << "PHI operand has no type, not a gvreg?\n");
1352 return false;
1353 }
1354
1355 const RegisterBank &RB = *cast<const RegisterBank *>(RegClassOrBank);
1356 DefRC = TRI.getRegClassForTypeOnBank(DefTy, RB, STI.is64Bit());
1357 if (!DefRC) {
1358 LLVM_DEBUG(dbgs() << "PHI operand has unexpected size/bank\n");
1359 return false;
1360 }
1361 }
1362
1363 MI.setDesc(TII.get(TargetOpcode::PHI));
1364 return RBI.constrainGenericRegister(DefReg, *DefRC, *MRI);
1365 }
1366
1367 // Certain non-generic instructions also need some special handling.
1368 if (MI.isCopy())
1369 return selectCopy(MI);
1370
1371 return true;
1372 }
1373
1374 if (selectImpl(MI, *CoverageInfo))
1375 return true;
1376
1377 switch (Opc) {
1378 case TargetOpcode::G_BITCAST:
1379 case TargetOpcode::G_ANYEXT:
1380 case TargetOpcode::G_PTRTOINT:
1381 case TargetOpcode::G_INTTOPTR:
1382 case TargetOpcode::G_TRUNC:
1383 case TargetOpcode::G_FREEZE:
1384 return selectCopy(MI);
1385 case TargetOpcode::G_CONSTANT: {
1386 Register DstReg = MI.getOperand(0).getReg();
1387 int64_t Imm = MI.getOperand(1).getCImm()->getSExtValue();
1388
1389 if (!materializeImm(DstReg, Imm, MI))
1390 return false;
1391
1392 MI.eraseFromParent();
1393 return true;
1394 }
1395 case TargetOpcode::G_ZEXT:
1396 case TargetOpcode::G_SEXT: {
1397 bool IsSigned = Opc != TargetOpcode::G_ZEXT;
1398 Register DstReg = MI.getOperand(0).getReg();
1399 Register SrcReg = MI.getOperand(1).getReg();
1400 LLT SrcTy = MRI->getType(SrcReg);
1401 unsigned SrcSize = SrcTy.getSizeInBits();
1402
1403 if (SrcTy.isVector())
1404 return false; // Should be handled by imported patterns.
1405
1406 assert((*RBI.getRegBank(DstReg, *MRI, TRI)).getID() ==
1407 RISCV::GPRBRegBankID &&
1408 "Unexpected ext regbank");
1409
1410 // Use addiw SrcReg, 0 (sext.w) for i32.
1411 if (IsSigned && SrcSize == 32) {
1412 MI.setDesc(TII.get(RISCV::ADDIW));
1413 MI.addOperand(MachineOperand::CreateImm(0));
1415 return true;
1416 }
1417
1418 // Use add.uw SrcReg, X0 (zext.w) for i32 with Zba.
1419 if (!IsSigned && SrcSize == 32 && STI.hasStdExtZba()) {
1420 MI.setDesc(TII.get(RISCV::ADD_UW));
1421 MI.addOperand(MachineOperand::CreateReg(RISCV::X0, /*isDef=*/false));
1423 return true;
1424 }
1425
1426 // Use sext.h/zext.h for i16 with Zbb.
1427 if (SrcSize == 16 &&
1428 (STI.hasStdExtZbb() || (!IsSigned && STI.hasStdExtZbkb()))) {
1429 MI.setDesc(TII.get(IsSigned ? RISCV::SEXT_H
1430 : STI.is64Bit() ? RISCV::ZEXT_H_RV64
1431 : RISCV::ZEXT_H_RV32));
1433 return true;
1434 }
1435
1436 // Fall back to shift pair.
1437 Register ShiftLeftReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
1438 MachineInstr *ShiftLeft = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1439 TII.get(RISCV::SLLI), ShiftLeftReg)
1440 .addReg(SrcReg)
1441 .addImm(STI.getXLen() - SrcSize);
1442 constrainSelectedInstRegOperands(*ShiftLeft, TII, TRI, RBI);
1443 MachineInstr *ShiftRight =
1444 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1445 TII.get(IsSigned ? RISCV::SRAI : RISCV::SRLI), DstReg)
1446 .addReg(ShiftLeftReg)
1447 .addImm(STI.getXLen() - SrcSize);
1448 constrainSelectedInstRegOperands(*ShiftRight, TII, TRI, RBI);
1449 MI.eraseFromParent();
1450 return true;
1451 }
1452 case TargetOpcode::G_FCONSTANT: {
1453 // TODO: Use constant pool for complex constants.
1454 Register DstReg = MI.getOperand(0).getReg();
1455 const APFloat &FPimm = MI.getOperand(1).getFPImm()->getValueAPF();
1456 unsigned Size = MRI->getType(DstReg).getSizeInBits();
1457
1458 // Zfa loads some constants straight into an FPR. This includes f64 on
1459 // RV32, which would otherwise have to be built through the stack.
1460 if (Subtarget->hasStdExtZfa() &&
1461 ((Size == 16 &&
1462 (Subtarget->hasStdExtZfh() || Subtarget->hasStdExtZvfh())) ||
1463 (Size == 32 && Subtarget->hasStdExtF()) ||
1464 (Size == 64 && Subtarget->hasStdExtD()))) {
1466 // Some negative constants can be produced by fli + fneg.
1467 bool Negate = false;
1468 if (Index < 0 && FPimm.isNegative()) {
1470 Negate = true;
1471 }
1472 if (Index >= 0) {
1473 unsigned FLIOpc = Size == 64 ? RISCV::FLI_D
1474 : Size == 32 ? RISCV::FLI_S
1475 : RISCV::FLI_H;
1476 Register FLIReg = DstReg;
1477 if (Negate) {
1478 const TargetRegisterClass *RC = TRI.getRegClassForTypeOnBank(
1479 MRI->getType(DstReg), RBI.getRegBank(RISCV::FPRBRegBankID),
1480 STI.is64Bit());
1481 FLIReg = MRI->createVirtualRegister(RC);
1482 }
1483 MachineInstr *FLI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1484 TII.get(FLIOpc), FLIReg)
1485 .addImm(Index);
1487
1488 if (Negate) {
1489 unsigned FNegOpc = Size == 64 ? RISCV::FSGNJN_D
1490 : Size == 32 ? RISCV::FSGNJN_S
1491 : RISCV::FSGNJN_H;
1492 MachineInstr *FNeg = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1493 TII.get(FNegOpc), DstReg)
1494 .addReg(FLIReg)
1495 .addReg(FLIReg);
1497 }
1498
1499 MI.eraseFromParent();
1500 return true;
1501 }
1502 }
1503
1504 if (Size == 16 || Size == 32 || (Size == 64 && Subtarget->is64Bit())) {
1505 Register GPRReg;
1506 if (FPimm.isPosZero()) {
1507 GPRReg = RISCV::X0;
1508 } else {
1509 GPRReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
1510 APInt Imm = FPimm.bitcastToAPInt();
1511 if (!materializeImm(GPRReg, Imm.getSExtValue(), MI))
1512 return false;
1513 }
1514
1515 unsigned Opcode = Size == 64 ? RISCV::FMV_D_X
1516 : Size == 32 ? RISCV::FMV_W_X
1517 : RISCV::FMV_H_X;
1518 MachineInstr *FMV = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1519 TII.get(Opcode), DstReg)
1520 .addReg(GPRReg);
1522 } else {
1523 // s64 on rv32
1524 assert(Size == 64 && !Subtarget->is64Bit() &&
1525 "Unexpected size or subtarget");
1526
1527 if (FPimm.isPosZero()) {
1528 // Optimize +0.0 to use fcvt.d.w
1529 MachineInstr *FCVT = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1530 TII.get(RISCV::FCVT_D_W), DstReg)
1531 .addReg(RISCV::X0)
1534
1535 MI.eraseFromParent();
1536 return true;
1537 }
1538
1539 // Split into two pieces and build through the stack.
1540 Register GPRRegHigh = MRI->createVirtualRegister(&RISCV::GPRRegClass);
1541 Register GPRRegLow = MRI->createVirtualRegister(&RISCV::GPRRegClass);
1542 APInt Imm = FPimm.bitcastToAPInt();
1543 if (!materializeImm(GPRRegHigh, Imm.extractBits(32, 32).getSExtValue(),
1544 MI))
1545 return false;
1546 if (!materializeImm(GPRRegLow, Imm.trunc(32).getSExtValue(), MI))
1547 return false;
1548 MachineInstr *PairF64 =
1549 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1550 TII.get(RISCV::BuildPairF64Pseudo), DstReg)
1551 .addReg(GPRRegLow)
1552 .addReg(GPRRegHigh);
1553 constrainSelectedInstRegOperands(*PairF64, TII, TRI, RBI);
1554 }
1555
1556 MI.eraseFromParent();
1557 return true;
1558 }
1559 case TargetOpcode::G_GLOBAL_VALUE: {
1560 auto *GV = MI.getOperand(1).getGlobal();
1561 if (GV->isThreadLocal()) {
1562 // TODO: implement this case.
1563 return false;
1564 }
1565
1566 return selectAddr(MI, GV->isDSOLocal(), GV->hasExternalWeakLinkage());
1567 }
1568 case TargetOpcode::G_JUMP_TABLE:
1569 case TargetOpcode::G_CONSTANT_POOL:
1570 return selectAddr(MI);
1571 case TargetOpcode::G_BRCOND: {
1572 Register LHS, RHS;
1574 getOperandsForBranch(MI.getOperand(0).getReg(), CC, LHS, RHS, *MRI);
1575
1576 MachineInstr *Bcc = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1578 .addReg(LHS)
1579 .addReg(RHS)
1580 .addMBB(MI.getOperand(1).getMBB());
1581 MI.eraseFromParent();
1583 return true;
1584 }
1585 case TargetOpcode::G_SELECT:
1586 return selectSelect(MI);
1587 case TargetOpcode::G_FCMP:
1588 return selectFPCompare(MI);
1589 case TargetOpcode::G_FENCE: {
1590 AtomicOrdering FenceOrdering =
1591 static_cast<AtomicOrdering>(MI.getOperand(0).getImm());
1592 SyncScope::ID FenceSSID =
1593 static_cast<SyncScope::ID>(MI.getOperand(1).getImm());
1594 emitFence(FenceOrdering, FenceSSID, MI);
1595 MI.eraseFromParent();
1596 return true;
1597 }
1598 case TargetOpcode::G_IMPLICIT_DEF:
1599 return selectImplicitDef(MI);
1600 case TargetOpcode::G_UNMERGE_VALUES:
1601 return selectUnmergeValues(MI);
1602 case TargetOpcode::G_MERGE_VALUES:
1603 return selectMergeValues(MI);
1604 case TargetOpcode::G_LOAD:
1605 case TargetOpcode::G_STORE: {
1606 GLoadStore &LdSt = cast<GLoadStore>(MI);
1607 const Register ValReg = LdSt.getReg(0);
1608 const Register PtrReg = LdSt.getPointerReg();
1609 LLT PtrTy = MRI->getType(PtrReg);
1610
1611 const RegisterBank &RB = *RBI.getRegBank(ValReg, *MRI, TRI);
1612 if (RB.getID() != RISCV::GPRBRegBankID)
1613 return false;
1614
1615#ifndef NDEBUG
1616 const RegisterBank &PtrRB = *RBI.getRegBank(PtrReg, *MRI, TRI);
1617 // Check that the pointer register is valid.
1618 assert(PtrRB.getID() == RISCV::GPRBRegBankID &&
1619 "Load/Store pointer operand isn't a GPR");
1620 assert(PtrTy.isPointer() && "Load/Store pointer operand isn't a pointer");
1621#endif
1622
1623 // Can only handle AddressSpace 0.
1624 if (PtrTy.getAddressSpace() != 0)
1625 return false;
1626
1627 unsigned MemSize = LdSt.getMemSizeInBits().getValue();
1628 AtomicOrdering Order = LdSt.getMMO().getSuccessOrdering();
1629
1630 if (isStrongerThanMonotonic(Order)) {
1631 MI.setDesc(TII.get(selectZalasrLoadStoreOp(Opc, MemSize)));
1633 return true;
1634 }
1635
1636 const unsigned NewOpc =
1637 selectRegImmLoadStoreOp(STI, MI.getOpcode(), MemSize);
1638 if (NewOpc == MI.getOpcode())
1639 return false;
1640
1641 // Check if we can fold anything into the addressing mode.
1642 auto AddrModeFns = selectAddrRegImm(MI.getOperand(1));
1643 if (!AddrModeFns)
1644 return false;
1645
1646 // Folded something. Create a new instruction and return it.
1647 MachineInstrBuilder NewInst =
1648 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII.get(NewOpc));
1649 NewInst.setMIFlags(MI.getFlags());
1650 if (isa<GStore>(MI))
1651 NewInst.addUse(ValReg);
1652 else
1653 NewInst.addDef(ValReg);
1654 NewInst.cloneMemRefs(MI);
1655 for (auto &Fn : *AddrModeFns)
1656 Fn(NewInst);
1657 MI.eraseFromParent();
1658
1659 constrainSelectedInstRegOperands(*NewInst, TII, TRI, RBI);
1660 return true;
1661 }
1662 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
1663 return selectIntrinsicWithSideEffects(MI);
1664 case TargetOpcode::G_INTRINSIC:
1665 return selectIntrinsic(MI);
1666 case TargetOpcode::G_SPLAT_VECTOR:
1667 return selectSplatVector(MI);
1668 case TargetOpcode::G_EXTRACT_SUBVECTOR:
1669 return selectExtractSubvector(MI);
1670 case TargetOpcode::G_INSERT_SUBVECTOR:
1671 return selectInsertSubVector(MI);
1672 default:
1673 return false;
1674 }
1675}
1676
1677bool RISCVInstructionSelector::selectUnmergeValues(MachineInstr &MI) const {
1678 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES);
1679
1680 // Split Src into two s32 parts.
1681 if (MI.getNumOperands() != 3)
1682 return false;
1683 Register Src = MI.getOperand(2).getReg();
1685 Register Hi = MI.getOperand(1).getReg();
1686
1687 // RV32+Zilsd: split a GPRPair (i64) into its two s32 GPR halves.
1688 if (!Subtarget->is64Bit() && Subtarget->hasStdExtZilsd() &&
1689 MRI->getType(Src) == LLT::scalar(64) && isRegInGprb(Src) &&
1690 isRegInGprb(Lo) && isRegInGprb(Hi)) {
1691 // GPRPairNoX0 rather than GPRPair: a sub-register index is only valid for
1692 // a class when every register in it supports the index, and X0_Pair has no
1693 // sub_gpr_odd. SelectionDAG gets the same effect through
1694 // InstrEmitter::ConstrainForSubReg.
1695 if (!RBI.constrainGenericRegister(Src, RISCV::GPRPairNoX0RegClass, *MRI))
1696 return false;
1697 // COPY with a sub-register index rather than EXTRACT_SUBREG, which is what
1698 // SelectionDAG emits too: InstrEmitter lowers an EXTRACT_SUBREG SDNode to
1699 // %dst = COPY %src:sub and never builds the pseudo itself. A literal
1700 // EXTRACT_SUBREG would also survive to ExpandPostRAPseudos, which treats
1701 // one as unreachable.
1702 auto ExtractHalf = [&](Register Dst, unsigned SubIdx) {
1703 RBI.constrainGenericRegister(Dst, RISCV::GPRRegClass, *MRI);
1704 MachineInstr &C = *BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1705 TII.get(TargetOpcode::COPY), Dst)
1706 .addReg(Src, {}, SubIdx);
1708 };
1709 ExtractHalf(Lo, RISCV::sub_gpr_even);
1710 ExtractHalf(Hi, RISCV::sub_gpr_odd);
1711 MI.eraseFromParent();
1712 return true;
1713 }
1714
1715 if (!Subtarget->hasStdExtZfa())
1716 return false;
1717
1718 if (!isRegInFprb(Src) || !isRegInGprb(Lo) || !isRegInGprb(Hi))
1719 return false;
1720
1721 MachineInstr *ExtractLo = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1722 TII.get(RISCV::FMV_X_W_FPR64), Lo)
1723 .addReg(Src);
1724 constrainSelectedInstRegOperands(*ExtractLo, TII, TRI, RBI);
1725
1726 MachineInstr *ExtractHi = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1727 TII.get(RISCV::FMVH_X_D), Hi)
1728 .addReg(Src);
1729 constrainSelectedInstRegOperands(*ExtractHi, TII, TRI, RBI);
1730
1731 MI.eraseFromParent();
1732 return true;
1733}
1734
1735bool RISCVInstructionSelector::selectMergeValues(MachineInstr &MI) const {
1736 assert(MI.getOpcode() == TargetOpcode::G_MERGE_VALUES);
1737
1738 if (MI.getNumOperands() != 3)
1739 return false;
1740 Register Dst = MI.getOperand(0).getReg();
1742 Register Hi = MI.getOperand(2).getReg();
1743
1744 // RV32+Zilsd: build a GPRPair (i64) from two s32 GPR halves.
1745 if (!Subtarget->is64Bit() && Subtarget->hasStdExtZilsd() &&
1746 MRI->getType(Dst) == LLT::scalar(64) && isRegInGprb(Dst) &&
1747 isRegInGprb(Lo) && isRegInGprb(Hi)) {
1748 // GPRPairNoX0 rather than GPRPair, because sub_gpr_odd is not valid for
1749 // X0_Pair. Constrain Dst up front: constrainSelectedInstRegOperands below
1750 // would otherwise infer GPRPair from the s64 type.
1751 if (!RBI.constrainGenericRegister(Dst, RISCV::GPRPairNoX0RegClass, *MRI))
1752 return false;
1753 MachineInstr &Seq = *BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1754 TII.get(TargetOpcode::REG_SEQUENCE), Dst)
1755 .addReg(Lo)
1756 .addImm(RISCV::sub_gpr_even)
1757 .addReg(Hi)
1758 .addImm(RISCV::sub_gpr_odd);
1759 MI.eraseFromParent();
1761 return true;
1762 }
1763 return false;
1764}
1765
1766bool RISCVInstructionSelector::replacePtrWithInt(MachineInstr &MI,
1767 unsigned OpIdx) {
1768 MachineOperand &Op = MI.getOperand(OpIdx);
1769 Register PtrReg = Op.getReg();
1770 assert(MRI->getType(PtrReg).isPointer() && "Operand is not a pointer!");
1771
1772 const LLT iXLen = LLT::integer(STI.getXLen());
1773 Register IntReg = MRI->createGenericVirtualRegister(iXLen);
1774 MRI->setRegBank(IntReg, RBI.getRegBank(RISCV::GPRBRegBankID));
1775 MachineInstr *PtrToInt = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1776 TII.get(TargetOpcode::G_PTRTOINT), IntReg)
1777 .addReg(PtrReg);
1778 Op.setReg(IntReg);
1779 return select(*PtrToInt);
1780}
1781
1782void RISCVInstructionSelector::preISelLower(MachineInstr &MI) {
1783 switch (MI.getOpcode()) {
1784 case TargetOpcode::G_PTR_ADD: {
1785 Register DstReg = MI.getOperand(0).getReg();
1786 const LLT iXLen = LLT::integer(STI.getXLen());
1787
1788 replacePtrWithInt(MI, 1);
1789 MI.setDesc(TII.get(TargetOpcode::G_ADD));
1790 MRI->setType(DstReg, iXLen);
1791 break;
1792 }
1793 case TargetOpcode::G_PTRMASK: {
1794 Register DstReg = MI.getOperand(0).getReg();
1795 const LLT iXLen = LLT::integer(STI.getXLen());
1796 replacePtrWithInt(MI, 1);
1797 MI.setDesc(TII.get(TargetOpcode::G_AND));
1798 MRI->setType(DstReg, iXLen);
1799 break;
1800 }
1801 }
1802}
1803
1804void RISCVInstructionSelector::renderNegImm(MachineInstrBuilder &MIB,
1805 const MachineInstr &MI,
1806 int OpIdx) const {
1807 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1808 "Expected G_CONSTANT");
1809 int64_t CstVal = MI.getOperand(1).getCImm()->getSExtValue();
1810 MIB.addImm(-CstVal);
1811}
1812
1813void RISCVInstructionSelector::renderImmSubFromXLen(MachineInstrBuilder &MIB,
1814 const MachineInstr &MI,
1815 int OpIdx) const {
1816 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1817 "Expected G_CONSTANT");
1818 uint64_t CstVal = MI.getOperand(1).getCImm()->getZExtValue();
1819 MIB.addImm(STI.getXLen() - CstVal);
1820}
1821
1822void RISCVInstructionSelector::renderImmSubFrom32(MachineInstrBuilder &MIB,
1823 const MachineInstr &MI,
1824 int OpIdx) const {
1825 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1826 "Expected G_CONSTANT");
1827 uint64_t CstVal = MI.getOperand(1).getCImm()->getZExtValue();
1828 MIB.addImm(32 - CstVal);
1829}
1830
1831void RISCVInstructionSelector::renderImmPlus1(MachineInstrBuilder &MIB,
1832 const MachineInstr &MI,
1833 int OpIdx) const {
1834 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1835 "Expected G_CONSTANT");
1836 int64_t CstVal = MI.getOperand(1).getCImm()->getSExtValue();
1837 MIB.addImm(CstVal + 1);
1838}
1839
1840void RISCVInstructionSelector::renderTrailingZeros(MachineInstrBuilder &MIB,
1841 const MachineInstr &MI,
1842 int OpIdx) const {
1843 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1844 "Expected G_CONSTANT");
1845 uint64_t C = MI.getOperand(1).getCImm()->getZExtValue();
1847}
1848
1849void RISCVInstructionSelector::renderXLenSubTrailingOnes(
1850 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
1851 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1852 "Expected G_CONSTANT");
1853 uint64_t C = MI.getOperand(1).getCImm()->getZExtValue();
1854 MIB.addImm(Subtarget->getXLen() - llvm::countr_one(C));
1855}
1856
1857void RISCVInstructionSelector::renderAddiPairImmSmall(MachineInstrBuilder &MIB,
1858 const MachineInstr &MI,
1859 int OpIdx) const {
1860 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1861 "Expected G_CONSTANT");
1862 int64_t Imm = MI.getOperand(1).getCImm()->getSExtValue();
1863 int64_t Adj = Imm < 0 ? -2048 : 2047;
1864 MIB.addImm(Imm - Adj);
1865}
1866
1867void RISCVInstructionSelector::renderAddiPairImmLarge(MachineInstrBuilder &MIB,
1868 const MachineInstr &MI,
1869 int OpIdx) const {
1870 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
1871 "Expected G_CONSTANT");
1872 int64_t Imm = MI.getOperand(1).getCImm()->getSExtValue() < 0 ? -2048 : 2047;
1873 MIB.addImm(Imm);
1874}
1875
1876bool RISCVInstructionSelector::isRegInGprb(Register Reg) const {
1877 return RBI.getRegBank(Reg, *MRI, TRI)->getID() == RISCV::GPRBRegBankID;
1878}
1879
1880bool RISCVInstructionSelector::isRegInFprb(Register Reg) const {
1881 return RBI.getRegBank(Reg, *MRI, TRI)->getID() == RISCV::FPRBRegBankID;
1882}
1883
1884// A G_PTR_ADD result is worth splitting into Hi (materialized) +
1885// Lo12 (folded offset) only if every user is a plain scalar load/store
1886// using it as the address. Otherwise the ADD is selected on its own with
1887// the full materialized constant, making the Hi materialization here redundant.
1888bool RISCVInstructionSelector::isWorthFoldingAdd(Register AddResult) const {
1889 for (const MachineInstr &User : MRI->use_nodbg_instructions(AddResult)) {
1890 auto *LdSt = dyn_cast<GLoadStore>(&User);
1891 if (!LdSt)
1892 return false;
1893 // Must be used as the pointer, not the stored value.
1894 if (LdSt->getPointerReg() != AddResult)
1895 return false;
1897 return false;
1898 // Only scalar integer/f16/f32/f64 memory (exclude vectors, f128, ...).
1899 LLT Ty = MRI->getType(User.getOperand(0).getReg());
1900 if (!Ty.isScalar() || Ty.getSizeInBits() > 64)
1901 return false;
1902 }
1903 return true;
1904}
1905
1906bool RISCVInstructionSelector::selectCopy(MachineInstr &MI) const {
1907 Register DstReg = MI.getOperand(0).getReg();
1908
1909 if (DstReg.isPhysical())
1910 return true;
1911
1912 const TargetRegisterClass *DstRC =
1913 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
1914
1915 assert(DstRC &&
1916 "Register class not available for LLT, register bank combination");
1917
1918 // No need to constrain SrcReg. It will get constrained when
1919 // we hit another of its uses or its defs.
1920 // Copies do not have constraints.
1921 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI)) {
1922 LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(MI.getOpcode())
1923 << " operand\n");
1924 return false;
1925 }
1926
1927 MI.setDesc(TII.get(RISCV::COPY));
1928 return true;
1929}
1930
1931bool RISCVInstructionSelector::selectImplicitDef(MachineInstr &MI) const {
1932 assert(MI.getOpcode() == TargetOpcode::G_IMPLICIT_DEF);
1933
1934 const Register DstReg = MI.getOperand(0).getReg();
1935 const TargetRegisterClass *DstRC = TRI.getRegClassForTypeOnBank(
1936 MRI->getType(DstReg), *RBI.getRegBank(DstReg, *MRI, TRI), STI.is64Bit());
1937
1938 assert(DstRC &&
1939 "Register class not available for LLT, register bank combination");
1940
1941 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI)) {
1942 LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(MI.getOpcode())
1943 << " operand\n");
1944 }
1945 MI.setDesc(TII.get(TargetOpcode::IMPLICIT_DEF));
1946 return true;
1947}
1948
1949bool RISCVInstructionSelector::materializeImm(Register DstReg, int64_t Imm,
1950 MachineInstr &MI) const {
1951 if (Imm == 0) {
1952 MachineBasicBlock &MBB = *MI.getParent();
1953 DebugLoc DL = MI.getDebugLoc();
1954 BuildMI(MBB, MI, DL, TII.get(TargetOpcode::COPY), DstReg).addReg(RISCV::X0);
1955 RBI.constrainGenericRegister(DstReg, RISCV::GPRRegClass, *MRI);
1956 return true;
1957 }
1958
1960 return materializeInstSeq(DstReg, Seq, MI);
1961}
1962
1963bool RISCVInstructionSelector::materializeInstSeq(
1964 Register DstReg, const RISCVMatInt::InstSeq &Seq, MachineInstr &MI) const {
1965 assert(!Seq.empty() && "materializeInstSeq requires a non-empty sequence");
1966
1967 MachineBasicBlock &MBB = *MI.getParent();
1968 DebugLoc DL = MI.getDebugLoc();
1969 unsigned NumInsts = Seq.size();
1970 Register SrcReg = RISCV::X0;
1971
1972 for (unsigned i = 0; i < NumInsts; i++) {
1973 Register TmpReg = i < NumInsts - 1
1974 ? MRI->createVirtualRegister(&RISCV::GPRRegClass)
1975 : DstReg;
1976 const RISCVMatInt::Inst &I = Seq[i];
1977 MachineInstr *Result;
1978
1979 switch (I.getOpndKind()) {
1980 case RISCVMatInt::Imm:
1981 Result = BuildMI(MBB, MI, DL, TII.get(I.getOpcode()), TmpReg)
1982 .addImm(I.getImm());
1983 break;
1984 case RISCVMatInt::RegX0:
1985 Result = BuildMI(MBB, MI, DL, TII.get(I.getOpcode()), TmpReg)
1986 .addReg(SrcReg)
1987 .addReg(RISCV::X0);
1988 break;
1990 Result = BuildMI(MBB, MI, DL, TII.get(I.getOpcode()), TmpReg)
1991 .addReg(SrcReg)
1992 .addReg(SrcReg);
1993 break;
1995 Result = BuildMI(MBB, MI, DL, TII.get(I.getOpcode()), TmpReg)
1996 .addReg(SrcReg)
1997 .addImm(I.getImm());
1998 break;
1999 }
2000
2002
2003 SrcReg = TmpReg;
2004 }
2005
2006 return true;
2007}
2008
2009InstructionSelector::ComplexRendererFns
2010RISCVInstructionSelector::computeConstAddr(int64_t CVal, bool IsPrefetch,
2011 Register OrigBase) const {
2012 // Split the constant into a materialized high part (the base) and
2013 // a simm12 low part (the offset). For prefetch the low part
2014 // must additionally be a multiple of 32 (simm12_lsb00000).
2015 int64_t Lo12 = SignExtend64<12>(CVal);
2016 int64_t Hi = (uint64_t)CVal - (uint64_t)Lo12;
2017 auto emit = [&](ConstAddrPlan Plan) -> ComplexRendererFns {
2018 return {{[=](MachineInstrBuilder &MIB) {
2019 MIB.addReg(materializeConstBase(MIB, Plan, OrigBase));
2020 },
2021 [=](MachineInstrBuilder &MIB) { MIB.addImm(Plan.Lo12); }}};
2022 };
2023 if (!Subtarget->is64Bit() || isInt<32>(Hi)) {
2024 if (IsPrefetch && (Lo12 & 0b11111) != 0)
2025 return std::nullopt;
2026 ConstAddrPlan Plan;
2027 Plan.Lo12 = Lo12;
2028 if (Hi) {
2029 Plan.Kind = ConstAddrPlan::LUI;
2030 Plan.Hi20 = (Hi >> 12) & 0xfffff;
2031 }
2032 return emit(std::move(Plan));
2033 }
2034
2035 // Otherwise ask constant materialization how it would handle the constant
2036 // and fold the trailing ADDI into the offset.
2038 if (Seq.back().getOpcode() != RISCV::ADDI)
2039 return std::nullopt;
2040 Lo12 = Seq.back().getImm();
2041 if (IsPrefetch && (Lo12 & 0b11111) != 0)
2042 return std::nullopt;
2043 Seq.pop_back();
2044 if (Seq.empty())
2045 return std::nullopt;
2046 ConstAddrPlan Plan;
2047 Plan.Kind = ConstAddrPlan::InstSeq;
2048 Plan.Seq = std::move(Seq);
2049 Plan.Lo12 = Lo12;
2050 return emit(std::move(Plan));
2051}
2052
2054RISCVInstructionSelector::materializeConstBase(MachineInstrBuilder &MIB,
2055 const ConstAddrPlan &Plan,
2056 Register OrigBase) const {
2057 MachineBasicBlock &MBB = *MIB->getParent();
2058 DebugLoc DL = MIB->getDebugLoc();
2059 MachineInstr &InsertPt = *MIB.getInstr();
2060
2061 Register HiReg = RISCV::X0;
2062 switch (Plan.Kind) {
2063 case ConstAddrPlan::X0:
2064 break;
2065 case ConstAddrPlan::LUI: {
2066 HiReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2067 MachineInstr *LUI = BuildMI(MBB, InsertPt, DL, TII.get(RISCV::LUI), HiReg)
2068 .addImm(Plan.Hi20);
2070 break;
2071 }
2072 case ConstAddrPlan::InstSeq: {
2073 HiReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2074 materializeInstSeq(HiReg, Plan.Seq, InsertPt);
2075 break;
2076 }
2077 }
2078
2079 // For G_PTR_ADD + large constant, add the original base to the materialized
2080 // high part.
2081 if (OrigBase.isValid() && HiReg != RISCV::X0) {
2082 Register BaseReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2083 MachineInstr *Add = BuildMI(MBB, InsertPt, DL, TII.get(RISCV::ADD), BaseReg)
2084 .addReg(OrigBase)
2085 .addReg(HiReg);
2087 return BaseReg;
2088 }
2089 return OrigBase.isValid() ? OrigBase : HiReg;
2090}
2091
2092bool RISCVInstructionSelector::selectAddr(MachineInstr &MI, bool IsLocal,
2093 bool IsExternWeak) const {
2094 assert((MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
2095 MI.getOpcode() == TargetOpcode::G_JUMP_TABLE ||
2096 MI.getOpcode() == TargetOpcode::G_CONSTANT_POOL) &&
2097 "Unexpected opcode");
2098
2099 const MachineOperand &DispMO = MI.getOperand(1);
2100
2101 Register DefReg = MI.getOperand(0).getReg();
2102 const LLT DefTy = MRI->getType(DefReg);
2103
2104 // When HWASAN is used and tagging of global variables is enabled
2105 // they should be accessed via the GOT, since the tagged address of a global
2106 // is incompatible with existing code models. This also applies to non-pic
2107 // mode.
2108 if (TM.isPositionIndependent() || Subtarget->allowTaggedGlobals()) {
2109 if (IsLocal && !Subtarget->allowTaggedGlobals()) {
2110 // Use PC-relative addressing to access the symbol. This generates the
2111 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2112 // %pcrel_lo(auipc)).
2113 MI.setDesc(TII.get(RISCV::PseudoLLA));
2115 return true;
2116 }
2117
2118 // Use PC-relative addressing to access the GOT for this symbol, then
2119 // load the address from the GOT. This generates the pattern (PseudoLGA
2120 // sym), which expands to (ld (addi (auipc %got_pcrel_hi(sym))
2121 // %pcrel_lo(auipc))).
2122 MachineFunction &MF = *MI.getParent()->getParent();
2123 MachineMemOperand *MemOp = MF.getMachineMemOperand(
2127 DefTy, Align(DefTy.getSizeInBits() / 8));
2128
2129 MachineInstr *Result = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2130 TII.get(RISCV::PseudoLGA), DefReg)
2131 .addDisp(DispMO, 0)
2132 .addMemOperand(MemOp);
2133
2135
2136 MI.eraseFromParent();
2137 return true;
2138 }
2139
2140 switch (TM.getCodeModel()) {
2141 default: {
2143 "Unsupported code model for lowering", MI);
2144 return false;
2145 }
2146 case CodeModel::Small: {
2147 // Must lie within a single 2 GiB address range and must lie between
2148 // absolute addresses -2 GiB and +2 GiB. This generates the pattern (addi
2149 // (lui %hi(sym)) %lo(sym)).
2150 Register AddrHiDest = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2151 MachineInstr *AddrHi = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2152 TII.get(RISCV::LUI), AddrHiDest)
2153 .addDisp(DispMO, 0, RISCVII::MO_HI);
2154
2156
2157 MachineInstr *Result = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2158 TII.get(RISCV::ADDI), DefReg)
2159 .addReg(AddrHiDest)
2160 .addDisp(DispMO, 0, RISCVII::MO_LO);
2161
2163
2164 MI.eraseFromParent();
2165 return true;
2166 }
2167 case CodeModel::Medium:
2168 // Emit LGA/LLA instead of the sequence it expands to because the pcrel_lo
2169 // relocation needs to reference a label that points to the auipc
2170 // instruction itself, not the global. This cannot be done inside the
2171 // instruction selector.
2172 if (IsExternWeak) {
2173 // An extern weak symbol may be undefined, i.e. have value 0, which may
2174 // not be within 2GiB of PC, so use GOT-indirect addressing to access the
2175 // symbol. This generates the pattern (PseudoLGA sym), which expands to
2176 // (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2177 MachineFunction &MF = *MI.getParent()->getParent();
2178 MachineMemOperand *MemOp = MF.getMachineMemOperand(
2182 DefTy, Align(DefTy.getSizeInBits() / 8));
2183
2184 MachineInstr *Result = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2185 TII.get(RISCV::PseudoLGA), DefReg)
2186 .addDisp(DispMO, 0)
2187 .addMemOperand(MemOp);
2188
2190
2191 MI.eraseFromParent();
2192 return true;
2193 }
2194
2195 // Generate a sequence for accessing addresses within any 2GiB range
2196 // within the address space. This generates the pattern (PseudoLLA sym),
2197 // which expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
2198 MI.setDesc(TII.get(RISCV::PseudoLLA));
2200 return true;
2201 }
2202
2203 return false;
2204}
2205
2206bool RISCVInstructionSelector::selectSelect(MachineInstr &MI) const {
2207 auto &SelectMI = cast<GSelect>(MI);
2208
2209 Register LHS, RHS;
2211 getOperandsForBranch(SelectMI.getCondReg(), CC, LHS, RHS, *MRI);
2212
2213 Register DstReg = SelectMI.getReg(0);
2214
2215 unsigned Opc = RISCV::Select_GPR_Using_CC_GPR;
2216 if (RBI.getRegBank(DstReg, *MRI, TRI)->getID() == RISCV::FPRBRegBankID) {
2217 unsigned Size = MRI->getType(DstReg).getSizeInBits();
2218 Opc = Size == 32 ? RISCV::Select_FPR32_Using_CC_GPR
2219 : RISCV::Select_FPR64_Using_CC_GPR;
2220 }
2221
2222 MachineInstr *Result =
2223 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII.get(Opc))
2224 .addDef(DstReg)
2225 .addReg(LHS)
2226 .addReg(RHS)
2227 .addImm(CC)
2228 .addReg(SelectMI.getTrueReg())
2229 .addReg(SelectMI.getFalseReg());
2230 MI.eraseFromParent();
2232 return true;
2233}
2234
2235// Convert an FCMP predicate to one of the supported F or D instructions.
2236static unsigned getFCmpOpcode(CmpInst::Predicate Pred, unsigned Size) {
2237 assert((Size == 16 || Size == 32 || Size == 64) && "Unsupported size");
2238 switch (Pred) {
2239 default:
2240 llvm_unreachable("Unsupported predicate");
2241 case CmpInst::FCMP_OLT:
2242 return Size == 16 ? RISCV::FLT_H : Size == 32 ? RISCV::FLT_S : RISCV::FLT_D;
2243 case CmpInst::FCMP_OLE:
2244 return Size == 16 ? RISCV::FLE_H : Size == 32 ? RISCV::FLE_S : RISCV::FLE_D;
2245 case CmpInst::FCMP_OEQ:
2246 return Size == 16 ? RISCV::FEQ_H : Size == 32 ? RISCV::FEQ_S : RISCV::FEQ_D;
2247 }
2248}
2249
2250// Try legalizing an FCMP by swapping or inverting the predicate to one that
2251// is supported.
2253 CmpInst::Predicate &Pred, bool &NeedInvert) {
2254 auto isLegalFCmpPredicate = [](CmpInst::Predicate Pred) {
2255 return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE ||
2257 };
2258
2259 assert(!isLegalFCmpPredicate(Pred) && "Predicate already legal?");
2260
2262 if (isLegalFCmpPredicate(InvPred)) {
2263 Pred = InvPred;
2264 std::swap(LHS, RHS);
2265 return true;
2266 }
2267
2269 NeedInvert = true;
2270 if (isLegalFCmpPredicate(InvPred)) {
2271 Pred = InvPred;
2272 return true;
2273 }
2274 InvPred = CmpInst::getSwappedPredicate(InvPred);
2275 if (isLegalFCmpPredicate(InvPred)) {
2276 Pred = InvPred;
2277 std::swap(LHS, RHS);
2278 return true;
2279 }
2280
2281 return false;
2282}
2283
2284// Emit a sequence of instructions to compare LHS and RHS using Pred. Return
2285// the result in DstReg.
2286// FIXME: Maybe we should expand this earlier.
2287bool RISCVInstructionSelector::selectFPCompare(MachineInstr &MI) const {
2288 auto &CmpMI = cast<GFCmp>(MI);
2289 CmpInst::Predicate Pred = CmpMI.getCond();
2290
2291 Register DstReg = CmpMI.getReg(0);
2292 Register LHS = CmpMI.getLHSReg();
2293 Register RHS = CmpMI.getRHSReg();
2294
2295 unsigned Size = MRI->getType(LHS).getSizeInBits();
2296 assert((Size == 16 || Size == 32 || Size == 64) && "Unexpected size");
2297
2298 Register TmpReg = DstReg;
2299
2300 bool NeedInvert = false;
2301 // First try swapping operands or inverting.
2302 if (legalizeFCmpPredicate(LHS, RHS, Pred, NeedInvert)) {
2303 if (NeedInvert)
2304 TmpReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2305 MachineInstr *Cmp = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2306 TII.get(getFCmpOpcode(Pred, Size)), TmpReg)
2308 .addReg(LHS)
2309 .addReg(RHS);
2311 } else if (Pred == CmpInst::FCMP_ONE || Pred == CmpInst::FCMP_UEQ) {
2312 // fcmp one LHS, RHS => (OR (FLT LHS, RHS), (FLT RHS, LHS))
2313 NeedInvert = Pred == CmpInst::FCMP_UEQ;
2314 Register Cmp1Reg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2315 MachineInstr *Cmp1 =
2316 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2317 TII.get(getFCmpOpcode(CmpInst::FCMP_OLT, Size)), Cmp1Reg)
2319 .addReg(LHS)
2320 .addReg(RHS);
2322 Register Cmp2Reg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2323 MachineInstr *Cmp2 =
2324 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2325 TII.get(getFCmpOpcode(CmpInst::FCMP_OLT, Size)), Cmp2Reg)
2327 .addReg(RHS)
2328 .addReg(LHS);
2330 if (NeedInvert)
2331 TmpReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2332 MachineInstr *Or = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2333 TII.get(RISCV::OR), TmpReg)
2334 .addReg(Cmp1Reg)
2335 .addReg(Cmp2Reg);
2337 } else if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
2338 // fcmp ord LHS, RHS => (AND (FEQ LHS, LHS), (FEQ RHS, RHS))
2339 // If LHS and RHS are the same, a single FEQ suffices.
2340 NeedInvert = Pred == CmpInst::FCMP_UNO;
2341 if (NeedInvert)
2342 TmpReg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2343 if (LHS == RHS) {
2344 MachineInstr *Cmp =
2345 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2346 TII.get(getFCmpOpcode(CmpInst::FCMP_OEQ, Size)), TmpReg)
2348 .addReg(LHS)
2349 .addReg(LHS);
2351 } else {
2352 Register Cmp1Reg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2353 MachineInstr *Cmp1 =
2354 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2355 TII.get(getFCmpOpcode(CmpInst::FCMP_OEQ, Size)), Cmp1Reg)
2357 .addReg(LHS)
2358 .addReg(LHS);
2360 Register Cmp2Reg = MRI->createVirtualRegister(&RISCV::GPRRegClass);
2361 MachineInstr *Cmp2 =
2362 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2363 TII.get(getFCmpOpcode(CmpInst::FCMP_OEQ, Size)), Cmp2Reg)
2365 .addReg(RHS)
2366 .addReg(RHS);
2368 MachineInstr *And = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2369 TII.get(RISCV::AND), TmpReg)
2370 .addReg(Cmp1Reg)
2371 .addReg(Cmp2Reg);
2373 }
2374 } else
2375 llvm_unreachable("Unhandled predicate");
2376
2377 // Emit an XORI to invert the result if needed.
2378 if (NeedInvert) {
2379 MachineInstr *Xor = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2380 TII.get(RISCV::XORI), DstReg)
2381 .addReg(TmpReg)
2382 .addImm(1);
2384 }
2385
2386 MI.eraseFromParent();
2387 return true;
2388}
2389
2390void RISCVInstructionSelector::emitFence(AtomicOrdering FenceOrdering,
2391 SyncScope::ID FenceSSID,
2392 MachineInstr &MI) const {
2393 MachineBasicBlock &MBB = *MI.getParent();
2394 DebugLoc DL = MI.getDebugLoc();
2395
2396 if (STI.hasStdExtZtso()) {
2397 // The only fence that needs an instruction is a sequentially-consistent
2398 // cross-thread fence.
2399 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
2400 FenceSSID == SyncScope::System) {
2401 // fence rw, rw
2402 BuildMI(MBB, MI, DL, TII.get(RISCV::FENCE))
2405 return;
2406 }
2407
2408 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
2409 BuildMI(MBB, MI, DL, TII.get(TargetOpcode::MEMBARRIER));
2410 return;
2411 }
2412
2413 // singlethread fences only synchronize with signal handlers on the same
2414 // thread and thus only need to preserve instruction order, not actually
2415 // enforce memory ordering.
2416 if (FenceSSID == SyncScope::SingleThread) {
2417 BuildMI(MBB, MI, DL, TII.get(TargetOpcode::MEMBARRIER));
2418 return;
2419 }
2420
2421 // Refer to Table A.6 in the version 2.3 draft of the RISC-V Instruction Set
2422 // Manual: Volume I.
2423 unsigned Pred, Succ;
2424 switch (FenceOrdering) {
2425 default:
2426 llvm_unreachable("Unexpected ordering");
2427 case AtomicOrdering::AcquireRelease:
2428 // fence acq_rel -> fence.tso
2429 BuildMI(MBB, MI, DL, TII.get(RISCV::FENCE_TSO));
2430 return;
2431 case AtomicOrdering::Acquire:
2432 // fence acquire -> fence r, rw
2435 break;
2436 case AtomicOrdering::Release:
2437 // fence release -> fence rw, w
2439 Succ = RISCVFenceField::W;
2440 break;
2441 case AtomicOrdering::SequentiallyConsistent:
2442 // fence seq_cst -> fence rw, rw
2445 break;
2446 }
2447 BuildMI(MBB, MI, DL, TII.get(RISCV::FENCE)).addImm(Pred).addImm(Succ);
2448}
2449
2450namespace llvm {
2451InstructionSelector *
2454 const RISCVRegisterBankInfo &RBI) {
2455 return new RISCVInstructionSelector(TM, Subtarget, RBI);
2456}
2457} // end namespace llvm
const AArch64Subtarget & Subtarget
SDValue Pred
#define GET_GLOBALISEL_PREDICATES_INIT
#define GET_GLOBALISEL_TEMPORARIES_INIT
static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
static bool selectMergeValues(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
static bool selectUnmergeValues(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
static bool hasAllWUsers(const MachineInstr &OrigMI, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI)
static bool hasAllNBitUsers(const MachineInstr &OrigMI, const LoongArchSubtarget &ST, const MachineRegisterInfo &MRI, unsigned OrigBits)
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
static StringRef getName(Value *V)
static bool isWorthFoldingAdd(SDValue Add)
static unsigned selectRegImmLoadStoreOp(const RISCVSubtarget &STI, unsigned GenericOpc, unsigned OpSize)
Select the RISC-V regimm opcode for the G_LOAD or G_STORE operation GenericOpc on STI,...
static unsigned selectZalasrLoadStoreOp(unsigned GenericOpc, unsigned OpSize)
Select the RISC-V Zalasr opcode for the G_LOAD or G_STORE operation GenericOpc, appropriate for the G...
static unsigned getFCmpOpcode(CmpInst::Predicate Pred, unsigned Size)
static bool legalizeFCmpPredicate(Register &LHS, Register &RHS, CmpInst::Predicate &Pred, bool &NeedInvert)
static void getOperandsForBranch(Register CondReg, RISCVCC::CondCode &CC, Register &LHS, Register &RHS, MachineRegisterInfo &MRI)
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
This file declares the targeting of the RegisterBankInfo class for RISC-V.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
bool isNegative() const
Definition APFloat.h:1616
APInt bitcastToAPInt() const
Definition APFloat.h:1508
bool isPosZero() const
Definition APFloat.h:1627
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
This is an important base class in LLVM.
Definition Constant.h:44
virtual void setupMF(MachineFunction &mf, GISelValueTracking *vt, CodeGenCoverage *covinfo=nullptr, ProfileSummaryInfo *psi=nullptr, BlockFrequencyInfo *bfi=nullptr)
Setup per-MF executor state.
Register getPointerReg() const
Get the source register of the pointer value.
MachineMemOperand & getMMO() const
Get the MachineMemOperand on this instruction.
LocationSize getMemSizeInBits() const
Returns the size in bits of the memory access.
Register getReg(unsigned Idx) const
Access the Idx'th operand as a register and return it.
constexpr unsigned getScalarSizeInBits() const
constexpr bool isScalar() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr bool isVector() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr bool isPointer() const
constexpr unsigned getAddressSpace() const
static LLT integer(unsigned SizeInBits)
TypeSize getValue() const
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addDisp(const MachineOperand &Disp, int64_t off, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
AtomicOrdering getSuccessOrdering() const
Return the atomic ordering requirements for this memory operation.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static MachineOperand CreateImm(int64_t Val)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
const RegClassOrRegBank & getRegClassOrRegBank(Register Reg) const
Return the register bank or register class of Reg.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
LLVM_ABI void setRegBank(Register Reg, const RegisterBank &RegBank)
Set the register bank to RegBank for Reg.
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
LLVM_ABI Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
Analysis providing profile information.
This class provides the information for the target register banks.
unsigned getXLen() const
static std::pair< unsigned, unsigned > decomposeSubvectorInsertExtractToSubRegs(MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, const RISCVRegisterInfo *TRI)
static unsigned getRegClassIDForVecVT(MVT VT)
static RISCVVType::VLMUL getLMUL(MVT VT)
static const TargetRegisterClass * constrainGenericRegister(Register Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI)
Constrain the (possibly generic) virtual register Reg to RC.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
unsigned getID() const
Get the identifier of this register bank.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
bool isPositionIndependent() const
CodeModel::Model getCodeModel() const
Returns the code model.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
operand_type_match m_Reg()
SpecificConstantMatch m_SpecificICst(const APInt &RequestedValue)
Matches a constant equal to RequestedValue.
GCstAndRegMatch m_GCst(std::optional< ValueAndVReg > &ValReg)
operand_type_match m_Pred()
UnaryOp_match< SrcTy, TargetOpcode::G_ZEXT > m_GZExt(const SrcTy &Src)
ConstantMatch< APInt > m_ICst(APInt &Cst)
UnaryOp_match< SrcTy, TargetOpcode::G_INTTOPTR > m_GIntToPtr(const SrcTy &Src)
BinaryOp_match< LHS, RHS, TargetOpcode::G_ADD, true > m_GAdd(const LHS &L, const RHS &R)
SpecificImmMatch m_SpecificImm(int64_t RequestedValue)
Matches an immediate operand equal to RequestedValue.
AllOnesConstantMatch m_AllOnes()
CompareOp_match< Pred, LHS, RHS, TargetOpcode::G_ICMP > m_GICmp(const Pred &P, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_SUB > m_GSub(const LHS &L, const RHS &R)
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
BinaryOp_match< LHS, RHS, TargetOpcode::G_PTR_ADD, false > m_GPtrAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_SHL, false > m_GShl(const LHS &L, const RHS &R)
GFrameIndexMatch m_GFrameIndex(int &FI)
BinaryOp_match< LHS, RHS, TargetOpcode::G_AND, true > m_GAnd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_LSHR, false > m_GLShr(const LHS &L, const RHS &R)
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
SrcImmOp_match< SrcTy, AnyImmMatch, TargetOpcode::G_SEXT_INREG > m_GSExtInReg(const SrcTy &Src)
Matches a G_SEXT_INREG, binding its source and immediate width.
unsigned getBrCond(CondCode CC, unsigned SelectOpc=0)
int getLoadFPImm(APFloat FPImm)
getLoadFPImm - Return a 5-bit binary encoding of the floating-point immediate value.
InstSeq generateInstSeq(int64_t Val, const MCSubtargetInfo &STI)
SmallVector< Inst, 8 > InstSeq
Definition RISCVMatInt.h:43
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
LLVM_ABI unsigned encodeVTYPE(VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic, bool AltFmt=false)
static constexpr int64_t VLMaxSentinel
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:63
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
@ User
could "use" a pointer
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
PointerUnion< const TargetRegisterClass *, const RegisterBank * > RegClassOrRegBank
Convenient type to represent either a register class or a register bank.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isStrongerThanMonotonic(AtomicOrdering AO)
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
Mutate the newly-selected instruction I to constrain its (possibly generic) virtual register operands...
Definition Utils.cpp:163
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI MVT getMVTForLLT(LLT Ty)
Get a rough equivalent of an MVT for a given LLT.
InstructionSelector * createRISCVInstructionSelector(const RISCVTargetMachine &TM, const RISCVSubtarget &Subtarget, const RISCVRegisterBankInfo &RBI)
LLVM_ABI std::optional< int64_t > getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT fits in int64_t returns it.
Definition Utils.cpp:321
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
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
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void reportGISelFailure(MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext's diagnostic stream.
Definition Utils.cpp:265
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T maskTrailingZeros(unsigned N)
Create a bitmask with the N right-most bits set to 0, and all other bits set to 1.
Definition MathExtras.h:95
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:440
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:572
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define MORE()
Definition regcomp.c:247
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.