LLVM 24.0.0git
AMDGPUISelDAGToDAG.cpp
Go to the documentation of this file.
1//===-- AMDGPUISelDAGToDAG.cpp - A dag to dag inst selector for AMDGPU ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//==-----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines an instruction selector for the AMDGPU target.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AMDGPUISelDAGToDAG.h"
15#include "AMDGPU.h"
16#include "AMDGPUInstrInfo.h"
17#include "AMDGPUMachineInstrs.h"
18#include "AMDGPUSubtarget.h"
20#include "R600RegisterInfo.h"
21#include "SIISelLowering.h"
28#include "llvm/IR/IntrinsicsAMDGPU.h"
31
32#ifdef EXPENSIVE_CHECKS
34#include "llvm/IR/Dominators.h"
35#endif
36
37#define DEBUG_TYPE "amdgpu-isel"
38
39using namespace llvm;
40
41//===----------------------------------------------------------------------===//
42// Instruction Selector Implementation
43//===----------------------------------------------------------------------===//
44
45namespace {
46static SDValue stripBitcast(SDValue Val) {
47 return Val.getOpcode() == ISD::BITCAST ? Val.getOperand(0) : Val;
48}
49
50// Figure out if this is really an extract of the high 16-bits of a dword.
51static bool isExtractHiElt(SDValue In, SDValue &Out) {
52 In = stripBitcast(In);
53
54 if (In.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
55 if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(In.getOperand(1))) {
56 if (!Idx->isOne())
57 return false;
58 Out = In.getOperand(0);
59 return true;
60 }
61 }
62
63 if (In.getOpcode() != ISD::TRUNCATE)
64 return false;
65
66 SDValue Srl = In.getOperand(0);
67 if (Srl.getOpcode() == ISD::SRL) {
68 if (ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
69 if (ShiftAmt->getZExtValue() == 16) {
70 SDValue Result = stripBitcast(Srl.getOperand(0));
71 // op_sel can only select the high half of a 32-bit source. If the
72 // shift source is wider (e.g. a 64-bit D16 image sample result), we
73 // cannot fold it directly. Do not assign Out before this check since
74 // the caller may pass the same SDValue for both In and Out.
75 if (Result.getValueSizeInBits() != 32)
76 return false;
77 Out = Result;
78 return true;
79 }
80 }
81 }
82
83 return false;
84}
85
86static bool isLoEltExtractHi(SDValue BV) {
87 SDValue Lo = stripBitcast(BV.getOperand(0));
88 if (Lo.getOpcode() == ISD::FNEG)
89 Lo = stripBitcast(Lo.getOperand(0));
90 SDValue Unused;
91 return isExtractHiElt(Lo, Unused);
92}
93
94static SDValue createVOP3PSrc32FromLo16(SDValue Lo, SDValue Src,
95 llvm::SelectionDAG *CurDAG,
96 const GCNSubtarget *Subtarget) {
97 if (!Subtarget->useRealTrue16Insts()) {
98 return Lo;
99 }
100
101 SDValue NewSrc;
102 SDLoc SL(Lo);
103
104 if (Lo->isDivergent()) {
105 SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
106 SL, Lo.getValueType()),
107 0);
108 const SDValue Ops[] = {
109 CurDAG->getTargetConstant(AMDGPU::VGPR_32RegClassID, SL, MVT::i32), Lo,
110 CurDAG->getTargetConstant(AMDGPU::lo16, SL, MVT::i16), Undef,
111 CurDAG->getTargetConstant(AMDGPU::hi16, SL, MVT::i16)};
112
113 NewSrc = SDValue(CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, SL,
114 Src.getValueType(), Ops),
115 0);
116 } else {
117 // the S_MOV is needed since the Lo could still be a VGPR16.
118 // With S_MOV, isel insert a "sgpr32 = copy vgpr16" and we reply on
119 // the fixvgpr2sgprcopy pass to legalize it
120 NewSrc = SDValue(
121 CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, Src.getValueType(), Lo),
122 0);
123 }
124
125 return NewSrc;
126}
127
128// Look through operations that obscure just looking at the low 16-bits of the
129// same register.
130static SDValue stripExtractLoElt(SDValue In) {
131 if (In.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
132 SDValue Idx = In.getOperand(1);
133 if (isNullConstant(Idx) && In.getValueSizeInBits() <= 32)
134 return In.getOperand(0);
135 }
136
137 if (In.getOpcode() == ISD::TRUNCATE) {
138 SDValue Src = In.getOperand(0);
139 if (Src.getValueType().getSizeInBits() == 32)
140 return stripBitcast(Src);
141 }
142
143 return In;
144}
145
146static SDValue emitRegSequence(llvm::SelectionDAG &CurDAG, unsigned DstRegClass,
147 EVT DstTy, ArrayRef<SDValue> Elts,
148 ArrayRef<unsigned> SubRegClass,
149 const SDLoc &DL) {
150 assert(Elts.size() == SubRegClass.size() && "array size mismatch");
151 unsigned NumElts = Elts.size();
152 SmallVector<SDValue, 17> Ops(2 * NumElts + 1);
153 Ops[0] = (CurDAG.getTargetConstant(DstRegClass, DL, MVT::i32));
154 for (unsigned i = 0; i < NumElts; ++i) {
155 Ops[2 * i + 1] = Elts[i];
156 Ops[2 * i + 2] = CurDAG.getTargetConstant(SubRegClass[i], DL, MVT::i32);
157 }
158 return SDValue(
159 CurDAG.getMachineNode(TargetOpcode::REG_SEQUENCE, DL, DstTy, Ops), 0);
160}
161
162} // end anonymous namespace
163
165 "AMDGPU DAG->DAG Pattern Instruction Selection", false,
166 false)
167INITIALIZE_PASS_DEPENDENCY(AMDGPUPerfHintAnalysisLegacy)
169#ifdef EXPENSIVE_CHECKS
172#endif
174 "AMDGPU DAG->DAG Pattern Instruction Selection", false,
175 false)
176
177/// This pass converts a legalized DAG into a AMDGPU-specific
178// DAG, ready for instruction scheduling.
180 CodeGenOptLevel OptLevel) {
181 return new AMDGPUDAGToDAGISelLegacy(TM, OptLevel);
182}
183
187
189 Subtarget = &MF.getSubtarget<GCNSubtarget>();
190 Subtarget->checkSubtargetFeatures(MF.getFunction());
192}
193
194bool AMDGPUDAGToDAGISel::fp16SrcZerosHighBits(unsigned Opc) const {
195 // XXX - only need to list legal operations.
196 switch (Opc) {
197 case ISD::POISON:
198 return true;
199 case ISD::FADD:
200 case ISD::FSUB:
201 case ISD::FMUL:
202 case ISD::FDIV:
203 case ISD::FREM:
205 case ISD::UINT_TO_FP:
206 case ISD::SINT_TO_FP:
207 case ISD::FABS:
208 // Fabs is lowered to a bit operation, but it's an and which will clear the
209 // high bits anyway.
210 case ISD::FSQRT:
211 case ISD::FSIN:
212 case ISD::FCOS:
213 case ISD::FPOWI:
214 case ISD::FPOW:
215 case ISD::FLOG:
216 case ISD::FLOG2:
217 case ISD::FLOG10:
218 case ISD::FEXP:
219 case ISD::FEXP2:
220 case ISD::FCEIL:
221 case ISD::FTRUNC:
222 case ISD::FRINT:
223 case ISD::FNEARBYINT:
224 case ISD::FROUNDEVEN:
225 case ISD::FROUND:
226 case ISD::FFLOOR:
227 case ISD::FMINNUM:
228 case ISD::FMAXNUM:
229 case ISD::FLDEXP:
230 case AMDGPUISD::FRACT:
231 case AMDGPUISD::CLAMP:
232 case AMDGPUISD::COS_HW:
233 case AMDGPUISD::SIN_HW:
234 case AMDGPUISD::FMIN3:
235 case AMDGPUISD::FMAX3:
236 case AMDGPUISD::FMED3:
237 case AMDGPUISD::FMAD_FTZ:
238 case AMDGPUISD::RCP:
239 case AMDGPUISD::RSQ:
240 case AMDGPUISD::RCP_IFLAG:
241 // On gfx10, all 16-bit instructions preserve the high bits.
242 return Subtarget->getGeneration() <= AMDGPUSubtarget::GFX9;
243 case ISD::FP_ROUND:
244 // We may select fptrunc (fma/mad) to mad_mixlo, which does not zero the
245 // high bits on gfx9.
246 // TODO: If we had the source node we could see if the source was fma/mad
247 return Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
248 case ISD::FMA:
249 case ISD::FMAD:
250 case AMDGPUISD::DIV_FIXUP:
251 return Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
252 default:
253 // fcopysign, select and others may be lowered to 32-bit bit operations
254 // which don't zero the high bits.
255 return false;
256 }
257}
258
260#ifdef EXPENSIVE_CHECKS
262 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
263 for (auto &L : LI->getLoopsInPreorder()) {
264 assert(L->isLCSSAForm(DT));
265 }
266#endif
268}
269
278
280 assert(Subtarget->d16PreservesUnusedBits());
281 MVT VT = N->getValueType(0).getSimpleVT();
282 if (VT != MVT::v2i16 && VT != MVT::v2f16)
283 return false;
284
285 SDValue Lo = N->getOperand(0);
286 SDValue Hi = N->getOperand(1);
287
288 LoadSDNode *LdHi = dyn_cast<LoadSDNode>(stripBitcast(Hi));
289
290 // build_vector lo, (load ptr) -> load_d16_hi ptr, lo
291 // build_vector lo, (zextload ptr from i8) -> load_d16_hi_u8 ptr, lo
292 // build_vector lo, (sextload ptr from i8) -> load_d16_hi_i8 ptr, lo
293
294 // With real true16, if the low half is also a load, leave both as _t16 loads
295 // into 16-bit registers. Tying the low half into a 32-bit d16_hi load makes
296 // it look like a read of the pending low load and forces a wait between the
297 // two loads.
298 bool LoIsT16Load =
299 Subtarget->useRealTrue16Insts() && isa<LoadSDNode>(stripBitcast(Lo));
300
301 // Need to check for possible indirect dependencies on the other half of the
302 // vector to avoid introducing a cycle.
303 if (LdHi && Hi.hasOneUse() && !LoIsT16Load &&
304 !LdHi->isPredecessorOf(Lo.getNode())) {
305 SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
306
307 SDValue TiedIn = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Lo);
308 SDValue Ops[] = {
309 LdHi->getChain(), LdHi->getBasePtr(), TiedIn
310 };
311
312 unsigned LoadOp = AMDGPUISD::LOAD_D16_HI;
313 if (LdHi->getMemoryVT() == MVT::i8) {
314 LoadOp = LdHi->getExtensionType() == ISD::SEXTLOAD ?
315 AMDGPUISD::LOAD_D16_HI_I8 : AMDGPUISD::LOAD_D16_HI_U8;
316 } else {
317 assert(LdHi->getMemoryVT() == MVT::i16);
318 }
319
320 SDValue NewLoadHi =
321 CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdHi), VTList,
322 Ops, LdHi->getMemoryVT(),
323 LdHi->getMemOperand());
324
325 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadHi);
326 CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdHi, 1), NewLoadHi.getValue(1));
327 return true;
328 }
329
330 // build_vector (load ptr), hi -> load_d16_lo ptr, hi
331 // build_vector (zextload ptr from i8), hi -> load_d16_lo_u8 ptr, hi
332 // build_vector (sextload ptr from i8), hi -> load_d16_lo_i8 ptr, hi
333 LoadSDNode *LdLo = dyn_cast<LoadSDNode>(stripBitcast(Lo));
334 if (LdLo && Lo.hasOneUse()) {
335 SDValue TiedIn = getHi16Elt(Hi);
336 if (!TiedIn || LdLo->isPredecessorOf(TiedIn.getNode()))
337 return false;
338
339 SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
340 unsigned LoadOp = AMDGPUISD::LOAD_D16_LO;
341 if (LdLo->getMemoryVT() == MVT::i8) {
342 LoadOp = LdLo->getExtensionType() == ISD::SEXTLOAD ?
343 AMDGPUISD::LOAD_D16_LO_I8 : AMDGPUISD::LOAD_D16_LO_U8;
344 } else {
345 assert(LdLo->getMemoryVT() == MVT::i16);
346 }
347
348 TiedIn = CurDAG->getNode(ISD::BITCAST, SDLoc(N), VT, TiedIn);
349
350 SDValue Ops[] = {
351 LdLo->getChain(), LdLo->getBasePtr(), TiedIn
352 };
353
354 SDValue NewLoadLo =
355 CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdLo), VTList,
356 Ops, LdLo->getMemoryVT(),
357 LdLo->getMemOperand());
358
359 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadLo);
360 CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdLo, 1), NewLoadLo.getValue(1));
361 return true;
362 }
363
364 return false;
365}
366
368 auto *Mem = cast<MemSDNode>(N);
369 EVT VT = N->getValueType(0);
370 if (Mem->getAddressSpace() != AMDGPUAS::REGION_ADDRESS || VT.isVector() ||
371 VT.getSizeInBits() != 16)
372 return false;
373
374 SDLoc SL(N);
375 auto *Ld = dyn_cast<LoadSDNode>(N);
376 ISD::LoadExtType ExtType =
377 Ld ? Ld->getExtensionType() : cast<AtomicSDNode>(N)->getExtensionType();
378 if (ExtType == ISD::NON_EXTLOAD)
379 ExtType = ISD::EXTLOAD;
380
381 EVT MemVT = Mem->getMemoryVT().changeTypeToInteger();
382 SDValue NewLoad =
383 Ld ? CurDAG->getExtLoad(ExtType, SL, MVT::i32, Mem->getChain(),
384 Mem->getBasePtr(), MemVT, Mem->getMemOperand())
385 : CurDAG->getAtomicLoad(ExtType, SL, MemVT, MVT::i32, Mem->getChain(),
386 Mem->getBasePtr(), Mem->getMemOperand());
387
388 SDValue Trunc = CurDAG->getNode(ISD::TRUNCATE, SL, MVT::i16, NewLoad);
389 SDValue Ops[] = {CurDAG->getBitcast(VT, Trunc), NewLoad.getValue(1)};
390 CurDAG->ReplaceAllUsesWith(N, Ops);
391 return true;
392}
393
395 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
396
397 bool MadeChange = false;
398 while (Position != CurDAG->allnodes_begin()) {
399 SDNode *N = &*--Position;
400 if (N->use_empty())
401 continue;
402
403 switch (N->getOpcode()) {
405 // TODO: Match load d16 from shl (extload:i16), 16
406 if (Subtarget->d16PreservesUnusedBits())
407 MadeChange |= matchLoadD16FromBuildVector(N);
408 break;
409 case ISD::LOAD:
410 case ISD::ATOMIC_LOAD:
411 if (Subtarget->useRealTrue16Insts())
412 MadeChange |= widenRegionLoad16(N);
413 break;
414 default:
415 break;
416 }
417 }
418
419 if (MadeChange) {
420 CurDAG->RemoveDeadNodes();
421 LLVM_DEBUG(dbgs() << "After PreProcess:\n";
422 CurDAG->dump(););
423 }
424}
425
426bool AMDGPUDAGToDAGISel::isInlineImmediate(const SDNode *N) const {
427 if (N->isUndef())
428 return true;
429
430 const SIInstrInfo *TII = Subtarget->getInstrInfo();
432 return TII->isInlineConstant(C->getAPIntValue());
433
435 return TII->isInlineConstant(C->getValueAPF());
436
437 return false;
438}
439
440/// Determine the register class for \p OpNo
441/// \returns The register class of the virtual register that will be used for
442/// the given operand number \OpNo or NULL if the register class cannot be
443/// determined.
444const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
445 unsigned OpNo) const {
446 if (!N->isMachineOpcode()) {
447 if (N->getOpcode() == ISD::CopyToReg) {
448 Register Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
449 if (Reg.isVirtual()) {
451 return MRI.getRegClass(Reg);
452 }
453
454 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
455 return TRI->getPhysRegBaseClass(Reg);
456 }
457
458 return nullptr;
459 }
460
461 switch (N->getMachineOpcode()) {
462 default: {
463 const SIInstrInfo *TII = Subtarget->getInstrInfo();
464 const MCInstrDesc &Desc = TII->get(N->getMachineOpcode());
465 unsigned OpIdx = Desc.getNumDefs() + OpNo;
466 if (OpIdx >= Desc.getNumOperands())
467 return nullptr;
468
469 int16_t RegClass = TII->getOpRegClassID(Desc.operands()[OpIdx]);
470 if (RegClass == -1)
471 return nullptr;
472
473 return Subtarget->getRegisterInfo()->getRegClass(RegClass);
474 }
475 case AMDGPU::REG_SEQUENCE: {
476 unsigned RCID = N->getConstantOperandVal(0);
477 const TargetRegisterClass *SuperRC =
478 Subtarget->getRegisterInfo()->getRegClass(RCID);
479
480 SDValue SubRegOp = N->getOperand(OpNo + 1);
481 unsigned SubRegIdx = SubRegOp->getAsZExtVal();
482 return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
483 SubRegIdx);
484 }
485 }
486}
487
488SDNode *AMDGPUDAGToDAGISel::glueCopyToOp(SDNode *N, SDValue NewChain,
489 SDValue Glue) const {
491 Ops.push_back(NewChain); // Replace the chain.
492 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
493 Ops.push_back(N->getOperand(i));
494
495 Ops.push_back(Glue);
496 return CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), Ops);
497}
498
499SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N, SDValue Val) const {
500 const SITargetLowering& Lowering =
501 *static_cast<const SITargetLowering*>(getTargetLowering());
502
503 assert(N->getOperand(0).getValueType() == MVT::Other && "Expected chain");
504
505 SDValue M0 = Lowering.copyToM0(*CurDAG, N->getOperand(0), SDLoc(N), Val);
506 return glueCopyToOp(N, M0, M0.getValue(1));
507}
508
509SDNode *AMDGPUDAGToDAGISel::glueCopyToM0LDSInit(SDNode *N) const {
510 unsigned AS = cast<MemSDNode>(N)->getAddressSpace();
511 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
512 if (Subtarget->ldsRequiresM0Init())
513 return glueCopyToM0(
514 N, CurDAG->getSignedTargetConstant(-1, SDLoc(N), MVT::i32));
515 } else if (AS == AMDGPUAS::REGION_ADDRESS) {
516 MachineFunction &MF = CurDAG->getMachineFunction();
517 unsigned Value = MF.getInfo<SIMachineFunctionInfo>()->getGDSSize();
518 return
519 glueCopyToM0(N, CurDAG->getTargetConstant(Value, SDLoc(N), MVT::i32));
520 }
521 return N;
522}
523
524MachineSDNode *AMDGPUDAGToDAGISel::buildSMovImm64(SDLoc &DL, uint64_t Imm,
525 EVT VT) const {
526 SDNode *Lo = CurDAG->getMachineNode(
527 AMDGPU::S_MOV_B32, DL, MVT::i32,
528 CurDAG->getTargetConstant(Lo_32(Imm), DL, MVT::i32));
529 SDNode *Hi = CurDAG->getMachineNode(
530 AMDGPU::S_MOV_B32, DL, MVT::i32,
531 CurDAG->getTargetConstant(Hi_32(Imm), DL, MVT::i32));
532 const SDValue Ops[] = {
533 CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
534 SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
535 SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
536
537 return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, VT, Ops);
538}
539
540SDNode *AMDGPUDAGToDAGISel::packConstantV2I16(const SDNode *N,
541 SelectionDAG &DAG) const {
542 // TODO: Handle undef as zero
543
544 assert(N->getOpcode() == ISD::BUILD_VECTOR && N->getNumOperands() == 2);
545 uint32_t LHSVal, RHSVal;
546 if (getConstantValue(N->getOperand(0), LHSVal) &&
547 getConstantValue(N->getOperand(1), RHSVal)) {
548 SDLoc SL(N);
549 uint32_t K = (LHSVal & 0xffff) | (RHSVal << 16);
550 return DAG.getMachineNode(
551 isVGPRImm(N) ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32, SL,
552 N->getValueType(0), DAG.getTargetConstant(K, SL, MVT::i32));
553 }
554
555 return nullptr;
556}
557
558void AMDGPUDAGToDAGISel::SelectBuildVector(SDNode *N, unsigned RegClassID) {
559 EVT VT = N->getValueType(0);
560 unsigned NumVectorElts = VT.getVectorNumElements();
561 EVT EltVT = VT.getVectorElementType();
562 SDLoc DL(N);
563 SDValue RegClass = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
564
565 if (NumVectorElts == 1) {
566 CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT, N->getOperand(0),
567 RegClass);
568 return;
569 }
570
571 bool IsGCN = CurDAG->getSubtarget().getTargetTriple().isAMDGCN();
572 if (IsGCN && Subtarget->has64BitLiterals() && VT.getSizeInBits() == 64 &&
573 CurDAG->isConstantValueOfAnyType(SDValue(N, 0))) {
574 uint64_t C = 0;
575 bool AllConst = true;
576 unsigned EltSize = EltVT.getSizeInBits();
577 for (unsigned I = 0; I < NumVectorElts; ++I) {
578 SDValue Op = N->getOperand(I);
579 if (Op.isUndef()) {
580 AllConst = false;
581 break;
582 }
583 uint64_t Val;
585 Val = CF->getValueAPF().bitcastToAPInt().getZExtValue();
586 } else
587 Val = cast<ConstantSDNode>(Op)->getZExtValue();
588 C |= Val << (EltSize * I);
589 }
590 if (AllConst) {
591 SDValue CV = CurDAG->getTargetConstant(C, DL, MVT::i64);
592 MachineSDNode *Copy =
593 CurDAG->getMachineNode(AMDGPU::S_MOV_B64_IMM_PSEUDO, DL, VT, CV);
594 CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, VT, SDValue(Copy, 0),
595 RegClass);
596 return;
597 }
598 }
599
600 assert(NumVectorElts <= 32 && "Vectors with more than 32 elements not "
601 "supported yet");
602 // 32 = Max Num Vector Elements
603 // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
604 // 1 = Vector Register Class
605 SmallVector<SDValue, 32 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
606
607 RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
608 bool IsRegSeq = true;
609 unsigned NOps = N->getNumOperands();
610 unsigned EltSizeInRegs = EltVT.getSizeInBits() / 32;
611 assert(IsGCN || EltSizeInRegs == 1);
612 for (unsigned i = 0; i < NOps; i++) {
613 // XXX: Why is this here?
614 if (isa<RegisterSDNode>(N->getOperand(i))) {
615 IsRegSeq = false;
616 break;
617 }
618 unsigned Sub = IsGCN ? SIRegisterInfo::getSubRegFromChannel(
619 i * EltSizeInRegs, EltSizeInRegs)
621 RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
622 RegSeqArgs[1 + (2 * i) + 1] = CurDAG->getTargetConstant(Sub, DL, MVT::i32);
623 }
624 if (NOps != NumVectorElts) {
625 // Fill in the missing undef elements if this was a scalar_to_vector.
626 assert(N->getOpcode() == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
627 MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
628 DL, EltVT);
629 for (unsigned i = NOps; i < NumVectorElts; ++i) {
630 unsigned Sub = IsGCN ? SIRegisterInfo::getSubRegFromChannel(
631 i * EltSizeInRegs, EltSizeInRegs)
633 RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
634 RegSeqArgs[1 + (2 * i) + 1] =
635 CurDAG->getTargetConstant(Sub, DL, MVT::i32);
636 }
637 }
638
639 if (!IsRegSeq)
640 SelectCode(N);
641 CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(), RegSeqArgs);
642}
643
645 EVT VT = N->getValueType(0);
646 EVT EltVT = VT.getVectorElementType();
647
648 // TODO: Handle 16-bit element vectors with even aligned masks.
649 if (!Subtarget->hasPkMovB32() || !EltVT.bitsEq(MVT::i32) ||
650 VT.getVectorNumElements() != 2) {
651 SelectCode(N);
652 return;
653 }
654
655 auto *SVN = cast<ShuffleVectorSDNode>(N);
656
657 SDValue Src0 = SVN->getOperand(0);
658 SDValue Src1 = SVN->getOperand(1);
659 ArrayRef<int> Mask = SVN->getMask();
660 SDLoc DL(N);
661
662 assert(Src0.getValueType().getVectorNumElements() == 2 && Mask.size() == 2 &&
663 Mask[0] < 4 && Mask[1] < 4);
664
665 SDValue VSrc0 = Mask[0] < 2 ? Src0 : Src1;
666 SDValue VSrc1 = Mask[1] < 2 ? Src0 : Src1;
667 unsigned Src0SubReg = Mask[0] & 1 ? AMDGPU::sub1 : AMDGPU::sub0;
668 unsigned Src1SubReg = Mask[1] & 1 ? AMDGPU::sub1 : AMDGPU::sub0;
669
670 if (Mask[0] < 0) {
671 Src0SubReg = Src1SubReg;
672 MachineSDNode *ImpDef =
673 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
674 VSrc0 = SDValue(ImpDef, 0);
675 }
676
677 if (Mask[1] < 0) {
678 Src1SubReg = Src0SubReg;
679 MachineSDNode *ImpDef =
680 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
681 VSrc1 = SDValue(ImpDef, 0);
682 }
683
684 // SGPR case needs to lower to copies.
685 //
686 // Also use subregister extract when we can directly blend the registers with
687 // a simple subregister copy.
688 //
689 // TODO: Maybe we should fold this out earlier
690 if (N->isDivergent() && Src0SubReg == AMDGPU::sub1 &&
691 Src1SubReg == AMDGPU::sub0) {
692 // The low element of the result always comes from src0.
693 // The high element of the result always comes from src1.
694 // op_sel selects the high half of src0.
695 // op_sel_hi selects the high half of src1.
696
697 unsigned Src0OpSel =
698 Src0SubReg == AMDGPU::sub1 ? SISrcMods::OP_SEL_0 : SISrcMods::NONE;
699 unsigned Src1OpSel =
700 Src1SubReg == AMDGPU::sub1 ? SISrcMods::OP_SEL_0 : SISrcMods::NONE;
701
702 // Enable op_sel_hi to avoid printing it. This should have no effect on the
703 // result.
704 Src0OpSel |= SISrcMods::OP_SEL_1;
705 Src1OpSel |= SISrcMods::OP_SEL_1;
706
707 SDValue Src0OpSelVal = CurDAG->getTargetConstant(Src0OpSel, DL, MVT::i32);
708 SDValue Src1OpSelVal = CurDAG->getTargetConstant(Src1OpSel, DL, MVT::i32);
709 SDValue ZeroMods = CurDAG->getTargetConstant(0, DL, MVT::i32);
710
711 CurDAG->SelectNodeTo(N, AMDGPU::V_PK_MOV_B32, N->getVTList(),
712 {Src0OpSelVal, VSrc0, Src1OpSelVal, VSrc1,
713 ZeroMods, // clamp
714 ZeroMods, // op_sel
715 ZeroMods, // op_sel_hi
716 ZeroMods, // neg_lo
717 ZeroMods}); // neg_hi
718 return;
719 }
720
721 SDValue ResultElt0 =
722 CurDAG->getTargetExtractSubreg(Src0SubReg, DL, EltVT, VSrc0);
723 SDValue ResultElt1 =
724 CurDAG->getTargetExtractSubreg(Src1SubReg, DL, EltVT, VSrc1);
725
726 const SDValue Ops[] = {
727 CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
728 ResultElt0, CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
729 ResultElt1, CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
730 CurDAG->SelectNodeTo(N, TargetOpcode::REG_SEQUENCE, VT, Ops);
731}
732
734 unsigned int Opc = N->getOpcode();
735 if (N->isMachineOpcode()) {
736 N->setNodeId(-1);
737 return; // Already selected.
738 }
739
740 // isa<MemSDNode> almost works but is slightly too permissive for some DS
741 // intrinsics.
742 if (Opc == ISD::LOAD || Opc == ISD::STORE || isa<AtomicSDNode>(N)) {
743 N = glueCopyToM0LDSInit(N);
744 SelectCode(N);
745 return;
746 }
747
748 switch (Opc) {
749 default:
750 break;
751 case ISD::UADDO_CARRY:
752 case ISD::USUBO_CARRY:
753 if (N->getValueType(0) == MVT::i64) {
754 SelectAddcSubbI64(N);
755 return;
756 }
757
758 if (N->getValueType(0) != MVT::i32)
759 break;
760
761 SelectAddcSubb(N);
762 return;
763 case ISD::UADDO:
764 case ISD::USUBO: {
765 if (N->getValueType(0) == MVT::i64) {
766 SelectAddcSubbI64(N);
767 return;
768 }
769
770 SelectUADDO_USUBO(N);
771 return;
772 }
773 case AMDGPUISD::FMUL_W_CHAIN: {
774 SelectFMUL_W_CHAIN(N);
775 return;
776 }
777 case AMDGPUISD::FMA_W_CHAIN: {
778 SelectFMA_W_CHAIN(N);
779 return;
780 }
781
783 case ISD::BUILD_VECTOR: {
784 EVT VT = N->getValueType(0);
785 unsigned NumVectorElts = VT.getVectorNumElements();
786 if (VT.getScalarSizeInBits() == 16) {
787 if (Opc == ISD::BUILD_VECTOR && NumVectorElts == 2) {
788 if (SDNode *Packed = packConstantV2I16(N, *CurDAG)) {
789 ReplaceNode(N, Packed);
790 return;
791 }
792 }
793
794 break;
795 }
796
797 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
798 EVT EltTy = VT.getVectorElementType();
799 assert(EltTy.bitsEq(MVT::i32) || EltTy.bitsEq(MVT::i64));
800 unsigned VecInBits = NumVectorElts * EltTy.getScalarSizeInBits();
801 const TargetRegisterClass *RegClass =
802 N->isDivergent() ? TRI->getDefaultVectorSuperClassForBitWidth(VecInBits)
804
805 SelectBuildVector(N, RegClass->getID());
806 return;
807 }
810 return;
811 case ISD::BUILD_PAIR: {
812 SDValue RC, SubReg0, SubReg1;
813 SDLoc DL(N);
814 if (N->getValueType(0) == MVT::i128) {
815 RC = CurDAG->getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32);
816 SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32);
817 SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32);
818 } else if (N->getValueType(0) == MVT::i64) {
819 RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32);
820 SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
821 SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
822 } else {
823 llvm_unreachable("Unhandled value type for BUILD_PAIR");
824 }
825 const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
826 N->getOperand(1), SubReg1 };
827 ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
828 N->getValueType(0), Ops));
829 return;
830 }
831
832 case ISD::Constant:
833 case ISD::ConstantFP: {
834 if (N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N) ||
835 Subtarget->has64BitLiterals())
836 break;
837
838 uint64_t Imm;
840 Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
842 break;
843 } else {
845 Imm = C->getZExtValue();
847 break;
848 }
849
850 SDLoc DL(N);
851 ReplaceNode(N, buildSMovImm64(DL, Imm, N->getValueType(0)));
852 return;
853 }
854 case AMDGPUISD::BFE_I32:
855 case AMDGPUISD::BFE_U32: {
856 // There is a scalar version available, but unlike the vector version which
857 // has a separate operand for the offset and width, the scalar version packs
858 // the width and offset into a single operand. Try to move to the scalar
859 // version if the offsets are constant, so that we can try to keep extended
860 // loads of kernel arguments in SGPRs.
861
862 // TODO: Technically we could try to pattern match scalar bitshifts of
863 // dynamic values, but it's probably not useful.
865 if (!Offset)
866 break;
867
868 ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
869 if (!Width)
870 break;
871
872 bool Signed = Opc == AMDGPUISD::BFE_I32;
873
874 uint32_t OffsetVal = Offset->getZExtValue();
875 uint32_t WidthVal = Width->getZExtValue();
876
877 ReplaceNode(N, getBFE32(Signed, SDLoc(N), N->getOperand(0), OffsetVal,
878 WidthVal));
879 return;
880 }
881 case AMDGPUISD::DIV_SCALE: {
882 SelectDIV_SCALE(N);
883 return;
884 }
887 SelectMAD_64_32(N);
888 return;
889 }
890 case ISD::SMUL_LOHI:
891 case ISD::UMUL_LOHI:
892 return SelectMUL_LOHI(N);
893 case ISD::CopyToReg: {
895 *static_cast<const SITargetLowering*>(getTargetLowering());
896 N = Lowering.legalizeTargetIndependentNode(N, *CurDAG);
897 break;
898 }
899 case ISD::AND:
900 case ISD::SRL:
901 case ISD::SRA:
903 if (N->getValueType(0) != MVT::i32)
904 break;
905
906 SelectS_BFE(N);
907 return;
908 case ISD::BRCOND:
909 SelectBRCOND(N);
910 return;
911 case ISD::FP_EXTEND:
912 SelectFP_EXTEND(N);
913 return;
914 case AMDGPUISD::CVT_PKRTZ_F16_F32:
915 case AMDGPUISD::CVT_PKNORM_I16_F32:
916 case AMDGPUISD::CVT_PKNORM_U16_F32:
917 case AMDGPUISD::CVT_PK_U16_U32:
918 case AMDGPUISD::CVT_PK_I16_I32: {
919 // Hack around using a legal type if f16 is illegal.
920 if (N->getValueType(0) == MVT::i32) {
921 MVT NewVT = Opc == AMDGPUISD::CVT_PKRTZ_F16_F32 ? MVT::v2f16 : MVT::v2i16;
922 N = CurDAG->MorphNodeTo(N, N->getOpcode(), CurDAG->getVTList(NewVT),
923 { N->getOperand(0), N->getOperand(1) });
924 SelectCode(N);
925 return;
926 }
927
928 break;
929 }
931 SelectINTRINSIC_W_CHAIN(N);
932 return;
933 }
935 SelectINTRINSIC_WO_CHAIN(N);
936 return;
937 }
938 case ISD::INTRINSIC_VOID: {
939 SelectINTRINSIC_VOID(N);
940 return;
941 }
943 SelectWAVE_ADDRESS(N);
944 return;
945 }
946 case ISD::STACKRESTORE: {
947 SelectSTACKRESTORE(N);
948 return;
949 }
950 case ISD::WRITE_REGISTER: {
951 SelectWRITE_REGISTER(N);
952 return;
953 }
954 }
955
956 SelectCode(N);
957}
958
960 if (!Subtarget->hasSDWA())
961 return false;
962
963 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
964 EVT VT = cast<VTSDNode>(N->getOperand(1))->getVT();
965 return VT.getScalarSizeInBits() == 8 || VT.getScalarSizeInBits() == 16;
966 }
967
968 if (N->getOpcode() == ISD::AND)
969 if (auto *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1)))
970 return RHS->getZExtValue() == 0xFF || RHS->getZExtValue() == 0xFFFF;
971
972 if (N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL)
973 if (auto *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1)))
974 return (RHS->getZExtValue() % 8) == 0;
975
976 return false;
977}
978
979bool AMDGPUDAGToDAGISel::isUniformBr(const SDNode *N) const {
980 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
981 const Instruction *Term = BB->getTerminator();
982 return Term->getMetadata("amdgpu.uniform") ||
983 Term->getMetadata("structurizecfg.uniform");
984}
985
986bool AMDGPUDAGToDAGISel::isVRegIdxFoldableAdd(const SDNode *N,
987 unsigned NumDwords) const {
988 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
989 if (!C)
990 return false;
991 int64_t Offset = C->getSExtValue();
992 unsigned NumIndexable =
994 if (Offset < 0 || Offset + NumDwords > NumIndexable)
995 return false;
996 // The pattern matches only a disjoint or, which cannot wrap.
997 return N->getOpcode() == ISD::OR || N->getFlags().hasNoUnsignedWrap() ||
998 CurDAG->SignBitIsZero(N->getOperand(0));
999}
1000
1001bool AMDGPUDAGToDAGISel::isUnneededShiftMask(const SDNode *N,
1002 unsigned ShAmtBits) const {
1003 assert(N->getOpcode() == ISD::AND);
1004
1005 const APInt &RHS = N->getConstantOperandAPInt(1);
1006 if (RHS.countr_one() >= ShAmtBits)
1007 return true;
1008
1009 const APInt &LHSKnownZeros = CurDAG->computeKnownBits(N->getOperand(0)).Zero;
1010 return (LHSKnownZeros | RHS).countr_one() >= ShAmtBits;
1011}
1012
1014 SDValue &N0, SDValue &N1) {
1015 if (Addr.getValueType() == MVT::i64 && Addr.getOpcode() == ISD::BITCAST &&
1016 Addr.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
1017 // As we split 64-bit `or` earlier, it's complicated pattern to match, i.e.
1018 // (i64 (bitcast (v2i32 (build_vector
1019 // (or (extract_vector_elt V, 0), OFFSET),
1020 // (extract_vector_elt V, 1)))))
1021 SDValue Lo = Addr.getOperand(0).getOperand(0);
1022 if (Lo.getOpcode() == ISD::OR && DAG.isBaseWithConstantOffset(Lo)) {
1023 SDValue BaseLo = Lo.getOperand(0);
1024 SDValue BaseHi = Addr.getOperand(0).getOperand(1);
1025 // Check that split base (Lo and Hi) are extracted from the same one.
1026 if (BaseLo.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
1027 BaseHi.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
1028 BaseLo.getOperand(0) == BaseHi.getOperand(0) &&
1029 // Lo is statically extracted from index 0.
1030 isa<ConstantSDNode>(BaseLo.getOperand(1)) &&
1031 BaseLo.getConstantOperandVal(1) == 0 &&
1032 // Hi is statically extracted from index 0.
1033 isa<ConstantSDNode>(BaseHi.getOperand(1)) &&
1034 BaseHi.getConstantOperandVal(1) == 1) {
1035 N0 = BaseLo.getOperand(0).getOperand(0);
1036 N1 = Lo.getOperand(1);
1037 return true;
1038 }
1039 }
1040 }
1041 return false;
1042}
1043
1044bool AMDGPUDAGToDAGISel::isBaseWithConstantOffset64(SDValue Addr, SDValue &LHS,
1045 SDValue &RHS) const {
1046 if (CurDAG->isBaseWithConstantOffset(Addr)) {
1047 LHS = Addr.getOperand(0);
1048 RHS = Addr.getOperand(1);
1049 return true;
1050 }
1051
1054 return true;
1055 }
1056
1057 return false;
1058}
1059
1061 return "AMDGPU DAG->DAG Pattern Instruction Selection";
1062}
1063
1067
1072 .getManager();
1073 auto &F = MF.getFunction();
1074 // UniformityInfoAnalysis is optional in generic dag isel,
1075 // AMDGPUISelDAGToDAGPass requires it, calculate it explicitly.
1076 FAM.getResult<UniformityInfoAnalysis>(F);
1077#ifdef EXPENSIVE_CHECKS
1078 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1079 LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
1080 for (auto &L : LI.getLoopsInPreorder())
1081 assert(L->isLCSSAForm(DT) && "Loop is not in LCSSA form!");
1082#endif
1083 return SelectionDAGISelPass::run(MF, MFAM);
1084}
1085
1086//===----------------------------------------------------------------------===//
1087// Complex Patterns
1088//===----------------------------------------------------------------------===//
1089
1090bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
1091 SDValue &Offset) {
1092 return false;
1093}
1094
1095bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
1096 SDValue &Offset) {
1098 SDLoc DL(Addr);
1099
1100 if ((C = dyn_cast<ConstantSDNode>(Addr))) {
1101 Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
1102 Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
1103 } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
1104 (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
1105 Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
1106 Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
1107 } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
1108 (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
1109 Base = Addr.getOperand(0);
1110 Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
1111 } else {
1112 Base = Addr;
1113 Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1114 }
1115
1116 return true;
1117}
1118
1119SDValue AMDGPUDAGToDAGISel::getMaterializedScalarImm32(int64_t Val,
1120 const SDLoc &DL) const {
1121 SDNode *Mov = CurDAG->getMachineNode(
1122 AMDGPU::S_MOV_B32, DL, MVT::i32,
1123 CurDAG->getTargetConstant(Val, DL, MVT::i32));
1124 return SDValue(Mov, 0);
1125}
1126
1127void AMDGPUDAGToDAGISel::SelectAddcSubb(SDNode *N) {
1128 SDValue LHS = N->getOperand(0);
1129 SDValue RHS = N->getOperand(1);
1130 SDValue CI = N->getOperand(2);
1131
1132 if (N->isDivergent()) {
1133 unsigned Opc = N->getOpcode() == ISD::UADDO_CARRY ? AMDGPU::V_ADDC_U32_e64
1134 : AMDGPU::V_SUBB_U32_e64;
1135 CurDAG->SelectNodeTo(
1136 N, Opc, N->getVTList(),
1137 {LHS, RHS, CI,
1138 CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
1139 } else {
1140 unsigned Opc = N->getOpcode() == ISD::UADDO_CARRY ? AMDGPU::S_ADD_CO_PSEUDO
1141 : AMDGPU::S_SUB_CO_PSEUDO;
1142 CurDAG->SelectNodeTo(N, Opc, N->getVTList(), {LHS, RHS, CI});
1143 }
1144}
1145
1146void AMDGPUDAGToDAGISel::SelectAddcSubbI64(SDNode *N) {
1147 SDLoc DL(N);
1148 SDValue LHS = N->getOperand(0);
1149 SDValue RHS = N->getOperand(1);
1150
1151 unsigned Opcode = N->getOpcode();
1152 bool ConsumeCarry = Opcode == ISD::UADDO_CARRY || Opcode == ISD::USUBO_CARRY;
1153 bool IsAdd = Opcode == ISD::UADDO || Opcode == ISD::UADDO_CARRY;
1154
1155 SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
1156 SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
1157
1158 SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1159 MVT::i32, LHS, Sub0);
1160 SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1161 MVT::i32, LHS, Sub1);
1162
1163 SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1164 MVT::i32, RHS, Sub0);
1165 SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1166 MVT::i32, RHS, Sub1);
1167
1168 SDVTList VTList = CurDAG->getVTList(MVT::i32, N->getValueType(1));
1169
1170 static const unsigned NoCarryOpcMap[2][2] = {
1171 {AMDGPU::S_USUBO_PSEUDO, AMDGPU::S_UADDO_PSEUDO},
1172 {AMDGPU::V_SUB_CO_U32_e64, AMDGPU::V_ADD_CO_U32_e64}};
1173 static const unsigned CarryOpcMap[2][2] = {
1174 {AMDGPU::S_SUB_CO_PSEUDO, AMDGPU::S_ADD_CO_PSEUDO},
1175 {AMDGPU::V_SUBB_U32_e64, AMDGPU::V_ADDC_U32_e64}};
1176
1177 bool IsVALU = N->isDivergent();
1178
1179 unsigned NoCarryOpc = NoCarryOpcMap[IsVALU][IsAdd];
1180 unsigned CarryOpc = CarryOpcMap[IsVALU][IsAdd];
1181 SDValue Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
1182
1183 SDNode *AddLo;
1184 if (!ConsumeCarry) {
1185 if (IsVALU) {
1186 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0), Clamp};
1187 AddLo = CurDAG->getMachineNode(NoCarryOpc, DL, VTList, Args);
1188 } else {
1189 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0)};
1190 AddLo = CurDAG->getMachineNode(NoCarryOpc, DL, VTList, Args);
1191 }
1192 } else {
1193 if (IsVALU) {
1194 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(2),
1195 Clamp};
1196 AddLo = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
1197 } else {
1198 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(2)};
1199 AddLo = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
1200 }
1201 }
1202
1203 SDNode *AddHi;
1204 if (IsVALU) {
1205 SDValue Args[] = {SDValue(Hi0, 0), SDValue(Hi1, 0), SDValue(AddLo, 1),
1206 Clamp};
1207 AddHi = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
1208 } else {
1209 SDValue Args[] = {SDValue(Hi0, 0), SDValue(Hi1, 0), SDValue(AddLo, 1)};
1210 AddHi = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
1211 }
1212
1213 unsigned RC = IsVALU ? AMDGPU::VReg_64RegClassID : AMDGPU::SReg_64RegClassID;
1214 SDValue RegSequenceArgs[] = {CurDAG->getTargetConstant(RC, DL, MVT::i32),
1215 SDValue(AddLo, 0), Sub0, SDValue(AddHi, 0),
1216 Sub1};
1217 SDNode *RegSequence = CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1218 MVT::i64, RegSequenceArgs);
1219
1220 ReplaceUses(SDValue(N, 1), SDValue(AddHi, 1));
1221 ReplaceNode(N, RegSequence);
1222}
1223
1224void AMDGPUDAGToDAGISel::SelectUADDO_USUBO(SDNode *N) {
1225 // The name of the opcodes are misleading. v_add_i32/v_sub_i32 have unsigned
1226 // carry out despite the _i32 name. These were renamed in VI to _U32.
1227 // FIXME: We should probably rename the opcodes here.
1228 bool IsAdd = N->getOpcode() == ISD::UADDO;
1229 bool IsVALU = N->isDivergent();
1230
1231 for (SDNode::user_iterator UI = N->user_begin(), E = N->user_end(); UI != E;
1232 ++UI)
1233 if (UI.getUse().getResNo() == 1) {
1234 if (UI->isMachineOpcode()) {
1235 if (UI->getMachineOpcode() !=
1236 (IsAdd ? AMDGPU::S_ADD_CO_PSEUDO : AMDGPU::S_SUB_CO_PSEUDO)) {
1237 IsVALU = true;
1238 break;
1239 }
1240 } else {
1241 if (UI->getOpcode() != (IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY)) {
1242 IsVALU = true;
1243 break;
1244 }
1245 }
1246 }
1247
1248 if (IsVALU) {
1249 unsigned Opc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
1250
1251 CurDAG->SelectNodeTo(
1252 N, Opc, N->getVTList(),
1253 {N->getOperand(0), N->getOperand(1),
1254 CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
1255 } else {
1256 unsigned Opc = IsAdd ? AMDGPU::S_UADDO_PSEUDO : AMDGPU::S_USUBO_PSEUDO;
1257
1258 CurDAG->SelectNodeTo(N, Opc, N->getVTList(),
1259 {N->getOperand(0), N->getOperand(1)});
1260 }
1261}
1262
1263void AMDGPUDAGToDAGISel::SelectFMA_W_CHAIN(SDNode *N) {
1264 // src0_modifiers, src0, src1_modifiers, src1, src2_modifiers, src2, clamp, omod
1265 SDValue Ops[10];
1266
1267 SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[6], Ops[7]);
1268 SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
1269 SelectVOP3Mods(N->getOperand(3), Ops[5], Ops[4]);
1270 Ops[8] = N->getOperand(0);
1271 Ops[9] = N->getOperand(4);
1272
1273 // If there are no source modifiers, prefer fmac over fma because it can use
1274 // the smaller VOP2 encoding.
1275 bool UseFMAC = Subtarget->hasDLInsts() &&
1276 cast<ConstantSDNode>(Ops[0])->isZero() &&
1277 cast<ConstantSDNode>(Ops[2])->isZero() &&
1278 cast<ConstantSDNode>(Ops[4])->isZero();
1279 unsigned Opcode = UseFMAC ? AMDGPU::V_FMAC_F32_e64 : AMDGPU::V_FMA_F32_e64;
1280 CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), Ops);
1281}
1282
1283void AMDGPUDAGToDAGISel::SelectFMUL_W_CHAIN(SDNode *N) {
1284 // src0_modifiers, src0, src1_modifiers, src1, clamp, omod
1285 SDValue Ops[8];
1286
1287 SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[4], Ops[5]);
1288 SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
1289 Ops[6] = N->getOperand(0);
1290 Ops[7] = N->getOperand(3);
1291
1292 CurDAG->SelectNodeTo(N, AMDGPU::V_MUL_F32_e64, N->getVTList(), Ops);
1293}
1294
1295// We need to handle this here because tablegen doesn't support matching
1296// instructions with multiple outputs.
1297void AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
1298 EVT VT = N->getValueType(0);
1299
1300 assert(VT == MVT::f32 || VT == MVT::f64);
1301
1302 unsigned Opc
1303 = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64_e64 : AMDGPU::V_DIV_SCALE_F32_e64;
1304
1305 // src0_modifiers, src0, src1_modifiers, src1, src2_modifiers, src2, clamp,
1306 // omod
1307 SDValue Ops[8];
1308 SelectVOP3BMods0(N->getOperand(0), Ops[1], Ops[0], Ops[6], Ops[7]);
1309 SelectVOP3BMods(N->getOperand(1), Ops[3], Ops[2]);
1310 SelectVOP3BMods(N->getOperand(2), Ops[5], Ops[4]);
1311 CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1312}
1313
1314// We need to handle this here because tablegen doesn't support matching
1315// instructions with multiple outputs.
1316void AMDGPUDAGToDAGISel::SelectMAD_64_32(SDNode *N) {
1317 SDLoc SL(N);
1318 bool Signed = N->getOpcode() == AMDGPUISD::MAD_I64_I32;
1319 unsigned Opc;
1320 bool UseNoCarry = Subtarget->hasMadNC64_32Insts() && !N->hasAnyUseOfValue(1);
1321 if (Subtarget->hasMADIntraFwdBug())
1322 Opc = Signed ? AMDGPU::V_MAD_I64_I32_gfx11_e64
1323 : AMDGPU::V_MAD_U64_U32_gfx11_e64;
1324 else if (UseNoCarry)
1325 Opc = Signed ? AMDGPU::V_MAD_NC_I64_I32_e64 : AMDGPU::V_MAD_NC_U64_U32_e64;
1326 else
1327 Opc = Signed ? AMDGPU::V_MAD_I64_I32_e64 : AMDGPU::V_MAD_U64_U32_e64;
1328
1329 SDValue Clamp = CurDAG->getTargetConstant(0, SL, MVT::i1);
1330 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
1331 Clamp };
1332
1333 if (UseNoCarry) {
1334 MachineSDNode *Mad = CurDAG->getMachineNode(Opc, SL, MVT::i64, Ops);
1335 ReplaceUses(SDValue(N, 0), SDValue(Mad, 0));
1336 CurDAG->RemoveDeadNode(N);
1337 return;
1338 }
1339
1340 CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1341}
1342
1343// We need to handle this here because tablegen doesn't support matching
1344// instructions with multiple outputs.
1345void AMDGPUDAGToDAGISel::SelectMUL_LOHI(SDNode *N) {
1346 SDLoc SL(N);
1347 bool Signed = N->getOpcode() == ISD::SMUL_LOHI;
1348 SDVTList VTList;
1349 unsigned Opc;
1350 if (Subtarget->hasMadNC64_32Insts()) {
1351 VTList = CurDAG->getVTList(MVT::i64);
1352 Opc = Signed ? AMDGPU::V_MAD_NC_I64_I32_e64 : AMDGPU::V_MAD_NC_U64_U32_e64;
1353 } else {
1354 VTList = CurDAG->getVTList(MVT::i64, MVT::i1);
1355 if (Subtarget->hasMADIntraFwdBug()) {
1356 Opc = Signed ? AMDGPU::V_MAD_I64_I32_gfx11_e64
1357 : AMDGPU::V_MAD_U64_U32_gfx11_e64;
1358 } else {
1359 Opc = Signed ? AMDGPU::V_MAD_I64_I32_e64 : AMDGPU::V_MAD_U64_U32_e64;
1360 }
1361 }
1362
1363 SDValue Zero = CurDAG->getTargetConstant(0, SL, MVT::i64);
1364 SDValue Clamp = CurDAG->getTargetConstant(0, SL, MVT::i1);
1365 SDValue Ops[] = {N->getOperand(0), N->getOperand(1), Zero, Clamp};
1366 SDNode *Mad = CurDAG->getMachineNode(Opc, SL, VTList, Ops);
1367 if (!SDValue(N, 0).use_empty()) {
1368 SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32);
1369 SDNode *Lo = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, SL,
1370 MVT::i32, SDValue(Mad, 0), Sub0);
1371 ReplaceUses(SDValue(N, 0), SDValue(Lo, 0));
1372 }
1373 if (!SDValue(N, 1).use_empty()) {
1374 SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32);
1375 SDNode *Hi = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, SL,
1376 MVT::i32, SDValue(Mad, 0), Sub1);
1377 ReplaceUses(SDValue(N, 1), SDValue(Hi, 0));
1378 }
1379 CurDAG->RemoveDeadNode(N);
1380}
1381
1382bool AMDGPUDAGToDAGISel::isDSOffsetLegal(SDValue Base, unsigned Offset) const {
1383 if (!isUInt<16>(Offset))
1384 return false;
1385
1386 if (!Base || Subtarget->hasUsableDSOffset() ||
1387 Subtarget->unsafeDSOffsetFoldingEnabled())
1388 return true;
1389
1390 // On Southern Islands instruction with a negative base value and an offset
1391 // don't seem to work.
1392 return CurDAG->SignBitIsZero(Base);
1393}
1394
1395bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
1396 SDValue &Offset) const {
1397 SDLoc DL(Addr);
1398 if (CurDAG->isBaseWithConstantOffset(Addr)) {
1399 SDValue N0 = Addr.getOperand(0);
1400 SDValue N1 = Addr.getOperand(1);
1401 ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1402 if (isDSOffsetLegal(N0, C1->getSExtValue())) {
1403 // (add n0, c0)
1404 Base = N0;
1405 Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1406 return true;
1407 }
1408 } else if (Addr.getOpcode() == ISD::SUB) {
1409 // sub C, x -> add (sub 0, x), C
1410 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1411 int64_t ByteOffset = C->getSExtValue();
1412 if (isDSOffsetLegal(SDValue(), ByteOffset)) {
1413 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1414
1415 // XXX - This is kind of hacky. Create a dummy sub node so we can check
1416 // the known bits in isDSOffsetLegal. We need to emit the selected node
1417 // here, so this is thrown away.
1418 SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
1419 Zero, Addr.getOperand(1));
1420
1421 if (isDSOffsetLegal(Sub, ByteOffset)) {
1423 Opnds.push_back(Zero);
1424 Opnds.push_back(Addr.getOperand(1));
1425
1426 // FIXME: Select to VOP3 version for with-carry.
1427 unsigned SubOp = AMDGPU::V_SUB_CO_U32_e32;
1428 if (Subtarget->hasAddNoCarryInsts()) {
1429 SubOp = AMDGPU::V_SUB_U32_e64;
1430 Opnds.push_back(
1431 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1432 }
1433
1434 MachineSDNode *MachineSub =
1435 CurDAG->getMachineNode(SubOp, DL, MVT::i32, Opnds);
1436
1437 Base = SDValue(MachineSub, 0);
1438 Offset = CurDAG->getTargetConstant(ByteOffset, DL, MVT::i16);
1439 return true;
1440 }
1441 }
1442 }
1443 } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1444 // If we have a constant address, prefer to put the constant into the
1445 // offset. This can save moves to load the constant address since multiple
1446 // operations can share the zero base address register, and enables merging
1447 // into read2 / write2 instructions.
1448
1449 SDLoc DL(Addr);
1450
1451 if (isDSOffsetLegal(SDValue(), CAddr->getZExtValue())) {
1452 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1453 MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1454 DL, MVT::i32, Zero);
1455 Base = SDValue(MovZero, 0);
1456 Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1457 return true;
1458 }
1459 }
1460
1461 // default case
1462 Base = Addr;
1463 Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i16);
1464 return true;
1465}
1466
1467bool AMDGPUDAGToDAGISel::isDSOffset2Legal(SDValue Base, unsigned Offset0,
1468 unsigned Offset1,
1469 unsigned Size) const {
1470 if (Offset0 % Size != 0 || Offset1 % Size != 0)
1471 return false;
1472 if (!isUInt<8>(Offset0 / Size) || !isUInt<8>(Offset1 / Size))
1473 return false;
1474
1475 if (!Base || Subtarget->hasUsableDSOffset() ||
1476 Subtarget->unsafeDSOffsetFoldingEnabled())
1477 return true;
1478
1479 // On Southern Islands instruction with a negative base value and an offset
1480 // don't seem to work.
1481 return CurDAG->SignBitIsZero(Base);
1482}
1483
1484// Return whether the operation has NoUnsignedWrap property.
1485static bool isNoUnsignedWrap(SDValue Addr) {
1486 return (Addr.getOpcode() == ISD::ADD &&
1487 Addr->getFlags().hasNoUnsignedWrap()) ||
1488 Addr->getOpcode() == ISD::OR;
1489}
1490
1491// Check that the base address of flat scratch load/store in the form of `base +
1492// offset` is legal to be put in SGPR/VGPR (i.e. unsigned per hardware
1493// requirement). We always treat the first operand as the base address here.
1494bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegal(SDValue Addr) const {
1495 if (isNoUnsignedWrap(Addr))
1496 return true;
1497
1498 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1499 // values.
1500 if (Subtarget->hasSignedScratchOffsets())
1501 return true;
1502
1503 auto LHS = Addr.getOperand(0);
1504 auto RHS = Addr.getOperand(1);
1505
1506 // If the immediate offset is negative and within certain range, the base
1507 // address cannot also be negative. If the base is also negative, the sum
1508 // would be either negative or much larger than the valid range of scratch
1509 // memory a thread can access.
1510 ConstantSDNode *ImmOp = nullptr;
1511 if (Addr.getOpcode() == ISD::ADD && (ImmOp = dyn_cast<ConstantSDNode>(RHS))) {
1512 if (ImmOp->getSExtValue() < 0 && ImmOp->getSExtValue() > -0x40000000)
1513 return true;
1514 }
1515
1516 return CurDAG->SignBitIsZero(LHS);
1517}
1518
1519// Check address value in SGPR/VGPR are legal for flat scratch in the form
1520// of: SGPR + VGPR.
1521bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegalSV(SDValue Addr) const {
1522 if (isNoUnsignedWrap(Addr))
1523 return true;
1524
1525 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1526 // values.
1527 if (Subtarget->hasSignedScratchOffsets())
1528 return true;
1529
1530 auto LHS = Addr.getOperand(0);
1531 auto RHS = Addr.getOperand(1);
1532 return CurDAG->SignBitIsZero(RHS) && CurDAG->SignBitIsZero(LHS);
1533}
1534
1535// Check address value in SGPR/VGPR are legal for flat scratch in the form
1536// of: SGPR + VGPR + Imm.
1537bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegalSVImm(SDValue Addr) const {
1538 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1539 // values.
1540 if (AMDGPU::isGFX12Plus(*Subtarget))
1541 return true;
1542
1543 auto Base = Addr.getOperand(0);
1544 auto *RHSImm = cast<ConstantSDNode>(Addr.getOperand(1));
1545 // If the immediate offset is negative and within certain range, the base
1546 // address cannot also be negative. If the base is also negative, the sum
1547 // would be either negative or much larger than the valid range of scratch
1548 // memory a thread can access.
1549 if (isNoUnsignedWrap(Base) &&
1550 (isNoUnsignedWrap(Addr) ||
1551 (RHSImm->getSExtValue() < 0 && RHSImm->getSExtValue() > -0x40000000)))
1552 return true;
1553
1554 auto LHS = Base.getOperand(0);
1555 auto RHS = Base.getOperand(1);
1556 return CurDAG->SignBitIsZero(RHS) && CurDAG->SignBitIsZero(LHS);
1557}
1558
1559// TODO: If offset is too big, put low 16-bit into offset.
1560bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
1561 SDValue &Offset0,
1562 SDValue &Offset1) const {
1563 return SelectDSReadWrite2(Addr, Base, Offset0, Offset1, 4);
1564}
1565
1566bool AMDGPUDAGToDAGISel::SelectDS128Bit8ByteAligned(SDValue Addr, SDValue &Base,
1567 SDValue &Offset0,
1568 SDValue &Offset1) const {
1569 return SelectDSReadWrite2(Addr, Base, Offset0, Offset1, 8);
1570}
1571
1572bool AMDGPUDAGToDAGISel::SelectDSReadWrite2(SDValue Addr, SDValue &Base,
1573 SDValue &Offset0, SDValue &Offset1,
1574 unsigned Size) const {
1575 SDLoc DL(Addr);
1576
1577 if (CurDAG->isBaseWithConstantOffset(Addr)) {
1578 SDValue N0 = Addr.getOperand(0);
1579 SDValue N1 = Addr.getOperand(1);
1580 ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1581 unsigned OffsetValue0 = C1->getZExtValue();
1582 unsigned OffsetValue1 = OffsetValue0 + Size;
1583
1584 // (add n0, c0)
1585 if (isDSOffset2Legal(N0, OffsetValue0, OffsetValue1, Size)) {
1586 Base = N0;
1587 Offset0 = CurDAG->getTargetConstant(OffsetValue0 / Size, DL, MVT::i32);
1588 Offset1 = CurDAG->getTargetConstant(OffsetValue1 / Size, DL, MVT::i32);
1589 return true;
1590 }
1591 } else if (Addr.getOpcode() == ISD::SUB) {
1592 // sub C, x -> add (sub 0, x), C
1593 if (const ConstantSDNode *C =
1595 unsigned OffsetValue0 = C->getZExtValue();
1596 unsigned OffsetValue1 = OffsetValue0 + Size;
1597
1598 if (isDSOffset2Legal(SDValue(), OffsetValue0, OffsetValue1, Size)) {
1599 SDLoc DL(Addr);
1600 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1601
1602 // XXX - This is kind of hacky. Create a dummy sub node so we can check
1603 // the known bits in isDSOffsetLegal. We need to emit the selected node
1604 // here, so this is thrown away.
1605 SDValue Sub =
1606 CurDAG->getNode(ISD::SUB, DL, MVT::i32, Zero, Addr.getOperand(1));
1607
1608 if (isDSOffset2Legal(Sub, OffsetValue0, OffsetValue1, Size)) {
1610 Opnds.push_back(Zero);
1611 Opnds.push_back(Addr.getOperand(1));
1612 unsigned SubOp = AMDGPU::V_SUB_CO_U32_e32;
1613 if (Subtarget->hasAddNoCarryInsts()) {
1614 SubOp = AMDGPU::V_SUB_U32_e64;
1615 Opnds.push_back(
1616 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1617 }
1618
1619 MachineSDNode *MachineSub = CurDAG->getMachineNode(
1620 SubOp, DL, MVT::getIntegerVT(Size * 8), Opnds);
1621
1622 Base = SDValue(MachineSub, 0);
1623 Offset0 =
1624 CurDAG->getTargetConstant(OffsetValue0 / Size, DL, MVT::i32);
1625 Offset1 =
1626 CurDAG->getTargetConstant(OffsetValue1 / Size, DL, MVT::i32);
1627 return true;
1628 }
1629 }
1630 }
1631 } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1632 unsigned OffsetValue0 = CAddr->getZExtValue();
1633 unsigned OffsetValue1 = OffsetValue0 + Size;
1634
1635 if (isDSOffset2Legal(SDValue(), OffsetValue0, OffsetValue1, Size)) {
1636 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1637 MachineSDNode *MovZero =
1638 CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, Zero);
1639 Base = SDValue(MovZero, 0);
1640 Offset0 = CurDAG->getTargetConstant(OffsetValue0 / Size, DL, MVT::i32);
1641 Offset1 = CurDAG->getTargetConstant(OffsetValue1 / Size, DL, MVT::i32);
1642 return true;
1643 }
1644 }
1645
1646 // default case
1647
1648 Base = Addr;
1649 Offset0 = CurDAG->getTargetConstant(0, DL, MVT::i32);
1650 Offset1 = CurDAG->getTargetConstant(1, DL, MVT::i32);
1651 return true;
1652}
1653
1654bool AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr, SDValue &VAddr,
1655 SDValue &SOffset, SDValue &Offset,
1656 SDValue &Offen, SDValue &Idxen,
1657 SDValue &Addr64) const {
1658 // Subtarget prefers to use flat instruction
1659 // FIXME: This should be a pattern predicate and not reach here
1660 if (Subtarget->useFlatForGlobal())
1661 return false;
1662
1663 bool Is32Bit = Addr.getValueType() == MVT::i32;
1664 SDLoc DL(Addr);
1665
1666 Idxen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1667 Offen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1668 Addr64 = CurDAG->getTargetConstant(0, DL, MVT::i1);
1669 SOffset = Subtarget->hasRestrictedSOffset()
1670 ? CurDAG->getRegister(AMDGPU::SGPR_NULL, MVT::i32)
1671 : CurDAG->getTargetConstant(0, DL, MVT::i32);
1672
1673 ConstantSDNode *C1 = nullptr;
1674 SDValue N0 = Addr;
1675 if ((!Is32Bit || isNoUnsignedWrap(Addr)) &&
1676 CurDAG->isBaseWithConstantOffset(Addr)) {
1678 if (isUInt<32>(C1->getZExtValue()))
1679 N0 = Addr.getOperand(0);
1680 else
1681 C1 = nullptr;
1682 }
1683
1684 N0 = Expand32BitAddress(N0);
1685 if (N0->isAnyAdd()) {
1686 // (add N2, N3) -> addr64, or
1687 // (add (add N2, N3), C1) -> addr64
1688 SDValue N2 = N0.getOperand(0);
1689 SDValue N3 = N0.getOperand(1);
1690 Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1691
1692 if (N2->isDivergent()) {
1693 if (N3->isDivergent()) {
1694 // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
1695 // addr64, and construct the resource from a 0 address.
1696 Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1697 VAddr = N0;
1698 } else {
1699 // N2 is divergent, N3 is not.
1700 Ptr = N3;
1701 VAddr = N2;
1702 }
1703 } else {
1704 // N2 is not divergent.
1705 Ptr = N2;
1706 VAddr = N3;
1707 }
1708 Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1709 } else if (N0->isDivergent()) {
1710 // N0 is divergent. Use it as the addr64, and construct the resource from a
1711 // 0 address.
1712 Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1713 VAddr = N0;
1714 Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1715 } else {
1716 // N0 -> offset, or
1717 // (N0 + C1) -> offset
1718 VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
1719 Ptr = N0;
1720 }
1721
1722 if (!C1) {
1723 // No offset.
1724 Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1725 return true;
1726 }
1727
1728 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1729 if (TII->isLegalMUBUFImmOffset(C1->getZExtValue())) {
1730 // Legal offset for instruction.
1731 Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
1732 return true;
1733 }
1734
1735 // Illegal offset, store it in soffset.
1736 Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1737 SOffset =
1738 SDValue(CurDAG->getMachineNode(
1739 AMDGPU::S_MOV_B32, DL, MVT::i32,
1740 CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32)),
1741 0);
1742 return true;
1743}
1744
1745bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1746 SDValue &VAddr, SDValue &SOffset,
1747 SDValue &Offset) const {
1748 SDValue Ptr, Offen, Idxen, Addr64;
1749
1750 // addr64 bit was removed for volcanic islands.
1751 // FIXME: This should be a pattern predicate and not reach here
1752 if (!Subtarget->hasAddr64())
1753 return false;
1754
1755 if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64))
1756 return false;
1757
1758 ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
1759 if (C->getSExtValue()) {
1760 SDLoc DL(Addr);
1761
1762 const SITargetLowering& Lowering =
1763 *static_cast<const SITargetLowering*>(getTargetLowering());
1764
1765 SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
1766 return true;
1767 }
1768
1769 return false;
1770}
1771
1772std::pair<SDValue, SDValue> AMDGPUDAGToDAGISel::foldFrameIndex(SDValue N) const {
1773 SDLoc DL(N);
1774
1775 auto *FI = dyn_cast<FrameIndexSDNode>(N);
1776 SDValue TFI =
1777 FI ? CurDAG->getTargetFrameIndex(FI->getIndex(), FI->getValueType(0)) : N;
1778
1779 // We rebase the base address into an absolute stack address and hence
1780 // use constant 0 for soffset. This value must be retained until
1781 // frame elimination and eliminateFrameIndex will choose the appropriate
1782 // frame register if need be.
1783 return std::pair(TFI, CurDAG->getTargetConstant(0, DL, MVT::i32));
1784}
1785
1786bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(SDNode *Parent,
1787 SDValue Addr, SDValue &Rsrc,
1788 SDValue &VAddr, SDValue &SOffset,
1789 SDValue &ImmOffset) const {
1790
1791 SDLoc DL(Addr);
1792 MachineFunction &MF = CurDAG->getMachineFunction();
1793 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1794
1795 Rsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1796
1797 if (ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1798 int64_t Imm = CAddr->getSExtValue();
1799 const int64_t NullPtr =
1801 // Don't fold null pointer.
1802 if (Imm != NullPtr) {
1803 const int64_t MaxOffset = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
1804 SDValue HighBits =
1805 CurDAG->getTargetConstant(Imm & ~MaxOffset, DL, MVT::i32);
1806 MachineSDNode *MovHighBits = CurDAG->getMachineNode(
1807 AMDGPU::V_MOV_B32_e32, DL, MVT::i32, HighBits);
1808 VAddr = SDValue(MovHighBits, 0);
1809
1810 SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1811 ImmOffset = CurDAG->getTargetConstant(Imm & MaxOffset, DL, MVT::i32);
1812 return true;
1813 }
1814 }
1815
1816 if (CurDAG->isBaseWithConstantOffset(Addr)) {
1817 // (add n0, c1)
1818
1819 SDValue N0 = Addr.getOperand(0);
1821
1822 // Offsets in vaddr must be positive if range checking is enabled.
1823 //
1824 // The total computation of vaddr + soffset + offset must not overflow. If
1825 // vaddr is negative, even if offset is 0 the sgpr offset add will end up
1826 // overflowing.
1827 //
1828 // Prior to gfx9, MUBUF instructions with the vaddr offset enabled would
1829 // always perform a range check. If a negative vaddr base index was used,
1830 // this would fail the range check. The overall address computation would
1831 // compute a valid address, but this doesn't happen due to the range
1832 // check. For out-of-bounds MUBUF loads, a 0 is returned.
1833 //
1834 // Therefore it should be safe to fold any VGPR offset on gfx9 into the
1835 // MUBUF vaddr, but not on older subtargets which can only do this if the
1836 // sign bit is known 0.
1837 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1838 if (TII->isLegalMUBUFImmOffset(C1) &&
1839 (!Subtarget->privateMemoryResourceIsRangeChecked() ||
1840 CurDAG->SignBitIsZero(N0))) {
1841 std::tie(VAddr, SOffset) = foldFrameIndex(N0);
1842 ImmOffset = CurDAG->getTargetConstant(C1, DL, MVT::i32);
1843 return true;
1844 }
1845 }
1846
1847 // (node)
1848 std::tie(VAddr, SOffset) = foldFrameIndex(Addr);
1849 ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1850 return true;
1851}
1852
1853static bool IsCopyFromSGPR(const SIRegisterInfo &TRI, SDValue Val) {
1854 if (Val.getOpcode() != ISD::CopyFromReg)
1855 return false;
1856 auto Reg = cast<RegisterSDNode>(Val.getOperand(1))->getReg();
1857 if (!Reg.isPhysical())
1858 return false;
1859 const auto *RC = TRI.getPhysRegBaseClass(Reg);
1860 return RC && TRI.isSGPRClass(RC);
1861}
1862
1863bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffset(SDNode *Parent,
1864 SDValue Addr,
1865 SDValue &SRsrc,
1866 SDValue &SOffset,
1867 SDValue &Offset) const {
1868 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
1869 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1870 MachineFunction &MF = CurDAG->getMachineFunction();
1871 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1872 SDLoc DL(Addr);
1873
1874 // CopyFromReg <sgpr>
1875 if (IsCopyFromSGPR(*TRI, Addr)) {
1876 SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1877 SOffset = Addr;
1878 Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1879 return true;
1880 }
1881
1882 ConstantSDNode *CAddr;
1883 if (Addr.getOpcode() == ISD::ADD) {
1884 // Add (CopyFromReg <sgpr>) <constant>
1885 CAddr = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
1886 if (!CAddr || !TII->isLegalMUBUFImmOffset(CAddr->getZExtValue()))
1887 return false;
1888 if (!IsCopyFromSGPR(*TRI, Addr.getOperand(0)))
1889 return false;
1890
1891 SOffset = Addr.getOperand(0);
1892 } else if ((CAddr = dyn_cast<ConstantSDNode>(Addr)) &&
1893 TII->isLegalMUBUFImmOffset(CAddr->getZExtValue())) {
1894 // <constant>
1895 SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1896 } else {
1897 return false;
1898 }
1899
1900 SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1901
1902 Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i32);
1903 return true;
1904}
1905
1906bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1907 SDValue &SOffset, SDValue &Offset
1908 ) const {
1909 SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1910 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1911
1912 if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64))
1913 return false;
1914
1915 if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1916 !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1917 !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1918 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1919 maskTrailingOnes<uint64_t>(32); // Size
1920 SDLoc DL(Addr);
1921
1922 const SITargetLowering& Lowering =
1923 *static_cast<const SITargetLowering*>(getTargetLowering());
1924
1925 SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1926 return true;
1927 }
1928 return false;
1929}
1930
1931bool AMDGPUDAGToDAGISel::SelectBUFSOffset(SDValue ByteOffsetNode,
1932 SDValue &SOffset) const {
1933 if (Subtarget->hasRestrictedSOffset() && isNullConstant(ByteOffsetNode)) {
1934 SOffset = CurDAG->getRegister(AMDGPU::SGPR_NULL, MVT::i32);
1935 return true;
1936 }
1937
1938 SOffset = ByteOffsetNode;
1939 return true;
1940}
1941
1942// Find a load or store from corresponding pattern root.
1943// Roots may be build_vector, bitconvert or their combinations.
1946 if (MemSDNode *MN = dyn_cast<MemSDNode>(N))
1947 return MN;
1949 for (SDValue V : N->op_values())
1950 if (MemSDNode *MN =
1952 return MN;
1953 llvm_unreachable("cannot find MemSDNode in the pattern!");
1954}
1955
1956bool AMDGPUDAGToDAGISel::SelectFlatOffsetImpl(
1957 SDNode *N, SDValue Addr, SDValue &VAddr, SDValue &Offset,
1958 AMDGPU::FlatAddrSpace FlatVariant) const {
1960 int64_t OffsetVal = 0;
1961
1962 unsigned AS = findMemSDNode(N)->getAddressSpace();
1963 bool Is32BitConstant =
1964 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && Addr.getValueType() == MVT::i32;
1965
1966 bool CanHaveFlatSegmentOffsetBug =
1967 Subtarget->hasFlatSegmentOffsetBug() &&
1968 FlatVariant == FlatAddrSpace::FLAT &&
1970
1971 if (Subtarget->hasFlatInstOffsets() && !CanHaveFlatSegmentOffsetBug) {
1972 SDValue N0, N1;
1973 if ((!Is32BitConstant || isNoUnsignedWrap(Addr)) &&
1974 isBaseWithConstantOffset64(Addr, N0, N1) &&
1975 (FlatVariant != FlatAddrSpace::FlatScratch ||
1976 isFlatScratchBaseLegal(Addr))) {
1977 auto *COffset = cast<ConstantSDNode>(N1);
1978 int64_t COffsetVal =
1979 Is32BitConstant ? COffset->getZExtValue() : COffset->getSExtValue();
1980
1981 // Adding the offset to the base address in a FLAT instruction must not
1982 // change the memory aperture in which the address falls. Therefore we can
1983 // only fold offsets from inbounds GEPs into FLAT instructions.
1984 // Nonwrapping 32-bit arithmetic also preserves the high bits.
1985 bool IsInBounds =
1986 Addr.getOpcode() == ISD::PTRADD && Addr->getFlags().hasInBounds();
1987 if (COffsetVal == 0 || FlatVariant != FlatAddrSpace::FLAT || IsInBounds ||
1988 Is32BitConstant) {
1989 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1990 if (TII->isLegalFLATOffset(COffsetVal, AS, FlatVariant)) {
1991 Addr = N0;
1992 OffsetVal = COffsetVal;
1993 } else {
1994 // If the offset doesn't fit, put the low bits into the offset field
1995 // and add the rest.
1996 //
1997 // For a FLAT instruction the hardware decides whether to access
1998 // global/scratch/shared memory based on the high bits of vaddr,
1999 // ignoring the offset field, so we have to ensure that when we add
2000 // remainder to vaddr it still points into the same underlying object.
2001 // The easiest way to do that is to make sure that we split the offset
2002 // into two pieces that are both >= 0 or both <= 0.
2003
2004 SDLoc DL(N);
2005 uint64_t RemainderOffset;
2006
2007 std::tie(OffsetVal, RemainderOffset) =
2008 TII->splitFlatOffset(COffsetVal, AS, FlatVariant);
2009
2010 SDValue AddOffsetLo =
2011 getMaterializedScalarImm32(Lo_32(RemainderOffset), DL);
2012 SDValue Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2013
2014 if (Addr.getValueType().getSizeInBits() == 32) {
2016 Opnds.push_back(N0);
2017 Opnds.push_back(AddOffsetLo);
2018 unsigned AddOp = AMDGPU::V_ADD_CO_U32_e32;
2019 if (Subtarget->hasAddNoCarryInsts()) {
2020 AddOp = AMDGPU::V_ADD_U32_e64;
2021 Opnds.push_back(Clamp);
2022 }
2023 Addr =
2024 SDValue(CurDAG->getMachineNode(AddOp, DL, MVT::i32, Opnds), 0);
2025 } else {
2026 // TODO: Should this try to use a scalar add pseudo if the base
2027 // address is uniform and saddr is usable?
2028 SDValue Sub0 =
2029 CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
2030 SDValue Sub1 =
2031 CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
2032
2033 SDNode *N0Lo = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2034 DL, MVT::i32, N0, Sub0);
2035 SDNode *N0Hi = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2036 DL, MVT::i32, N0, Sub1);
2037
2038 SDValue AddOffsetHi =
2039 getMaterializedScalarImm32(Hi_32(RemainderOffset), DL);
2040
2041 SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i1);
2042
2043 SDNode *Add =
2044 CurDAG->getMachineNode(AMDGPU::V_ADD_CO_U32_e64, DL, VTs,
2045 {AddOffsetLo, SDValue(N0Lo, 0), Clamp});
2046
2047 SDNode *Addc = CurDAG->getMachineNode(
2048 AMDGPU::V_ADDC_U32_e64, DL, VTs,
2049 {AddOffsetHi, SDValue(N0Hi, 0), SDValue(Add, 1), Clamp});
2050
2051 SDValue RegSequenceArgs[] = {
2052 CurDAG->getTargetConstant(AMDGPU::VReg_64RegClassID, DL,
2053 MVT::i32),
2054 SDValue(Add, 0), Sub0, SDValue(Addc, 0), Sub1};
2055
2056 Addr = SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2057 MVT::i64, RegSequenceArgs),
2058 0);
2059 }
2060 }
2061 }
2062 }
2063 }
2064
2065 VAddr = Is32BitConstant ? Expand32BitAddress(Addr) : Addr;
2066 Offset = CurDAG->getSignedTargetConstant(OffsetVal, SDLoc(), MVT::i32);
2067 return true;
2068}
2069
2070bool AMDGPUDAGToDAGISel::SelectFlatOffset(SDNode *N, SDValue Addr,
2071 SDValue &VAddr,
2072 SDValue &Offset) const {
2073 return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
2075}
2076
2077bool AMDGPUDAGToDAGISel::SelectGlobalOffset(SDNode *N, SDValue Addr,
2078 SDValue &VAddr,
2079 SDValue &Offset) const {
2080 return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
2082}
2083
2084bool AMDGPUDAGToDAGISel::SelectScratchOffset(SDNode *N, SDValue Addr,
2085 SDValue &VAddr,
2086 SDValue &Offset) const {
2087 return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
2089}
2090
2091// If this matches *_extend i32:x, return x
2092// Otherwise if the value is I32 returns x.
2094 const SelectionDAG *DAG) {
2095 if (Op.getValueType() == MVT::i32)
2096 return Op;
2097
2098 if (Op.getOpcode() != (IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND) &&
2099 Op.getOpcode() != ISD::ANY_EXTEND &&
2100 !(Op.getOpcode() == (IsSigned ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND) &&
2101 DAG->SignBitIsZero(Op.getOperand(0))))
2102 return SDValue();
2103
2104 SDValue ExtSrc = Op.getOperand(0);
2105 return (ExtSrc.getValueType() == MVT::i32) ? ExtSrc : SDValue();
2106}
2107
2108// Match (64-bit SGPR base) + (zext vgpr offset) + sext(imm offset)
2109// or (64-bit SGPR base) + (sext vgpr offset) + sext(imm offset)
2110bool AMDGPUDAGToDAGISel::SelectGlobalSAddr(SDNode *N, SDValue Addr,
2111 SDValue &SAddr, SDValue &VOffset,
2112 SDValue &Offset, bool &ScaleOffset,
2113 bool NeedIOffset) const {
2115 int64_t ImmOffset = 0;
2116 ScaleOffset = false;
2117
2118 bool Is32Bit = Addr.getValueType() == MVT::i32;
2119
2120 // Match the immediate offset first, which canonically is moved as low as
2121 // possible.
2122
2123 SDValue LHS, RHS;
2124 if ((!Is32Bit || isNoUnsignedWrap(Addr)) &&
2125 isBaseWithConstantOffset64(Addr, LHS, RHS)) {
2126 auto *COffset = cast<ConstantSDNode>(RHS);
2127 int64_t COffsetVal =
2128 Is32Bit ? COffset->getZExtValue() : COffset->getSExtValue();
2129 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2130
2131 if (NeedIOffset &&
2132 TII->isLegalFLATOffset(COffsetVal, AMDGPUAS::GLOBAL_ADDRESS,
2133 FlatAddrSpace::FlatGlobal)) {
2134 Addr = LHS;
2135 ImmOffset = COffsetVal;
2136 } else if (!LHS->isDivergent()) {
2137 if (COffsetVal != 0) {
2138 SDLoc SL(N);
2139 // saddr + large_offset -> saddr +
2140 // (voffset = large_offset & ~MaxOffset) +
2141 // (large_offset & MaxOffset);
2142 int64_t SplitImmOffset = 0, RemainderOffset = COffsetVal;
2143 if (NeedIOffset) {
2144 std::tie(SplitImmOffset, RemainderOffset) = TII->splitFlatOffset(
2145 COffsetVal, AMDGPUAS::GLOBAL_ADDRESS, FlatAddrSpace::FlatGlobal);
2146 }
2147
2148 if (Subtarget->hasSignedGVSOffset() ? isInt<32>(RemainderOffset)
2149 : isUInt<32>(RemainderOffset)) {
2150 SDNode *VMov = CurDAG->getMachineNode(
2151 AMDGPU::V_MOV_B32_e32, SL, MVT::i32,
2152 CurDAG->getTargetConstant(Lo_32(RemainderOffset), SDLoc(),
2153 MVT::i32));
2154 VOffset = SDValue(VMov, 0);
2155 SAddr = Expand32BitAddress(LHS);
2156 Offset = CurDAG->getSignedTargetConstant(SplitImmOffset, SDLoc(),
2157 MVT::i32);
2158 return true;
2159 }
2160 }
2161
2162 // We are adding a 64 bit SGPR and a constant. If constant bus limit
2163 // is 1 we would need to perform 1 or 2 extra moves for each half of
2164 // the constant and it is better to do a scalar add and then issue a
2165 // single VALU instruction to materialize zero. Otherwise it is less
2166 // instructions to perform VALU adds with immediates or inline literals.
2167 // A 32-bit scalar add needs no high-half arithmetic.
2168 unsigned NumLiterals =
2169 !TII->isInlineConstant(APInt(32, Lo_32(COffsetVal))) +
2170 !TII->isInlineConstant(APInt(32, Hi_32(COffsetVal)));
2171 if (!Is32Bit &&
2172 Subtarget->getConstantBusLimit(AMDGPU::V_ADD_U32_e64) > NumLiterals)
2173 return false;
2174 }
2175 }
2176
2177 Addr = Expand32BitAddress(Addr);
2178
2179 // Match the variable offset.
2180 if (Addr->isAnyAdd()) {
2181 LHS = Addr.getOperand(0);
2182
2183 if (!LHS->isDivergent()) {
2184 // add (i64 sgpr), (*_extend (i32 vgpr))
2185 RHS = Addr.getOperand(1);
2186 ScaleOffset = SelectScaleOffset(N, RHS, Subtarget->hasSignedGVSOffset());
2187 if (SDValue ExtRHS = matchExtFromI32orI32(
2188 RHS, Subtarget->hasSignedGVSOffset(), CurDAG)) {
2189 SAddr = LHS;
2190 VOffset = ExtRHS;
2191 }
2192 }
2193
2194 RHS = Addr.getOperand(1);
2195 if (!SAddr && !RHS->isDivergent()) {
2196 // add (*_extend (i32 vgpr)), (i64 sgpr)
2197 ScaleOffset = SelectScaleOffset(N, LHS, Subtarget->hasSignedGVSOffset());
2198 if (SDValue ExtLHS = matchExtFromI32orI32(
2199 LHS, Subtarget->hasSignedGVSOffset(), CurDAG)) {
2200 SAddr = RHS;
2201 VOffset = ExtLHS;
2202 }
2203 }
2204
2205 if (SAddr) {
2206 Offset = CurDAG->getSignedTargetConstant(ImmOffset, SDLoc(), MVT::i32);
2207 return true;
2208 }
2209 }
2210
2211 if (Subtarget->hasScaleOffset() &&
2212 (Addr.getOpcode() == (Subtarget->hasSignedGVSOffset()
2215 (Addr.getOpcode() == AMDGPUISD::MAD_U64_U32 &&
2216 CurDAG->SignBitIsZero(Addr.getOperand(0)))) &&
2217 Addr.getOperand(0)->isDivergent() &&
2219 !Addr.getOperand(2)->isDivergent()) {
2220 // mad_u64_u32 (i32 vgpr), (i32 c), (i64 sgpr)
2221 unsigned Size =
2222 (unsigned)cast<MemSDNode>(N)->getMemoryVT().getFixedSizeInBits() / 8;
2223 ScaleOffset = Addr.getConstantOperandVal(1) == Size;
2224 if (ScaleOffset) {
2225 SAddr = Addr.getOperand(2);
2226 VOffset = Addr.getOperand(0);
2227 Offset = CurDAG->getTargetConstant(ImmOffset, SDLoc(), MVT::i32);
2228 return true;
2229 }
2230 }
2231
2232 if (Addr->isDivergent() || Addr.isUndef() || isa<ConstantSDNode>(Addr))
2233 return false;
2234
2235 // It's cheaper to materialize a single 32-bit zero for vaddr than the two
2236 // moves required to copy a 64-bit SGPR to VGPR.
2237 SAddr = Addr;
2238 SDNode *VMov =
2239 CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(Addr), MVT::i32,
2240 CurDAG->getTargetConstant(0, SDLoc(), MVT::i32));
2241 VOffset = SDValue(VMov, 0);
2242 Offset = CurDAG->getSignedTargetConstant(ImmOffset, SDLoc(), MVT::i32);
2243 return true;
2244}
2245
2246bool AMDGPUDAGToDAGISel::SelectGlobalSAddr(SDNode *N, SDValue Addr,
2247 SDValue &SAddr, SDValue &VOffset,
2248 SDValue &Offset,
2249 SDValue &CPol) const {
2250 bool ScaleOffset;
2251 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2252 return false;
2253
2254 CPol = CurDAG->getTargetConstant(ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2255 SDLoc(), MVT::i32);
2256 return true;
2257}
2258
2259bool AMDGPUDAGToDAGISel::SelectGlobalSAddrCPol(SDNode *N, SDValue Addr,
2260 SDValue &SAddr, SDValue &VOffset,
2261 SDValue &Offset,
2262 SDValue &CPol) const {
2263 bool ScaleOffset;
2264 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2265 return false;
2266
2267 // We are assuming CPol is always the last operand of the intrinsic.
2268 auto PassedCPol =
2269 N->getConstantOperandVal(N->getNumOperands() - 1) & ~AMDGPU::CPol::SCAL;
2270 CPol = CurDAG->getTargetConstant(
2271 (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, SDLoc(), MVT::i32);
2272 return true;
2273}
2274
2275bool AMDGPUDAGToDAGISel::SelectGlobalSAddrCPolM0(SDNode *N, SDValue Addr,
2276 SDValue &SAddr,
2277 SDValue &VOffset,
2278 SDValue &Offset,
2279 SDValue &CPol) const {
2280 bool ScaleOffset;
2281 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2282 return false;
2283
2284 // We are assuming CPol is second from last operand of the intrinsic.
2285 auto PassedCPol =
2286 N->getConstantOperandVal(N->getNumOperands() - 2) & ~AMDGPU::CPol::SCAL;
2287 CPol = CurDAG->getTargetConstant(
2288 (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, SDLoc(), MVT::i32);
2289 return true;
2290}
2291
2292bool AMDGPUDAGToDAGISel::SelectGlobalSAddrGLC(SDNode *N, SDValue Addr,
2293 SDValue &SAddr, SDValue &VOffset,
2294 SDValue &Offset,
2295 SDValue &CPol) const {
2296 bool ScaleOffset;
2297 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2298 return false;
2299
2300 unsigned CPolVal = (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | AMDGPU::CPol::GLC;
2301 CPol = CurDAG->getTargetConstant(CPolVal, SDLoc(), MVT::i32);
2302 return true;
2303}
2304
2305bool AMDGPUDAGToDAGISel::SelectGlobalSAddrNoIOffset(SDNode *N, SDValue Addr,
2306 SDValue &SAddr,
2307 SDValue &VOffset,
2308 SDValue &CPol) const {
2309 bool ScaleOffset;
2310 SDValue DummyOffset;
2311 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, DummyOffset, ScaleOffset,
2312 false))
2313 return false;
2314
2315 // We are assuming CPol is always the last operand of the intrinsic.
2316 auto PassedCPol =
2317 N->getConstantOperandVal(N->getNumOperands() - 1) & ~AMDGPU::CPol::SCAL;
2318 CPol = CurDAG->getTargetConstant(
2319 (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, SDLoc(), MVT::i32);
2320 return true;
2321}
2322
2323bool AMDGPUDAGToDAGISel::SelectGlobalSAddrNoIOffsetM0(SDNode *N, SDValue Addr,
2324 SDValue &SAddr,
2325 SDValue &VOffset,
2326 SDValue &CPol) const {
2327 bool ScaleOffset;
2328 SDValue DummyOffset;
2329 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, DummyOffset, ScaleOffset,
2330 false))
2331 return false;
2332
2333 // We are assuming CPol is second from last operand of the intrinsic.
2334 auto PassedCPol =
2335 N->getConstantOperandVal(N->getNumOperands() - 2) & ~AMDGPU::CPol::SCAL;
2336 CPol = CurDAG->getTargetConstant(
2337 (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, SDLoc(), MVT::i32);
2338 return true;
2339}
2340
2342 if (auto *FI = dyn_cast<FrameIndexSDNode>(SAddr)) {
2343 SAddr = CurDAG->getTargetFrameIndex(FI->getIndex(), FI->getValueType(0));
2344 } else if (SAddr.getOpcode() == ISD::ADD &&
2346 // Materialize this into a scalar move for scalar address to avoid
2347 // readfirstlane.
2348 auto *FI = cast<FrameIndexSDNode>(SAddr.getOperand(0));
2349 SDValue TFI = CurDAG->getTargetFrameIndex(FI->getIndex(),
2350 FI->getValueType(0));
2351 SAddr = SDValue(CurDAG->getMachineNode(AMDGPU::S_ADD_I32, SDLoc(SAddr),
2352 MVT::i32, TFI, SAddr.getOperand(1)),
2353 0);
2354 }
2355
2356 return SAddr;
2357}
2358
2359// Match (32-bit SGPR base) + sext(imm offset)
2360bool AMDGPUDAGToDAGISel::SelectScratchSAddr(SDNode *Parent, SDValue Addr,
2361 SDValue &SAddr,
2362 SDValue &Offset) const {
2364 if (Addr->isDivergent())
2365 return false;
2366
2367 SDLoc DL(Addr);
2368
2369 int64_t COffsetVal = 0;
2370
2371 if (CurDAG->isBaseWithConstantOffset(Addr) && isFlatScratchBaseLegal(Addr)) {
2372 COffsetVal = cast<ConstantSDNode>(Addr.getOperand(1))->getSExtValue();
2373 SAddr = Addr.getOperand(0);
2374 } else {
2375 SAddr = Addr;
2376 }
2377
2378 SAddr = SelectSAddrFI(CurDAG, SAddr);
2379
2380 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2381
2382 if (!TII->isLegalFLATOffset(COffsetVal, AMDGPUAS::PRIVATE_ADDRESS,
2383 FlatAddrSpace::FlatScratch)) {
2384 int64_t SplitImmOffset, RemainderOffset;
2385 std::tie(SplitImmOffset, RemainderOffset) = TII->splitFlatOffset(
2386 COffsetVal, AMDGPUAS::PRIVATE_ADDRESS, FlatAddrSpace::FlatScratch);
2387
2388 COffsetVal = SplitImmOffset;
2389
2390 SDValue AddOffset =
2392 ? getMaterializedScalarImm32(Lo_32(RemainderOffset), DL)
2393 : CurDAG->getSignedTargetConstant(RemainderOffset, DL, MVT::i32);
2394 SAddr = SDValue(CurDAG->getMachineNode(AMDGPU::S_ADD_I32, DL, MVT::i32,
2395 SAddr, AddOffset),
2396 0);
2397 }
2398
2399 Offset = CurDAG->getSignedTargetConstant(COffsetVal, DL, MVT::i32);
2400
2401 return true;
2402}
2403
2404// Check whether the flat scratch SVS swizzle bug affects this access.
2405bool AMDGPUDAGToDAGISel::checkFlatScratchSVSSwizzleBug(
2406 SDValue VAddr, SDValue SAddr, uint64_t ImmOffset) const {
2407 if (!Subtarget->hasFlatScratchSVSSwizzleBug())
2408 return false;
2409
2410 // The bug affects the swizzling of SVS accesses if there is any carry out
2411 // from the two low order bits (i.e. from bit 1 into bit 2) when adding
2412 // voffset to (soffset + inst_offset).
2413 KnownBits VKnown = CurDAG->computeKnownBits(VAddr);
2414 KnownBits SKnown =
2415 KnownBits::add(CurDAG->computeKnownBits(SAddr),
2416 KnownBits::makeConstant(APInt(32, ImmOffset,
2417 /*isSigned=*/true)));
2418 uint64_t VMax = VKnown.getMaxValue().getZExtValue();
2420 return (VMax & 3) + (SMax & 3) >= 4;
2421}
2422
2423bool AMDGPUDAGToDAGISel::SelectScratchSVAddr(SDNode *N, SDValue Addr,
2424 SDValue &VAddr, SDValue &SAddr,
2425 SDValue &Offset,
2426 SDValue &CPol) const {
2427 int64_t ImmOffset = 0;
2428
2429 SDValue LHS, RHS;
2430 SDValue OrigAddr = Addr;
2431 if (isBaseWithConstantOffset64(Addr, LHS, RHS)) {
2432 int64_t COffsetVal = cast<ConstantSDNode>(RHS)->getSExtValue();
2433 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2434
2435 if (TII->isLegalFLATOffset(COffsetVal, AMDGPUAS::PRIVATE_ADDRESS,
2437 Addr = LHS;
2438 ImmOffset = COffsetVal;
2439 } else if (!LHS->isDivergent() && COffsetVal > 0) {
2440 SDLoc SL(N);
2441 // saddr + large_offset -> saddr + (vaddr = large_offset & ~MaxOffset) +
2442 // (large_offset & MaxOffset);
2443 int64_t SplitImmOffset, RemainderOffset;
2444 std::tie(SplitImmOffset, RemainderOffset) =
2445 TII->splitFlatOffset(COffsetVal, AMDGPUAS::PRIVATE_ADDRESS,
2447
2448 if (isUInt<32>(RemainderOffset)) {
2449 SDNode *VMov = CurDAG->getMachineNode(
2450 AMDGPU::V_MOV_B32_e32, SL, MVT::i32,
2451 CurDAG->getTargetConstant(RemainderOffset, SDLoc(), MVT::i32));
2452 VAddr = SDValue(VMov, 0);
2453 SAddr = LHS;
2454 if (!isFlatScratchBaseLegal(Addr))
2455 return false;
2456 if (checkFlatScratchSVSSwizzleBug(VAddr, SAddr, SplitImmOffset))
2457 return false;
2458 Offset = CurDAG->getTargetConstant(SplitImmOffset, SDLoc(), MVT::i32);
2459 CPol = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
2460 return true;
2461 }
2462 }
2463 }
2464
2465 if (Addr.getOpcode() != ISD::ADD)
2466 return false;
2467
2468 LHS = Addr.getOperand(0);
2469 RHS = Addr.getOperand(1);
2470
2471 if (!LHS->isDivergent() && RHS->isDivergent()) {
2472 SAddr = LHS;
2473 VAddr = RHS;
2474 } else if (!RHS->isDivergent() && LHS->isDivergent()) {
2475 SAddr = RHS;
2476 VAddr = LHS;
2477 } else {
2478 return false;
2479 }
2480
2481 if (OrigAddr != Addr) {
2482 if (!isFlatScratchBaseLegalSVImm(OrigAddr))
2483 return false;
2484 } else {
2485 if (!isFlatScratchBaseLegalSV(OrigAddr))
2486 return false;
2487 }
2488
2489 if (checkFlatScratchSVSSwizzleBug(VAddr, SAddr, ImmOffset))
2490 return false;
2491 SAddr = SelectSAddrFI(CurDAG, SAddr);
2492 Offset = CurDAG->getSignedTargetConstant(ImmOffset, SDLoc(), MVT::i32);
2493
2494 bool ScaleOffset = SelectScaleOffset(N, VAddr, true /* IsSigned */);
2495 CPol = CurDAG->getTargetConstant(ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2496 SDLoc(), MVT::i32);
2497 return true;
2498}
2499
2500// For unbuffered smem loads, it is illegal for the Immediate Offset to be
2501// negative if the resulting (Offset + (M0 or SOffset or zero) is negative.
2502// Handle the case where the Immediate Offset + SOffset is negative.
2503bool AMDGPUDAGToDAGISel::isSOffsetLegalWithImmOffset(SDValue *SOffset,
2504 bool Imm32Only,
2505 bool IsBuffer,
2506 int64_t ImmOffset) const {
2507 if (!IsBuffer && !Imm32Only && ImmOffset < 0 &&
2508 AMDGPU::hasSMRDSignedImmOffset(*Subtarget)) {
2509 KnownBits SKnown = CurDAG->computeKnownBits(*SOffset);
2510 if (ImmOffset + SKnown.getMinValue().getSExtValue() < 0)
2511 return false;
2512 }
2513
2514 return true;
2515}
2516
2517// Given \p Offset and load node \p N check if an \p Offset is a multiple of
2518// the load byte size. If it is update \p Offset to a pre-scaled value and
2519// return true.
2520bool AMDGPUDAGToDAGISel::SelectScaleOffset(SDNode *N, SDValue &Offset,
2521 bool IsSigned, bool IsSMEM) const {
2522 bool ScaleOffset = false;
2523 if (!Subtarget->hasScaleOffset() || !Offset)
2524 return false;
2525
2526 unsigned Size =
2527 (unsigned)cast<MemSDNode>(N)->getMemoryVT().getFixedSizeInBits() / 8;
2528
2529 SDValue Off = Offset;
2530 if (SDValue Ext = matchExtFromI32orI32(Offset, IsSigned, CurDAG))
2531 Off = Ext;
2532
2533 if (isPowerOf2_32(Size) && Off.getOpcode() == ISD::SHL) {
2534 if (auto *C = dyn_cast<ConstantSDNode>(Off.getOperand(1)))
2535 ScaleOffset = C->getZExtValue() == Log2_32(Size);
2536 } else if (Offset.getOpcode() == ISD::MUL ||
2537 (IsSigned && Offset.getOpcode() == AMDGPUISD::MUL_I24) ||
2538 Offset.getOpcode() == AMDGPUISD::MUL_U24 ||
2539 (Offset.isMachineOpcode() &&
2540 Offset.getMachineOpcode() ==
2541 (IsSigned ? AMDGPU::S_MUL_I64_I32_PSEUDO
2542 : AMDGPU::S_MUL_U64_U32_PSEUDO))) {
2543 if (auto *C = dyn_cast<ConstantSDNode>(Offset.getOperand(1)))
2544 ScaleOffset = C->getZExtValue() == Size;
2545 }
2546
2547 if (!ScaleOffset)
2548 return false;
2549
2550 // SMEM scales the offset in 32 bits, other instructions in 64 bits.
2551 unsigned Bits = Log2_32_Ceil(Size);
2552 if (IsSMEM) {
2553 if (Off.getValueType() == MVT::i64) {
2554 KnownBits Known = CurDAG->computeKnownBits(Off.getOperand(0));
2555 if (Known.countMaxActiveBits() + Bits > 32)
2556 return false;
2557 }
2558 } else if (Off != Offset) {
2559 SDNodeFlags Flags = Off->getFlags();
2560 SDValue Idx = Off.getOperand(0);
2561 if (IsSigned && !Flags.hasNoSignedWrap() &&
2562 CurDAG->ComputeNumSignBits(Idx) <= Bits)
2563 return false;
2564 if (!IsSigned && !Flags.hasNoUnsignedWrap() &&
2565 CurDAG->computeKnownBits(Idx).countMinLeadingZeros() < Bits)
2566 return false;
2567 }
2568
2569 Offset = Off.getOperand(0);
2570 return true;
2571}
2572
2573// Match an immediate (if Offset is not null) or an SGPR (if SOffset is
2574// not null) offset. If Imm32Only is true, match only 32-bit immediate
2575// offsets available on CI.
2576bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDNode *N, SDValue ByteOffsetNode,
2577 SDValue *SOffset, SDValue *Offset,
2578 bool Imm32Only, bool IsBuffer,
2579 bool HasSOffset, int64_t ImmOffset,
2580 bool *ScaleOffset) const {
2581 assert((!SOffset || !Offset) &&
2582 "Cannot match both soffset and offset at the same time!");
2583
2584 if (ScaleOffset) {
2585 assert(N && SOffset);
2586
2587 *ScaleOffset = SelectScaleOffset(N, ByteOffsetNode, false /* IsSigned */,
2588 true /* IsSMEM */);
2589 }
2590
2591 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ByteOffsetNode);
2592 if (!C) {
2593 if (!SOffset)
2594 return false;
2595
2596 if (ByteOffsetNode.getValueType().isScalarInteger() &&
2597 ByteOffsetNode.getValueType().getSizeInBits() == 32) {
2598 *SOffset = ByteOffsetNode;
2599 return isSOffsetLegalWithImmOffset(SOffset, Imm32Only, IsBuffer,
2600 ImmOffset);
2601 }
2602 if (ByteOffsetNode.getOpcode() == ISD::ZERO_EXTEND) {
2603 if (ByteOffsetNode.getOperand(0).getValueType().getSizeInBits() == 32) {
2604 *SOffset = ByteOffsetNode.getOperand(0);
2605 return isSOffsetLegalWithImmOffset(SOffset, Imm32Only, IsBuffer,
2606 ImmOffset);
2607 }
2608 }
2609 return false;
2610 }
2611
2612 SDLoc SL(ByteOffsetNode);
2613
2614 // GFX9 and GFX10 have signed byte immediate offsets. The immediate
2615 // offset for S_BUFFER instructions is unsigned.
2616 int64_t ByteOffset = IsBuffer ? C->getZExtValue() : C->getSExtValue();
2617 std::optional<int64_t> EncodedOffset = AMDGPU::getSMRDEncodedOffset(
2618 *Subtarget, ByteOffset, IsBuffer, HasSOffset);
2619 if (EncodedOffset && Offset && !Imm32Only) {
2620 *Offset = CurDAG->getSignedTargetConstant(*EncodedOffset, SL, MVT::i32);
2621 return true;
2622 }
2623
2624 // SGPR and literal offsets are unsigned.
2625 if (ByteOffset < 0)
2626 return false;
2627
2628 EncodedOffset = AMDGPU::getSMRDEncodedLiteralOffset32(*Subtarget, ByteOffset);
2629 if (EncodedOffset && Offset && Imm32Only) {
2630 *Offset = CurDAG->getTargetConstant(*EncodedOffset, SL, MVT::i32);
2631 return true;
2632 }
2633
2634 if (!isUInt<32>(ByteOffset) && !isInt<32>(ByteOffset))
2635 return false;
2636
2637 if (SOffset) {
2638 SDValue C32Bit = CurDAG->getTargetConstant(ByteOffset, SL, MVT::i32);
2639 *SOffset = SDValue(
2640 CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32, C32Bit), 0);
2641 return true;
2642 }
2643
2644 return false;
2645}
2646
2647SDValue AMDGPUDAGToDAGISel::Expand32BitAddress(SDValue Addr) const {
2648 if (Addr.getValueType() != MVT::i32)
2649 return Addr;
2650
2651 // Zero-extend a 32-bit address.
2652 SDLoc SL(Addr);
2653
2654 const MachineFunction &MF = CurDAG->getMachineFunction();
2655 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2656 unsigned AddrHiVal = Info->get32BitAddressHighBits();
2657 SDValue AddrHi = CurDAG->getTargetConstant(AddrHiVal, SL, MVT::i32);
2658
2659 const SDValue Ops[] = {
2660 CurDAG->getTargetConstant(AMDGPU::SReg_64_XEXECRegClassID, SL, MVT::i32),
2661 Addr,
2662 CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32),
2663 SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32, AddrHi),
2664 0),
2665 CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32),
2666 };
2667
2668 return SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, SL, MVT::i64,
2669 Ops), 0);
2670}
2671
2672// Match a base and an immediate (if Offset is not null) or an SGPR (if
2673// SOffset is not null) or an immediate+SGPR offset. If Imm32Only is
2674// true, match only 32-bit immediate offsets available on CI.
2675bool AMDGPUDAGToDAGISel::SelectSMRDBaseOffset(SDNode *N, SDValue Addr,
2676 SDValue &SBase, SDValue *SOffset,
2677 SDValue *Offset, bool Imm32Only,
2678 bool IsBuffer, bool HasSOffset,
2679 int64_t ImmOffset,
2680 bool *ScaleOffset) const {
2681 if (SOffset && Offset) {
2682 assert(!Imm32Only && !IsBuffer);
2683 SDValue B;
2684
2685 if (!SelectSMRDBaseOffset(N, Addr, B, nullptr, Offset, false, false, true))
2686 return false;
2687
2688 int64_t ImmOff = 0;
2689 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(*Offset))
2690 ImmOff = C->getSExtValue();
2691
2692 return SelectSMRDBaseOffset(N, B, SBase, SOffset, nullptr, false, false,
2693 true, ImmOff, ScaleOffset);
2694 }
2695
2696 // A 32-bit (address + offset) should not cause unsigned 32-bit integer
2697 // wraparound, because s_load instructions perform the addition in 64 bits.
2698 if (Addr.getValueType() == MVT::i32 && Addr.getOpcode() == ISD::ADD &&
2699 !Addr->getFlags().hasNoUnsignedWrap())
2700 return false;
2701
2702 SDValue N0, N1;
2703 // Extract the base and offset if possible.
2704 if (Addr->isAnyAdd() || CurDAG->isADDLike(Addr)) {
2705 N0 = Addr.getOperand(0);
2706 N1 = Addr.getOperand(1);
2707 } else if (getBaseWithOffsetUsingSplitOR(*CurDAG, Addr, N0, N1)) {
2708 assert(N0 && N1 && isa<ConstantSDNode>(N1));
2709 }
2710 if (!N0 || !N1)
2711 return false;
2712
2713 if (SelectSMRDOffset(N, N1, SOffset, Offset, Imm32Only, IsBuffer, HasSOffset,
2714 ImmOffset, ScaleOffset)) {
2715 SBase = N0;
2716 return true;
2717 }
2718 if (SelectSMRDOffset(N, N0, SOffset, Offset, Imm32Only, IsBuffer, HasSOffset,
2719 ImmOffset, ScaleOffset)) {
2720 SBase = N1;
2721 return true;
2722 }
2723 return false;
2724}
2725
2726bool AMDGPUDAGToDAGISel::SelectSMRD(SDNode *N, SDValue Addr, SDValue &SBase,
2727 SDValue *SOffset, SDValue *Offset,
2728 bool Imm32Only, bool *ScaleOffset) const {
2729 if (SelectSMRDBaseOffset(N, Addr, SBase, SOffset, Offset, Imm32Only,
2730 /* IsBuffer */ false, /* HasSOffset */ false,
2731 /* ImmOffset */ 0, ScaleOffset)) {
2732 SBase = Expand32BitAddress(SBase);
2733 return true;
2734 }
2735
2736 if (Addr.getValueType() == MVT::i32 && Offset && !SOffset) {
2737 SBase = Expand32BitAddress(Addr);
2738 *Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
2739 return true;
2740 }
2741
2742 return false;
2743}
2744
2745bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
2746 SDValue &Offset) const {
2747 return SelectSMRD(/* N */ nullptr, Addr, SBase, /* SOffset */ nullptr,
2748 &Offset);
2749}
2750
2751bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
2752 SDValue &Offset) const {
2753 assert(Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
2754 return SelectSMRD(/* N */ nullptr, Addr, SBase, /* SOffset */ nullptr,
2755 &Offset, /* Imm32Only */ true);
2756}
2757
2758bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDNode *N, SDValue Addr, SDValue &SBase,
2759 SDValue &SOffset, SDValue &CPol) const {
2760 bool ScaleOffset;
2761 if (!SelectSMRD(N, Addr, SBase, &SOffset, /* Offset */ nullptr,
2762 /* Imm32Only */ false, &ScaleOffset))
2763 return false;
2764
2765 CPol = CurDAG->getTargetConstant(ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2766 SDLoc(N), MVT::i32);
2767 return true;
2768}
2769
2770bool AMDGPUDAGToDAGISel::SelectSMRDSgprImm(SDNode *N, SDValue Addr,
2771 SDValue &SBase, SDValue &SOffset,
2772 SDValue &Offset,
2773 SDValue &CPol) const {
2774 bool ScaleOffset;
2775 if (!SelectSMRD(N, Addr, SBase, &SOffset, &Offset, false, &ScaleOffset))
2776 return false;
2777
2778 CPol = CurDAG->getTargetConstant(ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2779 SDLoc(N), MVT::i32);
2780 return true;
2781}
2782
2783bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue N, SDValue &Offset) const {
2784 return SelectSMRDOffset(/* N */ nullptr, N, /* SOffset */ nullptr, &Offset,
2785 /* Imm32Only */ false, /* IsBuffer */ true);
2786}
2787
2788bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue N,
2789 SDValue &Offset) const {
2790 assert(Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
2791 return SelectSMRDOffset(/* N */ nullptr, N, /* SOffset */ nullptr, &Offset,
2792 /* Imm32Only */ true, /* IsBuffer */ true);
2793}
2794
2795bool AMDGPUDAGToDAGISel::SelectSMRDBufferSgprImm(SDValue N, SDValue &SOffset,
2796 SDValue &Offset) const {
2797 // Match the (soffset + offset) pair as a 32-bit register base and
2798 // an immediate offset.
2799 return N.getValueType() == MVT::i32 &&
2800 SelectSMRDBaseOffset(/* N */ nullptr, N, /* SBase */ SOffset,
2801 /* SOffset*/ nullptr, &Offset,
2802 /* Imm32Only */ false, /* IsBuffer */ true);
2803}
2804
2805bool AMDGPUDAGToDAGISel::SelectMOVRELOffset(SDValue Index,
2806 SDValue &Base,
2807 SDValue &Offset) const {
2808 SDLoc DL(Index);
2809
2810 if (CurDAG->isBaseWithConstantOffset(Index)) {
2811 SDValue N0 = Index.getOperand(0);
2812 SDValue N1 = Index.getOperand(1);
2813 ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
2814
2815 // (add n0, c0)
2816 // Don't peel off the offset (c0) if doing so could possibly lead
2817 // the base (n0) to be negative.
2818 // (or n0, |c0|) can never change a sign given isBaseWithConstantOffset.
2819 if (C1->getSExtValue() <= 0 || CurDAG->SignBitIsZero(N0) ||
2820 (Index->getOpcode() == ISD::OR && C1->getSExtValue() >= 0)) {
2821 Base = N0;
2822 Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
2823 return true;
2824 }
2825 }
2826
2827 if (isa<ConstantSDNode>(Index))
2828 return false;
2829
2830 Base = Index;
2831 Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
2832 return true;
2833}
2834
2835SDNode *AMDGPUDAGToDAGISel::getBFE32(bool IsSigned, const SDLoc &DL,
2836 SDValue Val, uint32_t Offset,
2837 uint32_t Width) {
2838 if (Val->isDivergent()) {
2839 unsigned Opcode = IsSigned ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
2840 SDValue Off = CurDAG->getTargetConstant(Offset, DL, MVT::i32);
2841 SDValue W = CurDAG->getTargetConstant(Width, DL, MVT::i32);
2842
2843 return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, Off, W);
2844 }
2845 unsigned Opcode = IsSigned ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
2846 // Transformation function, pack the offset and width of a BFE into
2847 // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
2848 // source, bits [5:0] contain the offset and bits [22:16] the width.
2849 uint32_t PackedVal = Offset | (Width << 16);
2850 SDValue PackedConst = CurDAG->getTargetConstant(PackedVal, DL, MVT::i32);
2851
2852 return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, PackedConst);
2853}
2854
2855void AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
2856 // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
2857 // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
2858 // Predicate: 0 < b <= c < 32
2859
2860 const SDValue &Shl = N->getOperand(0);
2861 ConstantSDNode *B = dyn_cast<ConstantSDNode>(Shl->getOperand(1));
2862 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2863
2864 if (B && C) {
2865 uint32_t BVal = B->getZExtValue();
2866 uint32_t CVal = C->getZExtValue();
2867
2868 if (0 < BVal && BVal <= CVal && CVal < 32) {
2869 bool Signed = N->getOpcode() == ISD::SRA;
2870 ReplaceNode(N, getBFE32(Signed, SDLoc(N), Shl.getOperand(0), CVal - BVal,
2871 32 - CVal));
2872 return;
2873 }
2874 }
2875 SelectCode(N);
2876}
2877
2878void AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
2879 switch (N->getOpcode()) {
2880 case ISD::AND:
2881 if (N->getOperand(0).getOpcode() == ISD::SRL) {
2882 // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
2883 // Predicate: isMask(mask)
2884 const SDValue &Srl = N->getOperand(0);
2885 ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Srl.getOperand(1));
2886 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
2887
2888 if (Shift && Mask) {
2889 uint32_t ShiftVal = Shift->getZExtValue();
2890 uint32_t MaskVal = Mask->getZExtValue();
2891
2892 if (isMask_32(MaskVal)) {
2893 uint32_t WidthVal = llvm::popcount(MaskVal);
2894 ReplaceNode(N, getBFE32(false, SDLoc(N), Srl.getOperand(0), ShiftVal,
2895 WidthVal));
2896 return;
2897 }
2898 }
2899 }
2900 break;
2901 case ISD::SRL:
2902 if (N->getOperand(0).getOpcode() == ISD::AND) {
2903 // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
2904 // Predicate: isMask(mask >> b)
2905 const SDValue &And = N->getOperand(0);
2906 ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N->getOperand(1));
2907 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(And->getOperand(1));
2908
2909 if (Shift && Mask) {
2910 uint32_t ShiftVal = Shift->getZExtValue();
2911 uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
2912
2913 if (isMask_32(MaskVal)) {
2914 uint32_t WidthVal = llvm::popcount(MaskVal);
2915 ReplaceNode(N, getBFE32(false, SDLoc(N), And.getOperand(0), ShiftVal,
2916 WidthVal));
2917 return;
2918 }
2919 }
2920 } else if (N->getOperand(0).getOpcode() == ISD::SHL) {
2921 SelectS_BFEFromShifts(N);
2922 return;
2923 }
2924 break;
2925 case ISD::SRA:
2926 if (N->getOperand(0).getOpcode() == ISD::SHL) {
2927 SelectS_BFEFromShifts(N);
2928 return;
2929 }
2930 break;
2931
2933 // sext_inreg (srl x, 16), i8 -> bfe_i32 x, 16, 8
2934 SDValue Src = N->getOperand(0);
2935 if (Src.getOpcode() != ISD::SRL)
2936 break;
2937
2938 const ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
2939 if (!Amt)
2940 break;
2941
2942 unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
2943 ReplaceNode(N, getBFE32(true, SDLoc(N), Src.getOperand(0),
2944 Amt->getZExtValue(), Width));
2945 return;
2946 }
2947 }
2948
2949 SelectCode(N);
2950}
2951
2952bool AMDGPUDAGToDAGISel::isCBranchSCC(const SDNode *N) const {
2953 assert(N->getOpcode() == ISD::BRCOND);
2954 if (!N->hasOneUse())
2955 return false;
2956
2957 SDValue Cond = N->getOperand(1);
2958 if (Cond.getOpcode() == ISD::CopyToReg)
2959 Cond = Cond.getOperand(2);
2960
2961 if (!Cond.hasOneUse() ||
2962 (Cond.getOpcode() != ISD::SETCC && Cond.getOpcode() != ISD::TRUNCATE))
2963 return false;
2964
2965 MVT VT = Cond.getOperand(0).getSimpleValueType();
2966 if (Cond.getOpcode() == ISD::TRUNCATE)
2967 return VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64;
2968
2969 if (VT == MVT::i32)
2970 return true;
2971
2972 if (VT == MVT::i64) {
2973 ISD::CondCode CC = Cond.getOperandCondCode(2);
2974 return (CC == ISD::SETEQ || CC == ISD::SETNE) &&
2975 Subtarget->hasScalarCompareEq64();
2976 }
2977
2978 if ((VT == MVT::f16 || VT == MVT::f32) && Subtarget->hasSALUFloatInsts())
2979 return true;
2980
2981 return false;
2982}
2983
2984static SDValue combineBallotPattern(SDValue VCMP, bool &Negate) {
2985 assert(VCMP->getOpcode() == AMDGPUISD::SETCC);
2986 // Special case for amdgcn.ballot:
2987 // %Cond = i1 (and/or combination of i1 ISD::SETCCs)
2988 // %VCMP = i(WaveSize) AMDGPUISD::SETCC (ext %Cond), 0, setne/seteq
2989 // =>
2990 // Use i1 %Cond value instead of i(WaveSize) %VCMP.
2991 // This is possible because divergent ISD::SETCC is selected as V_CMP and
2992 // Cond becomes a i(WaveSize) full mask value.
2993 // Note that ballot doesn't use SETEQ condition but its easy to support it
2994 // here for completeness, so in this case Negate is set true on return.
2995 auto VCMP_CC = VCMP.getOperandCondCode(2);
2996 if ((VCMP_CC == ISD::SETEQ || VCMP_CC == ISD::SETNE) &&
2997 isNullConstant(VCMP.getOperand(1))) {
2998
2999 auto Cond = VCMP.getOperand(0);
3000 if (ISD::isExtOpcode(Cond->getOpcode())) // Skip extension.
3001 Cond = Cond.getOperand(0);
3002
3003 if (isBoolSGPR(Cond)) {
3004 Negate = VCMP_CC == ISD::SETEQ;
3005 return Cond;
3006 }
3007 }
3008 return SDValue();
3009}
3010
3011void AMDGPUDAGToDAGISel::SelectBRCOND(SDNode *N) {
3012 SDValue Cond = N->getOperand(1);
3013
3014 if (Cond.isUndef()) {
3015 CurDAG->SelectNodeTo(N, AMDGPU::SI_BR_UNDEF, MVT::Other,
3016 N->getOperand(2), N->getOperand(0));
3017 return;
3018 }
3019
3020 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3021
3022 bool UseSCCBr = isCBranchSCC(N) && isUniformBr(N);
3023 bool AndExec = !UseSCCBr;
3024 bool Negate = false;
3025
3026 if (Cond.getOpcode() == ISD::SETCC &&
3027 Cond->getOperand(0)->getOpcode() == AMDGPUISD::SETCC) {
3028 SDValue VCMP = Cond->getOperand(0);
3029 auto CC = Cond->getOperandCondCode(2);
3030 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3031 isNullConstant(Cond->getOperand(1)) &&
3032 // We may encounter ballot.i64 in wave32 mode on -O0.
3033 VCMP.getValueType().getSizeInBits() == Subtarget->getWavefrontSize()) {
3034 // %VCMP = i(WaveSize) AMDGPUISD::SETCC ...
3035 // %C = i1 ISD::SETCC %VCMP, 0, setne/seteq
3036 // BRCOND i1 %C, %BB
3037 // =>
3038 // %VCMP = i(WaveSize) AMDGPUISD::SETCC ...
3039 // VCC = COPY i(WaveSize) %VCMP
3040 // S_CBRANCH_VCCNZ/VCCZ %BB
3041 Negate = CC == ISD::SETEQ;
3042 bool NegatedBallot = false;
3043 if (auto BallotCond = combineBallotPattern(VCMP, NegatedBallot)) {
3044 Cond = BallotCond;
3045 UseSCCBr = !BallotCond->isDivergent();
3046 Negate = Negate ^ NegatedBallot;
3047 } else {
3048 // TODO: don't use SCC here assuming that AMDGPUISD::SETCC is always
3049 // selected as V_CMP, but this may change for uniform condition.
3050 Cond = VCMP;
3051 UseSCCBr = false;
3052 }
3053 }
3054 // Cond is either V_CMP resulted from AMDGPUISD::SETCC or a combination of
3055 // V_CMPs resulted from ballot or ballot has uniform condition and SCC is
3056 // used.
3057 AndExec = false;
3058 }
3059
3060 unsigned BrOp =
3061 UseSCCBr ? (Negate ? AMDGPU::S_CBRANCH_SCC0 : AMDGPU::S_CBRANCH_SCC1)
3062 : (Negate ? AMDGPU::S_CBRANCH_VCCZ : AMDGPU::S_CBRANCH_VCCNZ);
3063 Register CondReg = UseSCCBr ? AMDGPU::SCC : TRI->getVCC();
3064 SDLoc SL(N);
3065
3066 if (AndExec) {
3067 // This is the case that we are selecting to S_CBRANCH_VCCNZ. We have not
3068 // analyzed what generates the vcc value, so we do not know whether vcc
3069 // bits for disabled lanes are 0. Thus we need to mask out bits for
3070 // disabled lanes.
3071 //
3072 // For the case that we select S_CBRANCH_SCC1 and it gets
3073 // changed to S_CBRANCH_VCCNZ in SIFixSGPRCopies, SIFixSGPRCopies calls
3074 // SIInstrInfo::moveToVALU which inserts the S_AND).
3075 //
3076 // We could add an analysis of what generates the vcc value here and omit
3077 // the S_AND when is unnecessary. But it would be better to add a separate
3078 // pass after SIFixSGPRCopies to do the unnecessary S_AND removal, so it
3079 // catches both cases.
3080 Cond = SDValue(
3081 CurDAG->getMachineNode(
3082 Subtarget->isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64, SL,
3083 MVT::i1,
3084 CurDAG->getRegister(Subtarget->isWave32() ? AMDGPU::EXEC_LO
3085 : AMDGPU::EXEC,
3086 MVT::i1),
3087 Cond),
3088 0);
3089 }
3090
3091 SDValue VCC = CurDAG->getCopyToReg(N->getOperand(0), SL, CondReg, Cond);
3092 CurDAG->SelectNodeTo(N, BrOp, MVT::Other,
3093 N->getOperand(2), // Basic Block
3094 VCC.getValue(0));
3095}
3096
3097void AMDGPUDAGToDAGISel::SelectFP_EXTEND(SDNode *N) {
3098 if (Subtarget->hasSALUFloatInsts() && N->getValueType(0) == MVT::f32 &&
3099 !N->isDivergent()) {
3100 SDValue Src = N->getOperand(0);
3101 if (Src.getValueType() == MVT::f16) {
3102 if (isExtractHiElt(Src, Src)) {
3103 CurDAG->SelectNodeTo(N, AMDGPU::S_CVT_HI_F32_F16, N->getVTList(),
3104 {Src});
3105 return;
3106 }
3107 }
3108 }
3109
3110 SelectCode(N);
3111}
3112
3113void AMDGPUDAGToDAGISel::SelectDSAppendConsume(SDNode *N, unsigned IntrID) {
3114 // The address is assumed to be uniform, so if it ends up in a VGPR, it will
3115 // be copied to an SGPR with readfirstlane.
3116 unsigned Opc = IntrID == Intrinsic::amdgcn_ds_append ?
3117 AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
3118
3119 SDValue Chain = N->getOperand(0);
3120 SDValue Ptr = N->getOperand(2);
3121 MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
3122 MachineMemOperand *MMO = M->getMemOperand();
3123 bool IsGDS = M->getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
3124
3126 if (CurDAG->isBaseWithConstantOffset(Ptr)) {
3127 SDValue PtrBase = Ptr.getOperand(0);
3128 SDValue PtrOffset = Ptr.getOperand(1);
3129
3130 const APInt &OffsetVal = PtrOffset->getAsAPIntVal();
3131 if (isDSOffsetLegal(PtrBase, OffsetVal.getZExtValue())) {
3132 N = glueCopyToM0(N, PtrBase);
3133 Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i32);
3134 }
3135 }
3136
3137 if (!Offset) {
3138 N = glueCopyToM0(N, Ptr);
3139 Offset = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
3140 }
3141
3142 SDValue Ops[] = {
3143 Offset,
3144 CurDAG->getTargetConstant(IsGDS, SDLoc(), MVT::i32),
3145 Chain,
3146 N->getOperand(N->getNumOperands() - 1) // New glue
3147 };
3148
3149 SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
3150 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
3151}
3152
3153// We need to handle this here because tablegen doesn't support matching
3154// instructions with multiple outputs.
3155void AMDGPUDAGToDAGISel::SelectDSBvhStackIntrinsic(SDNode *N, unsigned IntrID) {
3156 unsigned Opc;
3157 switch (IntrID) {
3158 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
3159 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
3160 Opc = AMDGPU::DS_BVH_STACK_RTN_B32;
3161 break;
3162 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
3163 Opc = AMDGPU::DS_BVH_STACK_PUSH8_POP1_RTN_B32;
3164 break;
3165 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn:
3166 Opc = AMDGPU::DS_BVH_STACK_PUSH8_POP2_RTN_B64;
3167 break;
3168 }
3169 SDValue Ops[] = {N->getOperand(2), N->getOperand(3), N->getOperand(4),
3170 N->getOperand(5), N->getOperand(0)};
3171
3172 MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
3173 MachineMemOperand *MMO = M->getMemOperand();
3174 SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
3175 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
3176}
3177
3178void AMDGPUDAGToDAGISel::SelectTensorLoadStore(SDNode *N, unsigned IntrID) {
3179 bool IsLoad = IntrID == Intrinsic::amdgcn_tensor_load_to_lds;
3180 unsigned Opc =
3181 IsLoad ? AMDGPU::TENSOR_LOAD_TO_LDS_d4 : AMDGPU::TENSOR_STORE_FROM_LDS_d4;
3182
3183 SmallVector<SDValue, 7> TensorOps;
3184 // First two groups
3185 TensorOps.push_back(N->getOperand(2)); // D# group 0
3186 TensorOps.push_back(N->getOperand(3)); // D# group 1
3187
3188 // Use _D2 version if both group 2 and 3 are zero-initialized.
3189 SDValue Group2 = N->getOperand(4);
3190 SDValue Group3 = N->getOperand(5);
3191 if (ISD::isBuildVectorAllZeros(Group2) &&
3193 Opc = IsLoad ? AMDGPU::TENSOR_LOAD_TO_LDS_d2
3194 : AMDGPU::TENSOR_STORE_FROM_LDS_d2;
3195 } else { // Has at least 4 groups
3196 TensorOps.push_back(Group2); // D# group 2
3197 TensorOps.push_back(Group3); // D# group 3
3198 }
3199
3200 // TODO: Handle the fifth group: N->getOperand(6), which is silently ignored
3201 // for now because all existing targets only support up to 4 groups.
3202 TensorOps.push_back(CurDAG->getTargetConstant(0, SDLoc(N), MVT::i1)); // r128
3203 TensorOps.push_back(N->getOperand(7)); // cache policy
3204 TensorOps.push_back(N->getOperand(0)); // chain
3205
3206 (void)CurDAG->SelectNodeTo(N, Opc, MVT::Other, TensorOps);
3207}
3208
3209static unsigned gwsIntrinToOpcode(unsigned IntrID) {
3210 switch (IntrID) {
3211 case Intrinsic::amdgcn_ds_gws_init:
3212 return AMDGPU::DS_GWS_INIT;
3213 case Intrinsic::amdgcn_ds_gws_barrier:
3214 return AMDGPU::DS_GWS_BARRIER;
3215 case Intrinsic::amdgcn_ds_gws_sema_v:
3216 return AMDGPU::DS_GWS_SEMA_V;
3217 case Intrinsic::amdgcn_ds_gws_sema_br:
3218 return AMDGPU::DS_GWS_SEMA_BR;
3219 case Intrinsic::amdgcn_ds_gws_sema_p:
3220 return AMDGPU::DS_GWS_SEMA_P;
3221 case Intrinsic::amdgcn_ds_gws_sema_release_all:
3222 return AMDGPU::DS_GWS_SEMA_RELEASE_ALL;
3223 default:
3224 llvm_unreachable("not a gws intrinsic");
3225 }
3226}
3227
3228void AMDGPUDAGToDAGISel::SelectDS_GWS(SDNode *N, unsigned IntrID) {
3229 if (!Subtarget->hasGWS() ||
3230 (IntrID == Intrinsic::amdgcn_ds_gws_sema_release_all &&
3231 !Subtarget->hasGWSSemaReleaseAll())) {
3232 // Let this error.
3233 SelectCode(N);
3234 return;
3235 }
3236
3237 // Chain, intrinsic ID, vsrc, offset
3238 const bool HasVSrc = N->getNumOperands() == 4;
3239 assert(HasVSrc || N->getNumOperands() == 3);
3240
3241 SDLoc SL(N);
3242 SDValue BaseOffset = N->getOperand(HasVSrc ? 3 : 2);
3243 int ImmOffset = 0;
3244 MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
3245 MachineMemOperand *MMO = M->getMemOperand();
3246
3247 // Don't worry if the offset ends up in a VGPR. Only one lane will have
3248 // effect, so SIFixSGPRCopies will validly insert readfirstlane.
3249
3250 // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
3251 // offset field) % 64. Some versions of the programming guide omit the m0
3252 // part, or claim it's from offset 0.
3253 if (ConstantSDNode *ConstOffset = dyn_cast<ConstantSDNode>(BaseOffset)) {
3254 // If we have a constant offset, try to use the 0 in m0 as the base.
3255 // TODO: Look into changing the default m0 initialization value. If the
3256 // default -1 only set the low 16-bits, we could leave it as-is and add 1 to
3257 // the immediate offset.
3258 glueCopyToM0(N, CurDAG->getTargetConstant(0, SL, MVT::i32));
3259 ImmOffset = ConstOffset->getZExtValue();
3260 } else {
3261 if (CurDAG->isBaseWithConstantOffset(BaseOffset)) {
3262 ImmOffset = BaseOffset.getConstantOperandVal(1);
3263 BaseOffset = BaseOffset.getOperand(0);
3264 }
3265
3266 // Prefer to do the shift in an SGPR since it should be possible to use m0
3267 // as the result directly. If it's already an SGPR, it will be eliminated
3268 // later.
3269 SDNode *SGPROffset
3270 = CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL, MVT::i32,
3271 BaseOffset);
3272 // Shift to offset in m0
3273 SDNode *M0Base
3274 = CurDAG->getMachineNode(AMDGPU::S_LSHL_B32, SL, MVT::i32,
3275 SDValue(SGPROffset, 0),
3276 CurDAG->getTargetConstant(16, SL, MVT::i32));
3277 glueCopyToM0(N, SDValue(M0Base, 0));
3278 }
3279
3280 SDValue Chain = N->getOperand(0);
3281 SDValue OffsetField = CurDAG->getTargetConstant(ImmOffset, SL, MVT::i32);
3282
3283 const unsigned Opc = gwsIntrinToOpcode(IntrID);
3284
3285 const MCInstrDesc &InstrDesc = TII->get(Opc);
3286 int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
3287
3288 const TargetRegisterClass *DataRC = TII->getRegClass(InstrDesc, Data0Idx);
3289
3291 if (HasVSrc) {
3292 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3293
3294 SDValue Data = N->getOperand(2);
3295 MVT DataVT = Data.getValueType().getSimpleVT();
3296 if (TRI->isTypeLegalForClass(*DataRC, DataVT)) {
3297 // Normal 32-bit case.
3298 Ops.push_back(N->getOperand(2));
3299 } else {
3300 // Operand is really 32-bits, but requires 64-bit alignment, so use the
3301 // even aligned 64-bit register class.
3302 const SDValue RegSeqOps[] = {
3303 CurDAG->getTargetConstant(DataRC->getID(), SL, MVT::i32), Data,
3304 CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32),
3305 SDValue(
3306 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, SL, MVT::i32),
3307 0),
3308 CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32)};
3309
3310 Ops.push_back(SDValue(CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
3311 SL, MVT::v2i32, RegSeqOps),
3312 0));
3313 }
3314 }
3315
3316 Ops.push_back(OffsetField);
3317 Ops.push_back(Chain);
3318
3319 SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
3320 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
3321}
3322
3323void AMDGPUDAGToDAGISel::SelectInterpP1F16(SDNode *N) {
3324 if (Subtarget->getLDSBankCount() != 16) {
3325 // This is a single instruction with a pattern.
3326 SelectCode(N);
3327 return;
3328 }
3329
3330 SDLoc DL(N);
3331
3332 // This requires 2 instructions. It is possible to write a pattern to support
3333 // this, but the generated isel emitter doesn't correctly deal with multiple
3334 // output instructions using the same physical register input. The copy to m0
3335 // is incorrectly placed before the second instruction.
3336 //
3337 // TODO: Match source modifiers.
3338 //
3339 // def : Pat <
3340 // (int_amdgcn_interp_p1_f16
3341 // (VOP3Mods f32:$src0, i32:$src0_modifiers),
3342 // (i32 timm:$attrchan), (i32 timm:$attr),
3343 // (i1 timm:$high), M0),
3344 // (V_INTERP_P1LV_F16 $src0_modifiers, VGPR_32:$src0, timm:$attr,
3345 // timm:$attrchan, 0,
3346 // (V_INTERP_MOV_F32 2, timm:$attr, timm:$attrchan), timm:$high)> {
3347 // let Predicates = [has16BankLDS];
3348 // }
3349
3350 // 16 bank LDS
3351 SDValue ToM0 = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL, AMDGPU::M0,
3352 N->getOperand(5), SDValue());
3353
3354 SDVTList VTs = CurDAG->getVTList(MVT::f32, MVT::Other);
3355
3356 SDNode *InterpMov =
3357 CurDAG->getMachineNode(AMDGPU::V_INTERP_MOV_F32, DL, VTs, {
3358 CurDAG->getTargetConstant(2, DL, MVT::i32), // P0
3359 N->getOperand(3), // Attr
3360 N->getOperand(2), // Attrchan
3361 ToM0.getValue(1) // In glue
3362 });
3363
3364 SDNode *InterpP1LV =
3365 CurDAG->getMachineNode(AMDGPU::V_INTERP_P1LV_F16, DL, MVT::f32, {
3366 CurDAG->getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
3367 N->getOperand(1), // Src0
3368 N->getOperand(3), // Attr
3369 N->getOperand(2), // Attrchan
3370 CurDAG->getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
3371 SDValue(InterpMov, 0), // Src2 - holds two f16 values selected by high
3372 N->getOperand(4), // high
3373 CurDAG->getTargetConstant(0, DL, MVT::i1), // $clamp
3374 CurDAG->getTargetConstant(0, DL, MVT::i32), // $omod
3375 SDValue(InterpMov, 1)
3376 });
3377
3378 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), SDValue(InterpP1LV, 0));
3379}
3380
3381void AMDGPUDAGToDAGISel::SelectINTRINSIC_W_CHAIN(SDNode *N) {
3382 unsigned IntrID = N->getConstantOperandVal(1);
3383 switch (IntrID) {
3384 case Intrinsic::amdgcn_ds_append:
3385 case Intrinsic::amdgcn_ds_consume: {
3386 if (N->getValueType(0) != MVT::i32)
3387 break;
3388 SelectDSAppendConsume(N, IntrID);
3389 return;
3390 }
3391 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
3392 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
3393 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
3394 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn:
3395 SelectDSBvhStackIntrinsic(N, IntrID);
3396 return;
3397 case Intrinsic::amdgcn_init_whole_wave:
3398 CurDAG->getMachineFunction()
3399 .getInfo<SIMachineFunctionInfo>()
3400 ->setInitWholeWave();
3401 break;
3402 }
3403
3404 SelectCode(N);
3405}
3406
3407void AMDGPUDAGToDAGISel::SelectINTRINSIC_WO_CHAIN(SDNode *N) {
3408 unsigned IntrID = N->getConstantOperandVal(0);
3409 unsigned Opcode = AMDGPU::INSTRUCTION_LIST_END;
3410 SDNode *ConvGlueNode = N->getGluedNode();
3411 if (ConvGlueNode) {
3412 // FIXME: Possibly iterate over multiple glue nodes?
3413 assert(ConvGlueNode->getOpcode() == ISD::CONVERGENCECTRL_GLUE);
3414 ConvGlueNode = ConvGlueNode->getOperand(0).getNode();
3415 ConvGlueNode =
3416 CurDAG->getMachineNode(TargetOpcode::CONVERGENCECTRL_GLUE, {},
3417 MVT::Glue, SDValue(ConvGlueNode, 0));
3418 } else {
3419 ConvGlueNode = nullptr;
3420 }
3421 switch (IntrID) {
3422 case Intrinsic::amdgcn_wqm:
3423 Opcode = AMDGPU::WQM;
3424 break;
3425 case Intrinsic::amdgcn_softwqm:
3426 Opcode = AMDGPU::SOFT_WQM;
3427 break;
3428 case Intrinsic::amdgcn_wwm:
3429 case Intrinsic::amdgcn_strict_wwm:
3430 Opcode = AMDGPU::STRICT_WWM;
3431 break;
3432 case Intrinsic::amdgcn_strict_wqm:
3433 Opcode = AMDGPU::STRICT_WQM;
3434 break;
3435 case Intrinsic::amdgcn_interp_p1_f16:
3436 SelectInterpP1F16(N);
3437 return;
3438 case Intrinsic::amdgcn_permlane16_swap:
3439 case Intrinsic::amdgcn_permlane32_swap: {
3440 if ((IntrID == Intrinsic::amdgcn_permlane16_swap &&
3441 !Subtarget->hasPermlane16Swap()) ||
3442 (IntrID == Intrinsic::amdgcn_permlane32_swap &&
3443 !Subtarget->hasPermlane32Swap())) {
3444 SelectCode(N); // Hit the default error
3445 return;
3446 }
3447
3448 Opcode = IntrID == Intrinsic::amdgcn_permlane16_swap
3449 ? AMDGPU::V_PERMLANE16_SWAP_B32_e64
3450 : AMDGPU::V_PERMLANE32_SWAP_B32_e64;
3451
3452 SmallVector<SDValue, 4> NewOps(N->op_begin() + 1, N->op_end());
3453 if (ConvGlueNode)
3454 NewOps.push_back(SDValue(ConvGlueNode, 0));
3455
3456 bool FI = N->getConstantOperandVal(3);
3457 NewOps[2] = CurDAG->getTargetConstant(
3458 FI ? AMDGPU::DPP::DPP_FI_1 : AMDGPU::DPP::DPP_FI_0, SDLoc(), MVT::i32);
3459
3460 CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), NewOps);
3461 return;
3462 }
3463 default:
3464 SelectCode(N);
3465 break;
3466 }
3467
3468 if (Opcode != AMDGPU::INSTRUCTION_LIST_END) {
3469 SDValue Src = N->getOperand(1);
3470 CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), {Src});
3471 }
3472
3473 if (ConvGlueNode) {
3474 SmallVector<SDValue, 4> NewOps(N->ops());
3475 NewOps.push_back(SDValue(ConvGlueNode, 0));
3476 CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), NewOps);
3477 }
3478}
3479
3480void AMDGPUDAGToDAGISel::SelectINTRINSIC_VOID(SDNode *N) {
3481 unsigned IntrID = N->getConstantOperandVal(1);
3482 switch (IntrID) {
3483 case Intrinsic::amdgcn_ds_gws_init:
3484 case Intrinsic::amdgcn_ds_gws_barrier:
3485 case Intrinsic::amdgcn_ds_gws_sema_v:
3486 case Intrinsic::amdgcn_ds_gws_sema_br:
3487 case Intrinsic::amdgcn_ds_gws_sema_p:
3488 case Intrinsic::amdgcn_ds_gws_sema_release_all:
3489 SelectDS_GWS(N, IntrID);
3490 return;
3491 case Intrinsic::amdgcn_tensor_load_to_lds:
3492 case Intrinsic::amdgcn_tensor_store_from_lds:
3493 SelectTensorLoadStore(N, IntrID);
3494 return;
3495 default:
3496 break;
3497 }
3498
3499 SelectCode(N);
3500}
3501
3502void AMDGPUDAGToDAGISel::SelectWAVE_ADDRESS(SDNode *N) {
3503 SDValue Log2WaveSize =
3504 CurDAG->getTargetConstant(Subtarget->getWavefrontSizeLog2(), SDLoc(N), MVT::i32);
3505 CurDAG->SelectNodeTo(N, AMDGPU::S_LSHR_B32, N->getVTList(),
3506 {N->getOperand(0), Log2WaveSize});
3507}
3508
3509void AMDGPUDAGToDAGISel::SelectSTACKRESTORE(SDNode *N) {
3510 SDValue SrcVal = N->getOperand(1);
3511 if (SrcVal.getValueType() != MVT::i32) {
3512 SelectCode(N); // Emit default error
3513 return;
3514 }
3515
3516 SDValue CopyVal;
3517 Register SP = TLI->getStackPointerRegisterToSaveRestore();
3518 SDLoc SL(N);
3519
3520 if (SrcVal.getOpcode() == AMDGPUISD::WAVE_ADDRESS) {
3521 CopyVal = SrcVal.getOperand(0);
3522 } else {
3523 SDValue Log2WaveSize = CurDAG->getTargetConstant(
3524 Subtarget->getWavefrontSizeLog2(), SL, MVT::i32);
3525
3526 if (N->isDivergent()) {
3527 SrcVal = SDValue(CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL,
3528 MVT::i32, SrcVal),
3529 0);
3530 }
3531
3532 CopyVal = SDValue(CurDAG->getMachineNode(AMDGPU::S_LSHL_B32, SL, MVT::i32,
3533 {SrcVal, Log2WaveSize}),
3534 0);
3535 }
3536
3537 SDValue CopyToSP = CurDAG->getCopyToReg(N->getOperand(0), SL, SP, CopyVal);
3538 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyToSP);
3539}
3540
3541void AMDGPUDAGToDAGISel::SelectWRITE_REGISTER(SDNode *N) {
3542 const MDString *RegStr = cast<MDString>(
3543 cast<MDNodeSDNode>(N->getOperand(1))->getMD()->getOperand(0));
3544 SDValue SrcVal = N->getOperand(2);
3545 EVT VT = SrcVal.getValueType();
3546 Register Reg = TLI->getRegisterByName(RegStr->getString().data(),
3548 CurDAG->getMachineFunction());
3549 if (!Reg) {
3550 const Function &Fn = CurDAG->getMachineFunction().getFunction();
3551 Fn.getContext().diagnose(DiagnosticInfoGenericWithLoc(
3552 "invalid register \"" + Twine(RegStr->getString()) +
3553 "\" for llvm.write_register",
3554 Fn, N->getDebugLoc()));
3555 ReplaceUses(SDValue(N, 0), N->getOperand(0));
3556 CurDAG->RemoveDeadNode(N);
3557 return;
3558 }
3559
3560 // Speculatively insert a readfirstlane in case the source value ends up in a
3561 // VGPR, which hopefully will fold away if not.
3562 SDLoc SL(N);
3563 SDValue CopyVal;
3564 if (isa<ConstantSDNode>(SrcVal)) {
3565 CopyVal = SrcVal;
3566 } else if (VT == MVT::i32) {
3567 CopyVal = SDValue(CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL,
3568 MVT::i32, SrcVal),
3569 0);
3570 } else {
3571 assert(VT == MVT::i64);
3572 SDValue Lo =
3573 CurDAG->getTargetExtractSubreg(AMDGPU::sub0, SL, MVT::i32, SrcVal);
3574 SDValue Hi =
3575 CurDAG->getTargetExtractSubreg(AMDGPU::sub1, SL, MVT::i32, SrcVal);
3576 Lo = SDValue(
3577 CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL, MVT::i32, Lo),
3578 0);
3579 Hi = SDValue(
3580 CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL, MVT::i32, Hi),
3581 0);
3582 CopyVal = emitRegSequence(*CurDAG, AMDGPU::SReg_64RegClassID, VT, {Lo, Hi},
3583 {AMDGPU::sub0, AMDGPU::sub1}, SL);
3584 }
3585
3586 SDValue CopyToReg = CurDAG->getCopyToReg(N->getOperand(0), SL, Reg, CopyVal);
3587 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyToReg);
3588}
3589
3590bool AMDGPUDAGToDAGISel::SelectVOP3ModsImpl(SDValue In, SDValue &Src,
3591 unsigned &Mods,
3592 bool IsCanonicalizing,
3593 bool AllowAbs) const {
3594 Mods = SISrcMods::NONE;
3595 Src = In;
3596
3597 if (Src.getOpcode() == ISD::FNEG) {
3598 Mods |= SISrcMods::NEG;
3599 Src = Src.getOperand(0);
3600 } else if (Src.getOpcode() == ISD::FSUB && IsCanonicalizing) {
3601 // Fold fsub [+-]0 into fneg. This may not have folded depending on the
3602 // denormal mode, but we're implicitly canonicalizing in a source operand.
3603 auto *LHS = dyn_cast<ConstantFPSDNode>(Src.getOperand(0));
3604 if (LHS && LHS->isZero()) {
3605 Mods |= SISrcMods::NEG;
3606 Src = Src.getOperand(1);
3607 }
3608 }
3609
3610 if (AllowAbs && Src.getOpcode() == ISD::FABS) {
3611 Mods |= SISrcMods::ABS;
3612 Src = Src.getOperand(0);
3613 }
3614
3615 if (Mods != SISrcMods::NONE)
3616 return true;
3617
3618 // Convert various sign-bit masks on integers to src mods. Currently disabled
3619 // for 16-bit types as the codegen replaces the operand without adding a
3620 // srcmod. This is intentionally finding the cases where we are performing
3621 // float neg and abs on int types, the goal is not to obtain two's complement
3622 // neg or abs. Limit converison to select operands via the nonCanonalizing
3623 // pattern.
3624 // TODO: Add 16-bit support.
3625 if (IsCanonicalizing)
3626 return true;
3627
3628 // v2i32 xor/or/and are legal. A vselect using these instructions as operands
3629 // is scalarised into two selects with EXTRACT_VECTOR_ELT operands. Peek
3630 // through the extract to the bitwise op.
3631 SDValue PeekSrc =
3632 Src->getOpcode() == ISD::EXTRACT_VECTOR_ELT ? Src->getOperand(0) : Src;
3633 // Convert various sign-bit masks to src mods. Currently disabled for 16-bit
3634 // types as the codegen replaces the operand without adding a srcmod.
3635 // This is intentionally finding the cases where we are performing float neg
3636 // and abs on int types, the goal is not to obtain two's complement neg or
3637 // abs.
3638 // TODO: Add 16-bit support.
3639 unsigned Opc = PeekSrc.getOpcode();
3640 EVT VT = Src.getValueType();
3641 if ((Opc != ISD::AND && Opc != ISD::OR && Opc != ISD::XOR) ||
3642 (VT != MVT::i32 && VT != MVT::v2i32 && VT != MVT::i64))
3643 return true;
3644
3645 ConstantSDNode *CRHS = isConstOrConstSplat(PeekSrc->getOperand(1));
3646 if (!CRHS)
3647 return true;
3648
3649 auto ReplaceSrc = [&]() -> SDValue {
3650 if (Src->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
3651 return Src.getOperand(0);
3652
3653 SDValue LHS = PeekSrc->getOperand(0);
3654 SDValue Index = Src->getOperand(1);
3655 return CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Src),
3656 Src.getValueType(), LHS, Index);
3657 };
3658
3659 // Recognise Srcmods:
3660 // (xor a, 0x80000000) or v2i32 (xor a, {0x80000000,0x80000000}) as NEG.
3661 // (and a, 0x7fffffff) or v2i32 (and a, {0x7fffffff,0x7fffffff}) as ABS.
3662 // (or a, 0x80000000) or v2i32 (or a, {0x80000000,0x80000000}) as NEG+ABS
3663 // SrcModifiers.
3664 if (Opc == ISD::XOR && CRHS->getAPIntValue().isSignMask()) {
3665 Mods |= SISrcMods::NEG;
3666 Src = ReplaceSrc();
3667 } else if (Opc == ISD::AND && AllowAbs &&
3668 CRHS->getAPIntValue().isMaxSignedValue()) {
3669 Mods |= SISrcMods::ABS;
3670 Src = ReplaceSrc();
3671 } else if (Opc == ISD::OR && AllowAbs && CRHS->getAPIntValue().isSignMask()) {
3673 Src = ReplaceSrc();
3674 }
3675
3676 return true;
3677}
3678
3679bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
3680 SDValue &SrcMods) const {
3681 unsigned Mods;
3682 if (SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/true,
3683 /*AllowAbs=*/true)) {
3684 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3685 return true;
3686 }
3687
3688 return false;
3689}
3690
3691bool AMDGPUDAGToDAGISel::SelectVOP3ModsNonCanonicalizing(
3692 SDValue In, SDValue &Src, SDValue &SrcMods) const {
3693 unsigned Mods;
3694 if (SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/false,
3695 /*AllowAbs=*/true)) {
3696 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3697 return true;
3698 }
3699
3700 return false;
3701}
3702
3703bool AMDGPUDAGToDAGISel::SelectVOP3BMods(SDValue In, SDValue &Src,
3704 SDValue &SrcMods) const {
3705 unsigned Mods;
3706 if (SelectVOP3ModsImpl(In, Src, Mods,
3707 /*IsCanonicalizing=*/true,
3708 /*AllowAbs=*/false)) {
3709 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3710 return true;
3711 }
3712
3713 return false;
3714}
3715
3716bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src) const {
3717 if (In.getOpcode() == ISD::FABS || In.getOpcode() == ISD::FNEG)
3718 return false;
3719
3720 Src = In;
3721 return true;
3722}
3723
3724bool AMDGPUDAGToDAGISel::SelectVOP3NoOpSelMods(SDValue In, SDValue &Src) const {
3726 if (isExtractHiElt(In, Unused))
3727 return false;
3728
3729 return SelectVOP3NoMods(In, Src);
3730}
3731
3732bool AMDGPUDAGToDAGISel::SelectVINTERPModsImpl(SDValue In, SDValue &Src,
3733 SDValue &SrcMods,
3734 bool OpSel) const {
3735 unsigned Mods;
3736 if (SelectVOP3ModsImpl(In, Src, Mods,
3737 /*IsCanonicalizing=*/true,
3738 /*AllowAbs=*/false)) {
3739 if (OpSel)
3740 Mods |= SISrcMods::OP_SEL_0;
3741 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3742 return true;
3743 }
3744
3745 return false;
3746}
3747
3748bool AMDGPUDAGToDAGISel::SelectVINTERPMods(SDValue In, SDValue &Src,
3749 SDValue &SrcMods) const {
3750 return SelectVINTERPModsImpl(In, Src, SrcMods, /* OpSel */ false);
3751}
3752
3753bool AMDGPUDAGToDAGISel::SelectVINTERPModsHi(SDValue In, SDValue &Src,
3754 SDValue &SrcMods) const {
3755 return SelectVINTERPModsImpl(In, Src, SrcMods, /* OpSel */ true);
3756}
3757
3758bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
3759 SDValue &SrcMods, SDValue &Clamp,
3760 SDValue &Omod) const {
3761 SDLoc DL(In);
3762 Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
3763 Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
3764
3765 return SelectVOP3Mods(In, Src, SrcMods);
3766}
3767
3768bool AMDGPUDAGToDAGISel::SelectVOP3BMods0(SDValue In, SDValue &Src,
3769 SDValue &SrcMods, SDValue &Clamp,
3770 SDValue &Omod) const {
3771 SDLoc DL(In);
3772 Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
3773 Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
3774
3775 return SelectVOP3BMods(In, Src, SrcMods);
3776}
3777
3778bool AMDGPUDAGToDAGISel::SelectVOP3OMods(SDValue In, SDValue &Src,
3779 SDValue &Clamp, SDValue &Omod) const {
3780 Src = In;
3781
3782 SDLoc DL(In);
3783 Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
3784 Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
3785
3786 return true;
3787}
3788
3789bool AMDGPUDAGToDAGISel::SelectVOP3PModsPkFmaOpSel0(SDValue In, SDValue &Src,
3790 SDValue &SrcMods) const {
3791 return SelectVOP3PMods(In, Src, SrcMods, false,
3792 Subtarget->hasPkF32InvalidOpSel() &&
3793 In.getValueType() == MVT::v2f32);
3794}
3795
3796bool AMDGPUDAGToDAGISel::SelectVOP3PModsPkAddMulOpSel0(SDValue In, SDValue &Src,
3797 SDValue &SrcMods) const {
3798 if (!SelectVOP3PMods(In, Src, SrcMods))
3799 return false;
3800
3801 return !Subtarget->hasPkF32InvalidOpSel() ||
3802 In.getValueType() != MVT::v2f32 ||
3803 (cast<ConstantSDNode>(SrcMods)->getZExtValue() &
3804 SISrcMods::OP_SEL_0) == 0;
3805}
3806
3807bool AMDGPUDAGToDAGISel::SelectVOP3PMods(SDValue In, SDValue &Src,
3808 SDValue &SrcMods, bool IsDOT,
3809 bool NoOpSel0) const {
3810 unsigned Mods = SISrcMods::NONE;
3811 Src = In;
3812
3813 // TODO: Handle G_FSUB 0 as fneg
3814 if (Src.getOpcode() == ISD::FNEG) {
3816 Src = Src.getOperand(0);
3817 }
3818
3819 // 64-bit VOP3P instructions do not have OPSEL or ABS.
3820 bool HasOpSel = Src.getValueSizeInBits() != 128;
3821
3822 if (Src.getOpcode() == ISD::BUILD_VECTOR && Src.getNumOperands() == 2 &&
3823 (!IsDOT || !Subtarget->hasDOTOpSelHazard()) &&
3824 (!NoOpSel0 || !isLoEltExtractHi(Src))) {
3825 unsigned VecMods = Mods;
3826
3827 SDValue Lo = stripBitcast(Src.getOperand(0));
3828 SDValue Hi = stripBitcast(Src.getOperand(1));
3829
3830 if (Lo.getOpcode() == ISD::FNEG) {
3831 Lo = stripBitcast(Lo.getOperand(0));
3832 Mods ^= SISrcMods::NEG;
3833 }
3834
3835 if (Hi.getOpcode() == ISD::FNEG) {
3836 Hi = stripBitcast(Hi.getOperand(0));
3837 Mods ^= SISrcMods::NEG_HI;
3838 }
3839
3840 if (HasOpSel) {
3841 if (isExtractHiElt(Lo, Lo))
3842 Mods |= SISrcMods::OP_SEL_0;
3843
3844 if (isExtractHiElt(Hi, Hi))
3845 Mods |= SISrcMods::OP_SEL_1;
3846 }
3847
3848 unsigned VecSize = Src.getValueSizeInBits();
3849 Lo = stripExtractLoElt(Lo);
3850 Hi = stripExtractLoElt(Hi);
3851
3852 if (Lo.getValueSizeInBits() > VecSize) {
3853 Lo = CurDAG->getTargetExtractSubreg(
3854 (VecSize > 32) ? AMDGPU::sub0_sub1 : AMDGPU::sub0, SDLoc(In),
3855 MVT::getIntegerVT(VecSize), Lo);
3856 }
3857
3858 if (Hi.getValueSizeInBits() > VecSize) {
3859 Hi = CurDAG->getTargetExtractSubreg(
3860 (VecSize > 32) ? AMDGPU::sub0_sub1 : AMDGPU::sub0, SDLoc(In),
3861 MVT::getIntegerVT(VecSize), Hi);
3862 }
3863
3864 assert(Lo.getValueSizeInBits() <= VecSize &&
3865 Hi.getValueSizeInBits() <= VecSize);
3866
3867 if (Lo == Hi && !isInlineImmediate(Lo.getNode())) {
3868 // Really a scalar input. Just select from the low half of the register to
3869 // avoid packing.
3870
3871 if (VecSize == Lo.getValueSizeInBits()) {
3872 Src = Lo;
3873 } else if (VecSize == 32) {
3874 Src = createVOP3PSrc32FromLo16(Lo, Src, CurDAG, Subtarget);
3875 } else {
3876 assert((Lo.getValueSizeInBits() == 32 && VecSize == 64) ||
3877 (Lo.getValueSizeInBits() == 64 && VecSize == 128));
3878
3879 SDLoc SL(In);
3881 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, SL,
3882 Lo.getValueType()), 0);
3883 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3884 // <2 x 64> instructions do not have OPSEL and also replicate low 64
3885 // bits of a scalar input into high 64 bits. Use VGPRs in this case.
3886 // TODO: This fact can be exploited but we need to set proper OPSEL for
3887 // codegen folding purposes. It will not affect a final instruction.
3888 auto RC = Lo->isDivergent() ? TRI->getVGPRClassForBitWidth(VecSize)
3889 : TRI->getSGPRClassForBitWidth(VecSize);
3890 unsigned NumRegs = Lo.getValueSizeInBits() == 32 ? 1 : 2;
3891 const SDValue Ops[] = {
3892 CurDAG->getTargetConstant(RC->getID(), SL, MVT::i32), Lo,
3893 CurDAG->getTargetConstant(TRI->getSubRegFromChannel(0, NumRegs), SL,
3894 MVT::i32),
3895 // For packed 64-bit ops without OPSEL support, a later pass will
3896 // optimize the splat sgpr patterns to save registers.
3897 HasOpSel ? Undef : Lo,
3898 CurDAG->getTargetConstant(
3899 TRI->getSubRegFromChannel(NumRegs, NumRegs), SL, MVT::i32)};
3900
3901 Src = SDValue(CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, SL,
3902 Src.getValueType(), Ops), 0);
3903 // Check that both op_sel_0 and op_sel_1 are zero.
3905 }
3906 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3907 return true;
3908 }
3909
3910 if (VecSize == 64 && Lo == Hi && isa<ConstantFPSDNode>(Lo)) {
3911 uint64_t Lit = cast<ConstantFPSDNode>(Lo)->getValueAPF()
3912 .bitcastToAPInt().getZExtValue();
3913 if (AMDGPU::isInlinableLiteral32(Lit, Subtarget->hasInv2PiInlineImm())) {
3914 Src = CurDAG->getTargetConstant(Lit, SDLoc(In), MVT::i64);
3915 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3916 return true;
3917 }
3918 }
3919
3920 Mods = VecMods;
3921 } else if (Src.getOpcode() == ISD::VECTOR_SHUFFLE &&
3922 Src.getNumOperands() == 2) {
3923
3924 // TODO: We should repeat the build_vector source check above for the
3925 // vector_shuffle for negates and casts of individual elements.
3926
3927 assert(Src.getValueSizeInBits() != 128 &&
3928 "<2 x 64> VECTOR_SHUFFLE should not be legal.");
3929
3930 auto *SVN = cast<ShuffleVectorSDNode>(Src);
3931 ArrayRef<int> Mask = SVN->getMask();
3932
3933 if (Mask[0] < 2 && Mask[1] < 2 && (!NoOpSel0 || Mask[0] != 1)) {
3934 // src1 should be undef.
3935 SDValue ShuffleSrc = SVN->getOperand(0);
3936
3937 if (ShuffleSrc.getOpcode() == ISD::FNEG) {
3938 ShuffleSrc = ShuffleSrc.getOperand(0);
3940 }
3941
3942 if (Mask[0] == 1)
3943 Mods |= SISrcMods::OP_SEL_0;
3944 if (Mask[1] == 1)
3945 Mods |= SISrcMods::OP_SEL_1;
3946
3947 Src = ShuffleSrc;
3948 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3949 return true;
3950 }
3951 }
3952
3953 // Packed instructions do not have abs modifiers.
3954 Mods |= SISrcMods::OP_SEL_1;
3955
3956 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3957 return true;
3958}
3959
3960bool AMDGPUDAGToDAGISel::SelectVOP3PModsDOT(SDValue In, SDValue &Src,
3961 SDValue &SrcMods) const {
3962 return SelectVOP3PMods(In, Src, SrcMods, true);
3963}
3964
3965bool AMDGPUDAGToDAGISel::SelectVOP3PNoModsDOT(SDValue In, SDValue &Src) const {
3966 SDValue SrcTmp, SrcModsTmp;
3967 SelectVOP3PMods(In, SrcTmp, SrcModsTmp, true);
3968 if (cast<ConstantSDNode>(SrcModsTmp)->getZExtValue() == SISrcMods::OP_SEL_1) {
3969 Src = SrcTmp;
3970 return true;
3971 }
3972
3973 return false;
3974}
3975
3976bool AMDGPUDAGToDAGISel::SelectVOP3PModsF32(SDValue In, SDValue &Src,
3977 SDValue &SrcMods) const {
3978 SelectVOP3Mods(In, Src, SrcMods);
3979 unsigned Mods = SISrcMods::OP_SEL_1;
3980 Mods |= cast<ConstantSDNode>(SrcMods)->getZExtValue();
3981 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3982 return true;
3983}
3984
3985bool AMDGPUDAGToDAGISel::SelectVOP3PNoModsF32(SDValue In, SDValue &Src) const {
3986 SDValue SrcTmp, SrcModsTmp;
3987 SelectVOP3PModsF32(In, SrcTmp, SrcModsTmp);
3988 if (cast<ConstantSDNode>(SrcModsTmp)->getZExtValue() == SISrcMods::OP_SEL_1) {
3989 Src = SrcTmp;
3990 return true;
3991 }
3992
3993 return false;
3994}
3995
3996bool AMDGPUDAGToDAGISel::SelectWMMAOpSelVOP3PMods(SDValue In,
3997 SDValue &Src) const {
3998 const ConstantSDNode *C = cast<ConstantSDNode>(In);
3999 assert(C->getAPIntValue().getBitWidth() == 1 && "expected i1 value");
4000
4001 unsigned Mods = SISrcMods::OP_SEL_1;
4002 unsigned SrcVal = C->getZExtValue();
4003 if (SrcVal == 1)
4004 Mods |= SISrcMods::OP_SEL_0;
4005
4006 Src = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4007 return true;
4008}
4009
4011AMDGPUDAGToDAGISel::buildRegSequence32(SmallVectorImpl<SDValue> &Elts,
4012 const SDLoc &DL) const {
4013 unsigned DstRegClass;
4014 EVT DstTy;
4015 switch (Elts.size()) {
4016 case 8:
4017 DstRegClass = AMDGPU::VReg_256RegClassID;
4018 DstTy = MVT::v8i32;
4019 break;
4020 case 4:
4021 DstRegClass = AMDGPU::VReg_128RegClassID;
4022 DstTy = MVT::v4i32;
4023 break;
4024 case 2:
4025 DstRegClass = AMDGPU::VReg_64RegClassID;
4026 DstTy = MVT::v2i32;
4027 break;
4028 default:
4029 llvm_unreachable("unhandled Reg sequence size");
4030 }
4031
4033 Ops.push_back(CurDAG->getTargetConstant(DstRegClass, DL, MVT::i32));
4034 for (unsigned i = 0; i < Elts.size(); ++i) {
4035 Ops.push_back(Elts[i]);
4036 Ops.push_back(CurDAG->getTargetConstant(
4038 }
4039 return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, DstTy, Ops);
4040}
4041
4043AMDGPUDAGToDAGISel::buildRegSequence16(SmallVectorImpl<SDValue> &Elts,
4044 const SDLoc &DL) const {
4045 SmallVector<SDValue, 8> PackedElts;
4046 assert("unhandled Reg sequence size" &&
4047 (Elts.size() == 8 || Elts.size() == 16));
4048
4049 // Pack 16-bit elements in pairs into 32-bit register. If both elements are
4050 // unpacked from 32-bit source use it, otherwise pack them using v_perm.
4051 for (unsigned i = 0; i < Elts.size(); i += 2) {
4052 SDValue LoSrc = stripExtractLoElt(stripBitcast(Elts[i]));
4053 SDValue HiSrc;
4054 if (isExtractHiElt(Elts[i + 1], HiSrc) && LoSrc == HiSrc) {
4055 PackedElts.push_back(HiSrc);
4056 } else {
4057 if (Subtarget->useRealTrue16Insts()) {
4058 // FIXME-TRUE16. For now pack VGPR_32 for 16-bit source before
4059 // passing to v_perm_b32. Eventually we should use replace v_perm_b32
4060 // by reg_sequence.
4062 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i16),
4063 0);
4064 Elts[i] =
4065 emitRegSequence(*CurDAG, AMDGPU::VGPR_32RegClassID, MVT::i32,
4066 {Elts[i], Undef}, {AMDGPU::lo16, AMDGPU::hi16}, DL);
4067 Elts[i + 1] = emitRegSequence(*CurDAG, AMDGPU::VGPR_32RegClassID,
4068 MVT::i32, {Elts[i + 1], Undef},
4069 {AMDGPU::lo16, AMDGPU::hi16}, DL);
4070 }
4071 SDValue PackLoLo = CurDAG->getTargetConstant(0x05040100, DL, MVT::i32);
4072 MachineSDNode *Packed =
4073 CurDAG->getMachineNode(AMDGPU::V_PERM_B32_e64, DL, MVT::i32,
4074 {Elts[i + 1], Elts[i], PackLoLo});
4075 PackedElts.push_back(SDValue(Packed, 0));
4076 }
4077 }
4078 return buildRegSequence32(PackedElts, DL);
4079}
4080
4082AMDGPUDAGToDAGISel::buildRegSequence(SmallVectorImpl<SDValue> &Elts,
4083 const SDLoc &DL,
4084 unsigned ElementSize) const {
4085 if (ElementSize == 16)
4086 return buildRegSequence16(Elts, DL);
4087 if (ElementSize == 32)
4088 return buildRegSequence32(Elts, DL);
4089 llvm_unreachable("Unhandled element size");
4090}
4091
4092void AMDGPUDAGToDAGISel::selectWMMAModsNegAbs(unsigned ModOpcode,
4093 unsigned &Mods,
4095 SDValue &Src, const SDLoc &DL,
4096 unsigned ElementSize) const {
4097 if (ModOpcode == ISD::FNEG) {
4098 Mods |= SISrcMods::NEG;
4099 // Check if all elements also have abs modifier
4100 SmallVector<SDValue, 8> NegAbsElts;
4101 for (auto El : Elts) {
4102 if (El.getOpcode() != ISD::FABS)
4103 break;
4104 NegAbsElts.push_back(El->getOperand(0));
4105 }
4106 if (Elts.size() != NegAbsElts.size()) {
4107 // Neg
4108 Src = SDValue(buildRegSequence(Elts, DL, ElementSize), 0);
4109 } else {
4110 // Neg and Abs
4111 Mods |= SISrcMods::NEG_HI;
4112 Src = SDValue(buildRegSequence(NegAbsElts, DL, ElementSize), 0);
4113 }
4114 } else {
4115 assert(ModOpcode == ISD::FABS);
4116 // Abs
4117 Mods |= SISrcMods::NEG_HI;
4118 Src = SDValue(buildRegSequence(Elts, DL, ElementSize), 0);
4119 }
4120}
4121
4122// Check all f16 elements for modifiers while looking through b32 and v2b16
4123// build vector, stop if element does not satisfy ModifierCheck.
4124static void
4126 std::function<bool(SDValue)> ModifierCheck) {
4127 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4128 if (auto *F16Pair =
4129 dyn_cast<BuildVectorSDNode>(stripBitcast(BV->getOperand(i)))) {
4130 for (unsigned i = 0; i < F16Pair->getNumOperands(); ++i) {
4131 SDValue ElF16 = stripBitcast(F16Pair->getOperand(i));
4132 if (!ModifierCheck(ElF16))
4133 break;
4134 }
4135 }
4136 }
4137}
4138
4139bool AMDGPUDAGToDAGISel::SelectWMMAModsF16Neg(SDValue In, SDValue &Src,
4140 SDValue &SrcMods) const {
4141 Src = In;
4142 unsigned Mods = SISrcMods::OP_SEL_1;
4143
4144 // mods are on f16 elements
4145 if (auto *BV = dyn_cast<BuildVectorSDNode>(stripBitcast(In))) {
4147
4148 checkWMMAElementsModifiersF16(BV, [&](SDValue Element) -> bool {
4149 if (Element.getOpcode() != ISD::FNEG)
4150 return false;
4151 EltsF16.push_back(Element.getOperand(0));
4152 return true;
4153 });
4154
4155 // All elements have neg modifier
4156 if (BV->getNumOperands() * 2 == EltsF16.size()) {
4157 Src = SDValue(buildRegSequence16(EltsF16, SDLoc(In)), 0);
4158 Mods |= SISrcMods::NEG;
4159 Mods |= SISrcMods::NEG_HI;
4160 }
4161 }
4162
4163 // mods are on v2f16 elements
4164 if (auto *BV = dyn_cast<BuildVectorSDNode>(stripBitcast(In))) {
4165 SmallVector<SDValue, 8> EltsV2F16;
4166 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4167 SDValue ElV2f16 = stripBitcast(BV->getOperand(i));
4168 // Based on first element decide which mod we match, neg or abs
4169 if (ElV2f16.getOpcode() != ISD::FNEG)
4170 break;
4171 EltsV2F16.push_back(ElV2f16.getOperand(0));
4172 }
4173
4174 // All pairs of elements have neg modifier
4175 if (BV->getNumOperands() == EltsV2F16.size()) {
4176 Src = SDValue(buildRegSequence32(EltsV2F16, SDLoc(In)), 0);
4177 Mods |= SISrcMods::NEG;
4178 Mods |= SISrcMods::NEG_HI;
4179 }
4180 }
4181
4182 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4183 return true;
4184}
4185
4186bool AMDGPUDAGToDAGISel::SelectWMMAModsF16NegAbs(SDValue In, SDValue &Src,
4187 SDValue &SrcMods) const {
4188 Src = In;
4189 unsigned Mods = SISrcMods::OP_SEL_1;
4190 unsigned ModOpcode;
4191
4192 // mods are on f16 elements
4193 if (auto *BV = dyn_cast<BuildVectorSDNode>(stripBitcast(In))) {
4195 checkWMMAElementsModifiersF16(BV, [&](SDValue ElF16) -> bool {
4196 // Based on first element decide which mod we match, neg or abs
4197 if (EltsF16.empty())
4198 ModOpcode = (ElF16.getOpcode() == ISD::FNEG) ? ISD::FNEG : ISD::FABS;
4199 if (ElF16.getOpcode() != ModOpcode)
4200 return false;
4201 EltsF16.push_back(ElF16.getOperand(0));
4202 return true;
4203 });
4204
4205 // All elements have ModOpcode modifier
4206 if (BV->getNumOperands() * 2 == EltsF16.size())
4207 selectWMMAModsNegAbs(ModOpcode, Mods, EltsF16, Src, SDLoc(In), 16);
4208 }
4209
4210 // mods are on v2f16 elements
4211 if (auto *BV = dyn_cast<BuildVectorSDNode>(stripBitcast(In))) {
4212 SmallVector<SDValue, 8> EltsV2F16;
4213
4214 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4215 SDValue ElV2f16 = stripBitcast(BV->getOperand(i));
4216 // Based on first element decide which mod we match, neg or abs
4217 if (EltsV2F16.empty())
4218 ModOpcode = (ElV2f16.getOpcode() == ISD::FNEG) ? ISD::FNEG : ISD::FABS;
4219 if (ElV2f16->getOpcode() != ModOpcode)
4220 break;
4221 EltsV2F16.push_back(ElV2f16->getOperand(0));
4222 }
4223
4224 // All elements have ModOpcode modifier
4225 if (BV->getNumOperands() == EltsV2F16.size())
4226 selectWMMAModsNegAbs(ModOpcode, Mods, EltsV2F16, Src, SDLoc(In), 32);
4227 }
4228
4229 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4230 return true;
4231}
4232
4233bool AMDGPUDAGToDAGISel::SelectWMMAModsF32NegAbs(SDValue In, SDValue &Src,
4234 SDValue &SrcMods) const {
4235 Src = In;
4236 unsigned Mods = SISrcMods::OP_SEL_1;
4238
4239 if (auto *BV = dyn_cast<BuildVectorSDNode>(stripBitcast(In))) {
4240 assert(BV->getNumOperands() > 0);
4241 // Based on first element decide which mod we match, neg or abs
4242 SDValue ElF32 = stripBitcast(BV->getOperand(0));
4243 unsigned ModOpcode =
4244 (ElF32.getOpcode() == ISD::FNEG) ? ISD::FNEG : ISD::FABS;
4245 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4246 SDValue ElF32 = stripBitcast(BV->getOperand(i));
4247 if (ElF32.getOpcode() != ModOpcode)
4248 break;
4249 EltsF32.push_back(ElF32.getOperand(0));
4250 }
4251
4252 // All elements had ModOpcode modifier
4253 if (BV->getNumOperands() == EltsF32.size())
4254 selectWMMAModsNegAbs(ModOpcode, Mods, EltsF32, Src, SDLoc(In), 32);
4255 }
4256
4257 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4258 return true;
4259}
4260
4261bool AMDGPUDAGToDAGISel::SelectWMMAVISrc(SDValue In, SDValue &Src) const {
4262 if (auto *BV = dyn_cast<BuildVectorSDNode>(In)) {
4263 BitVector UndefElements;
4264 if (SDValue Splat = BV->getSplatValue(&UndefElements))
4265 if (isInlineImmediate(Splat.getNode())) {
4266 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Splat)) {
4267 unsigned Imm = C->getAPIntValue().getSExtValue();
4268 Src = CurDAG->getTargetConstant(Imm, SDLoc(In), MVT::i32);
4269 return true;
4270 }
4271 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Splat)) {
4272 unsigned Imm = C->getValueAPF().bitcastToAPInt().getSExtValue();
4273 Src = CurDAG->getTargetConstant(Imm, SDLoc(In), MVT::i32);
4274 return true;
4275 }
4276 llvm_unreachable("unhandled Constant node");
4277 }
4278 }
4279
4280 // 16 bit splat
4281 SDValue SplatSrc32 = stripBitcast(In);
4282 if (auto *SplatSrc32BV = dyn_cast<BuildVectorSDNode>(SplatSrc32))
4283 if (SDValue Splat32 = SplatSrc32BV->getSplatValue()) {
4284 SDValue SplatSrc16 = stripBitcast(Splat32);
4285 if (auto *SplatSrc16BV = dyn_cast<BuildVectorSDNode>(SplatSrc16))
4286 if (SDValue Splat = SplatSrc16BV->getSplatValue()) {
4287 const SIInstrInfo *TII = Subtarget->getInstrInfo();
4288 std::optional<APInt> RawValue;
4289 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Splat))
4290 RawValue = C->getValueAPF().bitcastToAPInt();
4291 else if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Splat))
4292 RawValue = C->getAPIntValue();
4293
4294 if (RawValue.has_value()) {
4295 EVT VT = In.getValueType().getScalarType();
4296 if (VT.getSimpleVT() == MVT::f16 || VT.getSimpleVT() == MVT::bf16) {
4297 APFloat FloatVal(VT.getSimpleVT() == MVT::f16
4300 RawValue.value());
4301 if (TII->isInlineConstant(FloatVal)) {
4302 Src = CurDAG->getTargetConstant(RawValue.value(), SDLoc(In),
4303 MVT::i16);
4304 return true;
4305 }
4306 } else if (VT.getSimpleVT() == MVT::i16) {
4307 if (TII->isInlineConstant(RawValue.value())) {
4308 Src = CurDAG->getTargetConstant(RawValue.value(), SDLoc(In),
4309 MVT::i16);
4310 return true;
4311 }
4312 } else
4313 llvm_unreachable("unknown 16-bit type");
4314 }
4315 }
4316 }
4317
4318 // Currently f64 immediate vectors are represented as vectors of v2i32, with
4319 // different lo and hi 32-bit values even though double values are splated.
4320 // So we have to manually compare to determine whether it is splated.
4321 if (CurDAG->isConstantIntBuildVectorOrConstantInt(SplatSrc32)) {
4322 int64_t Imm64 = 0;
4323 for (unsigned i = 0; i < SplatSrc32->getNumOperands(); i += 2) {
4324 auto Lo32 = cast<ConstantSDNode>(SplatSrc32->getOperand(i));
4325 auto Hi32 = cast<ConstantSDNode>(SplatSrc32->getOperand(i + 1));
4326 int64_t LoImm = Lo32->getAPIntValue().getSExtValue();
4327 int64_t HiImm = Hi32->getAPIntValue().getSExtValue();
4328 int64_t Imm64I = (HiImm << 32) + LoImm;
4329 if (i == 0) {
4330 if (!isInlineImmediate(APInt(64, Imm64I)))
4331 return false;
4332 Imm64 = Imm64I;
4333 } else if (Imm64I != Imm64)
4334 return false;
4335 } // end for
4336
4337 Src = CurDAG->getTargetConstant(Imm64, SDLoc(In), MVT::i64);
4338 return true;
4339 }
4340
4341 return false;
4342}
4343
4344bool AMDGPUDAGToDAGISel::SelectSWMMACIndex8(SDValue In, SDValue &Src,
4345 SDValue &IndexKey) const {
4346 unsigned Key = 0;
4347 Src = In;
4348
4349 if (In.getOpcode() == ISD::SRL) {
4350 const llvm::SDValue &ShiftSrc = In.getOperand(0);
4351 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
4352 if (ShiftSrc.getValueType().getSizeInBits() == 32 && ShiftAmt &&
4353 ShiftAmt->getZExtValue() % 8 == 0) {
4354 Key = ShiftAmt->getZExtValue() / 8;
4355 Src = ShiftSrc;
4356 }
4357 }
4358
4359 IndexKey = CurDAG->getTargetConstant(Key, SDLoc(In), MVT::i32);
4360 return true;
4361}
4362
4363bool AMDGPUDAGToDAGISel::SelectSWMMACIndex16(SDValue In, SDValue &Src,
4364 SDValue &IndexKey) const {
4365 unsigned Key = 0;
4366 Src = In;
4367
4368 if (In.getOpcode() == ISD::SRL) {
4369 const llvm::SDValue &ShiftSrc = In.getOperand(0);
4370 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
4371 if (ShiftSrc.getValueType().getSizeInBits() == 32 && ShiftAmt &&
4372 ShiftAmt->getZExtValue() == 16) {
4373 Key = 1;
4374 Src = ShiftSrc;
4375 }
4376 }
4377
4378 IndexKey = CurDAG->getTargetConstant(Key, SDLoc(In), MVT::i32);
4379 return true;
4380}
4381
4382bool AMDGPUDAGToDAGISel::SelectSWMMACIndex32(SDValue In, SDValue &Src,
4383 SDValue &IndexKey) const {
4384 unsigned Key = 0;
4385 Src = In;
4386
4387 SDValue InI32;
4388
4389 if (In.getOpcode() == ISD::ANY_EXTEND || In.getOpcode() == ISD::ZERO_EXTEND) {
4390 const SDValue &ExtendSrc = In.getOperand(0);
4391 if (ExtendSrc.getValueSizeInBits() == 32)
4392 InI32 = ExtendSrc;
4393 } else if (In->getOpcode() == ISD::BITCAST) {
4394 const SDValue &CastSrc = In.getOperand(0);
4395 if (CastSrc.getOpcode() == ISD::BUILD_VECTOR &&
4396 CastSrc.getOperand(0).getValueSizeInBits() == 32) {
4397 ConstantSDNode *Zero = dyn_cast<ConstantSDNode>(CastSrc.getOperand(1));
4398 if (Zero && Zero->getZExtValue() == 0)
4399 InI32 = CastSrc.getOperand(0);
4400 }
4401 }
4402
4403 if (InI32 && InI32.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4404 const SDValue &ExtractVecEltSrc = InI32.getOperand(0);
4405 ConstantSDNode *EltIdx = dyn_cast<ConstantSDNode>(InI32.getOperand(1));
4406 if (ExtractVecEltSrc.getValueSizeInBits() == 64 && EltIdx &&
4407 EltIdx->getZExtValue() == 1) {
4408 Key = 1;
4409 Src = ExtractVecEltSrc;
4410 }
4411 }
4412
4413 IndexKey = CurDAG->getTargetConstant(Key, SDLoc(In), MVT::i32);
4414 return true;
4415}
4416
4417bool AMDGPUDAGToDAGISel::SelectVOP3OpSel(SDValue In, SDValue &Src,
4418 SDValue &SrcMods) const {
4419 unsigned Mods = SISrcMods::NONE;
4420 Src = In;
4421 if (!Subtarget->useRealTrue16Insts() && In.getValueSizeInBits() == 16 &&
4422 isExtractHiElt(Src, Src))
4423 Mods |= SISrcMods::OP_SEL_0;
4424 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4425 return true;
4426}
4427
4428bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods(SDValue In, SDValue &Src,
4429 SDValue &SrcMods) const {
4430 unsigned Mods;
4431 if (!SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/true,
4432 /*AllowAbs=*/true))
4433 return false;
4434
4435 if (!Subtarget->useRealTrue16Insts() && In.getValueSizeInBits() == 16 &&
4436 isExtractHiElt(Src, Src))
4437 Mods |= SISrcMods::OP_SEL_0;
4438
4439 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4440 return true;
4441}
4442
4443// Match lowered fpext from bf16 to f32. This is a bit operation extending
4444// a 16-bit value with 16-bit of zeroes at LSB:
4445//
4446// 1. (f32 (bitcast (build_vector (i16 0), (i16 (bitcast bf16:val)))))
4447// 2. (f32 (bitcast (and i32:val, 0xffff0000))) -> IsExtractHigh = true
4448// 3. (f32 (bitcast (shl i32:va, 16) -> IsExtractHigh = false
4449static SDValue matchBF16FPExtendLike(SDValue Op, bool &IsExtractHigh) {
4450 if (Op.getValueType() != MVT::f32 || Op.getOpcode() != ISD::BITCAST)
4451 return SDValue();
4452 Op = Op.getOperand(0);
4453
4454 IsExtractHigh = false;
4455 if (Op.getValueType() == MVT::v2i16 && Op.getOpcode() == ISD::BUILD_VECTOR) {
4456 auto Low16 = dyn_cast<ConstantSDNode>(Op.getOperand(0));
4457 if (!Low16 || !Low16->isZero())
4458 return SDValue();
4459 Op = stripBitcast(Op.getOperand(1));
4460 if (Op.getValueType() != MVT::bf16)
4461 return SDValue();
4462 return Op;
4463 }
4464
4465 if (Op.getValueType() != MVT::i32)
4466 return SDValue();
4467
4468 if (Op.getOpcode() == ISD::AND) {
4469 if (auto Mask = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4470 if (Mask->getZExtValue() == 0xffff0000) {
4471 IsExtractHigh = true;
4472 return Op.getOperand(0);
4473 }
4474 }
4475 return SDValue();
4476 }
4477
4478 if (Op.getOpcode() == ISD::SHL) {
4479 if (auto Amt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4480 if (Amt->getZExtValue() == 16)
4481 return Op.getOperand(0);
4482 }
4483 }
4484
4485 return SDValue();
4486}
4487
4488// The return value is not whether the match is possible (which it always is),
4489// but whether or not it a conversion is really used.
4490bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src,
4491 unsigned &Mods,
4492 MVT VT) const {
4493 Mods = 0;
4494 SelectVOP3ModsImpl(In, Src, Mods);
4495
4496 bool IsExtractHigh = false;
4497 if (Src.getOpcode() == ISD::FP_EXTEND &&
4498 Src.getOperand(0).getValueType() == VT) {
4499 Src = Src.getOperand(0);
4500 } else if (VT == MVT::bf16) {
4501 SDValue B16 = matchBF16FPExtendLike(Src, IsExtractHigh);
4502 if (!B16)
4503 return false;
4504 Src = B16;
4505 } else
4506 return false;
4507
4508 if (Src.getValueType() != VT &&
4509 (VT != MVT::bf16 || Src.getValueType() != MVT::i32))
4510 return false;
4511
4512 Src = stripBitcast(Src);
4513
4514 // Be careful about folding modifiers if we already have an abs. fneg is
4515 // applied last, so we don't want to apply an earlier fneg.
4516 if ((Mods & SISrcMods::ABS) == 0) {
4517 unsigned ModsTmp;
4518 SelectVOP3ModsImpl(Src, Src, ModsTmp);
4519
4520 if ((ModsTmp & SISrcMods::NEG) != 0)
4521 Mods ^= SISrcMods::NEG;
4522
4523 if ((ModsTmp & SISrcMods::ABS) != 0)
4524 Mods |= SISrcMods::ABS;
4525 }
4526
4527 // op_sel/op_sel_hi decide the source type and source.
4528 // If the source's op_sel_hi is set, it indicates to do a conversion from
4529 // fp16. If the sources's op_sel is set, it picks the high half of the source
4530 // register.
4531
4532 Mods |= SISrcMods::OP_SEL_1;
4533 if (Src.getValueSizeInBits() == 16) {
4534 if (isExtractHiElt(Src, Src)) {
4535 Mods |= SISrcMods::OP_SEL_0;
4536
4537 // TODO: Should we try to look for neg/abs here?
4538 return true;
4539 }
4540
4541 if (Src.getOpcode() == ISD::TRUNCATE &&
4542 Src.getOperand(0).getValueType() == MVT::i32) {
4543 Src = Src.getOperand(0);
4544 return true;
4545 }
4546
4547 if (Subtarget->useRealTrue16Insts())
4548 // In true16 mode, pack src to a 32bit
4549 Src = createVOP3PSrc32FromLo16(Src, In, CurDAG, Subtarget);
4550 } else if (IsExtractHigh)
4551 Mods |= SISrcMods::OP_SEL_0;
4552
4553 return true;
4554}
4555
4556bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsExt(SDValue In, SDValue &Src,
4557 SDValue &SrcMods) const {
4558 unsigned Mods = 0;
4559 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::f16))
4560 return false;
4561 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4562 return true;
4563}
4564
4565bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixMods(SDValue In, SDValue &Src,
4566 SDValue &SrcMods) const {
4567 unsigned Mods = 0;
4568 SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::f16);
4569 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4570 return true;
4571}
4572
4573bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsExtNeg(SDValue In, SDValue &Src,
4574 SDValue &SrcMods) const {
4575 unsigned Mods = 0;
4576 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::f16))
4577 return false;
4578 SrcMods =
4579 CurDAG->getTargetConstant(Mods ^ SISrcMods::NEG, SDLoc(In), MVT::i32);
4580 return true;
4581}
4582
4583bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsNeg(SDValue In, SDValue &Src,
4584 SDValue &SrcMods) const {
4585 unsigned Mods = 0;
4586 SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::f16);
4587 SrcMods =
4588 CurDAG->getTargetConstant(Mods ^ SISrcMods::NEG, SDLoc(In), MVT::i32);
4589 return true;
4590}
4591
4592bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16ModsExt(SDValue In, SDValue &Src,
4593 SDValue &SrcMods) const {
4594 unsigned Mods = 0;
4595 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::bf16))
4596 return false;
4597 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4598 return true;
4599}
4600
4601bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16Mods(SDValue In, SDValue &Src,
4602 SDValue &SrcMods) const {
4603 unsigned Mods = 0;
4604 SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::bf16);
4605 SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
4606 return true;
4607}
4608
4609bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16ModsExtNeg(
4610 SDValue In, SDValue &Src, SDValue &SrcMods) const {
4611 unsigned Mods = 0;
4612 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::bf16))
4613 return false;
4614 SrcMods =
4615 CurDAG->getTargetConstant(Mods ^ SISrcMods::NEG, SDLoc(In), MVT::i32);
4616 return true;
4617}
4618
4619bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16ModsNeg(SDValue In, SDValue &Src,
4620 SDValue &SrcMods) const {
4621 unsigned Mods = 0;
4622 SelectVOP3PMadMixModsImpl(In, Src, Mods, MVT::bf16);
4623 SrcMods =
4624 CurDAG->getTargetConstant(Mods ^ SISrcMods::NEG, SDLoc(In), MVT::i32);
4625 return true;
4626}
4627
4628// Match BITOP3 operation and return a number of matched instructions plus
4629// truth table.
4630static std::pair<unsigned, uint8_t> BitOp3_Op(SDValue In,
4632 unsigned NumOpcodes = 0;
4633 uint8_t LHSBits, RHSBits;
4634
4635 auto getOperandBits = [&Src, In](SDValue Op, uint8_t &Bits) -> bool {
4636 // Define truth table given Src0, Src1, Src2 bits permutations:
4637 // 0 0 0
4638 // 0 0 1
4639 // 0 1 0
4640 // 0 1 1
4641 // 1 0 0
4642 // 1 0 1
4643 // 1 1 0
4644 // 1 1 1
4645 const uint8_t SrcBits[3] = { 0xf0, 0xcc, 0xaa };
4646
4647 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4648 if (C->isAllOnes()) {
4649 Bits = 0xff;
4650 return true;
4651 }
4652 if (C->isZero()) {
4653 Bits = 0;
4654 return true;
4655 }
4656 }
4657
4658 for (unsigned I = 0; I < Src.size(); ++I) {
4659 // Try to find existing reused operand
4660 if (Src[I] == Op) {
4661 Bits = SrcBits[I];
4662 return true;
4663 }
4664 // Try to replace parent operator
4665 if (Src[I] == In) {
4666 Bits = SrcBits[I];
4667 Src[I] = Op;
4668 return true;
4669 }
4670 }
4671
4672 if (Src.size() == 3) {
4673 // No room left for operands. Try one last time, there can be a 'not' of
4674 // one of our source operands. In this case we can compute the bits
4675 // without growing Src vector.
4676 if (Op.getOpcode() == ISD::XOR) {
4677 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4678 if (C->isAllOnes()) {
4679 SDValue LHS = Op.getOperand(0);
4680 for (unsigned I = 0; I < Src.size(); ++I) {
4681 if (Src[I] == LHS) {
4682 Bits = ~SrcBits[I];
4683 return true;
4684 }
4685 }
4686 }
4687 }
4688 }
4689
4690 return false;
4691 }
4692
4693 Bits = SrcBits[Src.size()];
4694 Src.push_back(Op);
4695 return true;
4696 };
4697
4698 switch (In.getOpcode()) {
4699 case ISD::AND:
4700 case ISD::OR:
4701 case ISD::XOR: {
4702 SDValue LHS = In.getOperand(0);
4703 SDValue RHS = In.getOperand(1);
4704
4705 SmallVector<SDValue, 3> Backup(Src.begin(), Src.end());
4706 if (!getOperandBits(LHS, LHSBits) ||
4707 !getOperandBits(RHS, RHSBits)) {
4708 Src = std::move(Backup);
4709 return std::make_pair(0, 0);
4710 }
4711
4712 // Recursion is naturally limited by the size of the operand vector.
4713 //
4714 // When LHS and RHS share a common sub-expression, one side's recursion
4715 // may decompose that sub-expression and replace the Src slot the other
4716 // side occupies with sub-operands via the "replace parent" path in
4717 // getOperandBits. The other side's cached bit-pattern then refers to a
4718 // slot whose contents changed, producing a wrong truth table.
4719 //
4720 // We detect this in three ways:
4721 // (A) If LHS recursed, its truth table is valid against the Src state
4722 // when LHS recursion completed (SrcAfterLHS). If RHS recursion
4723 // then mutates a Src slot that LHSBits depends on, LHSBits is
4724 // stale.
4725 // (B) If RHS did not recurse, RHSBits came from getOperandBits and
4726 // refers to a specific Src slot. If that slot's contents changed
4727 // (by either recursion), RHSBits is stale.
4728 // (C) Symmetrically for LHS if it did not recurse.
4729 SmallVector<SDValue, 3> SrcBeforeRecurse(Src.begin(), Src.end());
4730 uint8_t LHSBitsOrig = LHSBits;
4731 uint8_t RHSBitsOrig = RHSBits;
4732
4733 auto LHSOp = BitOp3_Op(LHS, Src);
4734 if (LHSOp.first) {
4735 NumOpcodes += LHSOp.first;
4736 LHSBits = LHSOp.second;
4737 }
4738
4739 SmallVector<SDValue, 3> SrcAfterLHS(Src.begin(), Src.end());
4740
4741 auto RHSOp = BitOp3_Op(RHS, Src);
4742 if (RHSOp.first) {
4743 NumOpcodes += RHSOp.first;
4744 RHSBits = RHSOp.second;
4745 }
4746
4747 // dependsOnSlot: true iff the truth table TT varies with slot Slot.
4748 auto dependsOnSlot = [](uint8_t TT, int Slot) -> bool {
4749 if (Slot < 0 || Slot > 2)
4750 return false;
4751 const uint8_t Masks[3] = {0x0f, 0x33, 0x55};
4752 const int Shifts[3] = {4, 2, 1};
4753 return ((TT ^ (TT >> Shifts[Slot])) & Masks[Slot]) != 0;
4754 };
4755
4756 // findSlot: locate the Src slot a getOperandBits result depends on,
4757 // including negated (XOR with -1) patterns that getOperandBits
4758 // resolves via the NOT shortcut (~SrcBits[I]).
4759 const uint8_t SrcBitsConst[3] = {0xf0, 0xcc, 0xaa};
4760 auto findSlot = [&](uint8_t Bits, SDValue Op,
4761 const SmallVectorImpl<SDValue> &S) -> int {
4762 SDValue NegatedInner;
4763 bool IsNegationOp =
4764 Op.getOpcode() == ISD::XOR && isAllOnesConstant(Op.getOperand(1));
4765 if (IsNegationOp)
4766 NegatedInner = Op.getOperand(0);
4767 for (int I = 0; I < (int)S.size(); I++) {
4768 if (Bits == SrcBitsConst[I] && S[I] == Op)
4769 return I;
4770 if (IsNegationOp && Bits == (uint8_t)~SrcBitsConst[I] &&
4771 S[I] == NegatedInner)
4772 return I;
4773 }
4774 return -1;
4775 };
4776
4777 bool Stale = false;
4778
4779 // (A) LHS recursed: its truth table is against SrcAfterLHS.
4780 // Check if RHS recursion mutated a slot that LHSBits uses.
4781 if (LHSOp.first) {
4782 for (int I = 0; I < (int)SrcAfterLHS.size() && I < 3; I++) {
4783 if (I < (int)Src.size() && Src[I] != SrcAfterLHS[I] &&
4784 dependsOnSlot(LHSBits, I)) {
4785 Stale = true;
4786 break;
4787 }
4788 }
4789 }
4790
4791 // (B) RHS did not recurse: RHSBits from getOperandBits is against
4792 // SrcBeforeRecurse. Check if that slot was mutated since then.
4793 if (!Stale && !RHSOp.first) {
4794 int Slot = findSlot(RHSBitsOrig, RHS, SrcBeforeRecurse);
4795 if (Slot >= 0 &&
4796 (Slot >= (int)Src.size() || Src[Slot] != SrcBeforeRecurse[Slot]))
4797 Stale = true;
4798 }
4799
4800 // (C) LHS did not recurse: LHSBits from getOperandBits is against
4801 // SrcBeforeRecurse. Check if that slot was mutated since then.
4802 if (!Stale && !LHSOp.first) {
4803 int Slot = findSlot(LHSBitsOrig, LHS, SrcBeforeRecurse);
4804 if (Slot >= 0 &&
4805 (Slot >= (int)Src.size() || Src[Slot] != SrcBeforeRecurse[Slot]))
4806 Stale = true;
4807 }
4808
4809 if (Stale) {
4810 Src = std::move(SrcBeforeRecurse);
4811 LHSBits = LHSBitsOrig;
4812 RHSBits = RHSBitsOrig;
4813 NumOpcodes = 0;
4814 }
4815 break;
4816 }
4817 default:
4818 return std::make_pair(0, 0);
4819 }
4820
4821 uint8_t TTbl;
4822 switch (In.getOpcode()) {
4823 case ISD::AND:
4824 TTbl = LHSBits & RHSBits;
4825 break;
4826 case ISD::OR:
4827 TTbl = LHSBits | RHSBits;
4828 break;
4829 case ISD::XOR:
4830 TTbl = LHSBits ^ RHSBits;
4831 break;
4832 default:
4833 break;
4834 }
4835
4836 return std::make_pair(NumOpcodes + 1, TTbl);
4837}
4838
4839bool AMDGPUDAGToDAGISel::SelectBITOP3(SDValue In, SDValue &Src0, SDValue &Src1,
4840 SDValue &Src2, SDValue &Tbl) const {
4842 uint8_t TTbl;
4843 unsigned NumOpcodes;
4844
4845 std::tie(NumOpcodes, TTbl) = BitOp3_Op(In, Src);
4846
4847 // Src.empty() case can happen if all operands are all zero or all ones.
4848 // Normally it shall be optimized out before reaching this.
4849 if (NumOpcodes < 2 || Src.empty())
4850 return false;
4851
4852 // For a uniform case threshold should be higher to account for moves between
4853 // VGPRs and SGPRs. It needs one operand in a VGPR, rest two can be in SGPRs
4854 // and a readtfirstlane after.
4855 if (NumOpcodes < 4 && !In->isDivergent())
4856 return false;
4857
4858 if (NumOpcodes == 2 && In.getValueType() == MVT::i32) {
4859 // Avoid using BITOP3 for OR3, XOR3, AND_OR. This is not faster but makes
4860 // asm more readable. This cannot be modeled with AddedComplexity because
4861 // selector does not know how many operations did we match.
4862 if ((In.getOpcode() == ISD::XOR || In.getOpcode() == ISD::OR) &&
4863 (In.getOperand(0).getOpcode() == In.getOpcode() ||
4864 In.getOperand(1).getOpcode() == In.getOpcode()))
4865 return false;
4866
4867 if (In.getOpcode() == ISD::OR &&
4868 (In.getOperand(0).getOpcode() == ISD::AND ||
4869 In.getOperand(1).getOpcode() == ISD::AND))
4870 return false;
4871 }
4872
4873 // Last operand can be ignored, turning a ternary operation into a binary.
4874 // For example: (~a & b & c) | (~a & b & ~c) -> (~a & b). We can replace
4875 // 'c' with 'a' here without changing the answer. In some pathological
4876 // cases it should be possible to get an operation with a single operand
4877 // too if optimizer would not catch it.
4878 while (Src.size() < 3)
4879 Src.push_back(Src[0]);
4880
4881 Src0 = Src[0];
4882 Src1 = Src[1];
4883 Src2 = Src[2];
4884
4885 Tbl = CurDAG->getTargetConstant(TTbl, SDLoc(In), MVT::i32);
4886 return true;
4887}
4888
4889SDValue AMDGPUDAGToDAGISel::getHi16Elt(SDValue In) const {
4890 if (In.getOpcode() == ISD::POISON)
4891 return CurDAG->getPOISON(MVT::i32);
4892
4893 if (In.getOpcode() == ISD::UNDEF)
4894 return CurDAG->getUNDEF(MVT::i32);
4895
4896 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(In)) {
4897 SDLoc SL(In);
4898 return CurDAG->getConstant(C->getZExtValue() << 16, SL, MVT::i32);
4899 }
4900
4901 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(In)) {
4902 SDLoc SL(In);
4903 return CurDAG->getConstant(
4904 C->getValueAPF().bitcastToAPInt().getZExtValue() << 16, SL, MVT::i32);
4905 }
4906
4907 SDValue Src;
4908 if (isExtractHiElt(In, Src))
4909 return Src;
4910
4911 return SDValue();
4912}
4913
4914bool AMDGPUDAGToDAGISel::isVGPRImm(const SDNode * N) const {
4915 assert(CurDAG->getTarget().getTargetTriple().isAMDGCN());
4916
4917 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
4918 const SIInstrInfo *SII = Subtarget->getInstrInfo();
4919
4920 unsigned Limit = 0;
4921 bool AllUsesAcceptSReg = true;
4922 for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
4923 Limit < 10 && U != E; ++U, ++Limit) {
4924 const TargetRegisterClass *RC =
4925 getOperandRegClass(U->getUser(), U->getOperandNo());
4926
4927 // If the register class is unknown, it could be an unknown
4928 // register class that needs to be an SGPR, e.g. an inline asm
4929 // constraint
4930 if (!RC || SIRI->isSGPRClass(RC))
4931 return false;
4932
4933 if (RC != &AMDGPU::VS_32RegClass && RC != &AMDGPU::VS_64RegClass &&
4934 RC != &AMDGPU::VS_64_Align2RegClass) {
4935 AllUsesAcceptSReg = false;
4936 SDNode *User = U->getUser();
4937 if (User->isMachineOpcode()) {
4938 unsigned Opc = User->getMachineOpcode();
4939 const MCInstrDesc &Desc = SII->get(Opc);
4940 if (Desc.isCommutable()) {
4941 unsigned OpIdx = Desc.getNumDefs() + U->getOperandNo();
4942 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
4943 if (SII->findCommutedOpIndices(Desc, OpIdx, CommuteIdx1)) {
4944 unsigned CommutedOpNo = CommuteIdx1 - Desc.getNumDefs();
4945 const TargetRegisterClass *CommutedRC =
4946 getOperandRegClass(U->getUser(), CommutedOpNo);
4947 if (CommutedRC == &AMDGPU::VS_32RegClass ||
4948 CommutedRC == &AMDGPU::VS_64RegClass ||
4949 CommutedRC == &AMDGPU::VS_64_Align2RegClass)
4950 AllUsesAcceptSReg = true;
4951 }
4952 }
4953 }
4954 // If "AllUsesAcceptSReg == false" so far we haven't succeeded
4955 // commuting current user. This means have at least one use
4956 // that strictly require VGPR. Thus, we will not attempt to commute
4957 // other user instructions.
4958 if (!AllUsesAcceptSReg)
4959 break;
4960 }
4961 }
4962 return !AllUsesAcceptSReg && (Limit < 10);
4963}
4964
4967 *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
4968 bool IsModified = false;
4969 do {
4970 IsModified = false;
4971
4972 // Go over all selected nodes and try to fold them a bit more
4973 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_begin();
4974 while (Position != CurDAG->allnodes_end()) {
4975 SDNode *Node = &*Position++;
4977 if (!MachineNode)
4978 continue;
4979
4980 SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
4981 if (ResNode != Node) {
4982 if (ResNode)
4983 ReplaceUses(Node, ResNode);
4984 IsModified = true;
4985 }
4986 }
4987 CurDAG->RemoveDeadNodes();
4988 } while (IsModified);
4989}
4990
4992 const SDValue &Op, InlineAsm::ConstraintCode ConstraintID,
4993 std::vector<SDValue> &OutOps) {
4994 switch (ConstraintID) {
4996 OutOps.push_back(Op);
4997 return false;
4999 // flat_load/flat_store require the address in a VGPR. Always force a copy
5000 // to the appropriate VGPR class.
5001 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
5002 MVT VT = Op.getSimpleValueType();
5003 const TargetRegisterClass *VRC =
5004 TRI->getVGPRClassForBitWidth(VT.getSizeInBits());
5005 assert(VRC && "Expected valid VGPR class for RF constraint operand");
5006 SDLoc DL(Op);
5007 SDValue RCVal = CurDAG->getTargetConstant(VRC->getID(), DL, MVT::i32);
5008 SDNode *Copy =
5009 CurDAG->getMachineNode(AMDGPU::COPY_TO_REGCLASS, DL, VT, {Op, RCVal});
5010 OutOps.push_back(SDValue(Copy, 0));
5011 return false;
5012 }
5013 default:
5014 return true;
5015 }
5016}
5017
5022
return SDValue()
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
static bool getBaseWithOffsetUsingSplitOR(SelectionDAG &DAG, SDValue Addr, SDValue &N0, SDValue &N1)
static SDValue SelectSAddrFI(SelectionDAG *CurDAG, SDValue SAddr)
static SDValue matchExtFromI32orI32(SDValue Op, bool IsSigned, const SelectionDAG *DAG)
static MemSDNode * findMemSDNode(SDNode *N)
static bool IsCopyFromSGPR(const SIRegisterInfo &TRI, SDValue Val)
static SDValue combineBallotPattern(SDValue VCMP, bool &Negate)
static SDValue matchBF16FPExtendLike(SDValue Op, bool &IsExtractHigh)
static void checkWMMAElementsModifiersF16(BuildVectorSDNode *BV, std::function< bool(SDValue)> ModifierCheck)
Defines an instruction selector for the AMDGPU target.
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
static bool isNoUnsignedWrap(MachineInstr *Addr)
static bool isExtractHiElt(MachineRegisterInfo &MRI, Register In, Register &Out)
static std::pair< unsigned, uint8_t > BitOp3_Op(Register R, SmallVectorImpl< Register > &Src, const MachineRegisterInfo &MRI)
static unsigned gwsIntrinToOpcode(unsigned IntrID)
Base class for AMDGPU specific classes of TargetSubtarget.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Provides R600 specific target descriptions.
Interface definition for R600RegisterInfo.
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
SI DAG Lowering interface definition.
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
AMDGPUDAGToDAGISelLegacy(TargetMachine &TM, CodeGenOptLevel OptLevel)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
AMDGPU specific code to select AMDGPU machine instructions for SelectionDAG operations.
bool isSDWAOperand(const SDNode *N) const
void SelectBuildVector(SDNode *N, unsigned RegClassID)
void Select(SDNode *N) override
Main hook for targets to transform nodes into machine nodes.
bool widenRegionLoad16(SDNode *N) const
bool runOnMachineFunction(MachineFunction &MF) override
void PreprocessISelDAG() override
PreprocessISelDAG - This hook allows targets to hack on the graph before instruction selection starts...
void PostprocessISelDAG() override
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
bool SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, std::vector< SDValue > &OutOps) override
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
bool matchLoadD16FromBuildVector(SDNode *N) const
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static unsigned getNumIndexableVGPRs(const MachineFunction &MF)
static SDValue stripBitcast(SDValue Val)
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static constexpr const fltSemantics & BFloat()
Definition APFloat.h:303
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI SDValue getSplatValue(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted value or a null value if this is not a splat.
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
int64_t getSExtValue() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
void checkSubtargetFeatures(const Function &F) const
Diagnose inconsistent subtarget features before attempting to codegen function F.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
unsigned getID() const
getID() - Return the register class ID number.
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
Machine Value Type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static MVT getIntegerVT(unsigned BitWidth)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
An SDNode that represents everything that will be needed to construct a MachineInstr.
This is an abstract virtual class for memory operations.
unsigned getAddressSpace() const
Return the address space for the associated pointer.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
bool isPredecessorOf(const SDNode *N) const
Return true if this node is a predecessor of N.
bool isAnyAdd() const
Returns true if the node type is ADD or PTRADD.
static use_iterator use_end()
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
static unsigned getMaxMUBUFImmOffset(const GCNSubtarget &ST)
bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx0, unsigned &SrcOpIdx1) const override
static LLVM_READONLY const TargetRegisterClass * getSGPRClassForBitWidth(unsigned BitWidth)
static unsigned getSubRegFromChannel(uint64_t Channel, uint64_t NumRegs=1)
static bool isSGPRClass(const TargetRegisterClass *RC)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
SelectionDAGISelLegacy(char &ID, std::unique_ptr< SelectionDAGISel > S)
SelectionDAGISelPass(std::unique_ptr< SelectionDAGISel > Selector)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
std::unique_ptr< FunctionLoweringInfo > FuncInfo
const TargetLowering * TLI
const TargetInstrInfo * TII
void ReplaceUses(SDValue F, SDValue T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
void ReplaceNode(SDNode *F, SDNode *T)
Replace all uses of F with T, then remove F from the DAG.
SelectionDAGISel(TargetMachine &tm, CodeGenOptLevel OL=CodeGenOptLevel::Default)
virtual bool runOnMachineFunction(MachineFunction &mf)
const TargetLowering * getTargetLowering() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
MachineFunction & getMachineFunction() const
ilist< SDNode >::iterator allnodes_iterator
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
static const unsigned CommuteAnyOperandIndex
Primary interface to the complete machine description for the target machine.
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS_32BIT
Address space for 32-bit constant memory.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
std::optional< int64_t > getSMRDEncodedLiteralOffset32(const MCSubtargetInfo &ST, int64_t ByteOffset)
bool isGFX12Plus(const MCSubtargetInfo &STI)
constexpr int64_t getNullPointerValue(unsigned AS)
Get the null pointer value for the given address space.
bool isValid32BitLiteral(uint64_t Val, bool IsFP64)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
bool hasSMRDSignedImmOffset(const MCSubtargetInfo &ST)
std::optional< int64_t > getSMRDEncodedOffset(const MCSubtargetInfo &ST, int64_t ByteOffset, bool IsBuffer, bool HasSOffset)
bool isExtendedGlobalAddrSpace(unsigned AS)
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.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ TargetFrameIndex
Definition ISDOpcodes.h:189
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ BRCOND
BRCOND - Conditional branch.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isExtOpcode(unsigned Opcode)
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:256
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Op::Description Desc
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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
bool isBoolSGPR(SDValue V)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
@ Off
Use window algorithm after SMS algorithm fails.
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static bool getConstantValue(SDValue N, uint32_t &Out)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
FunctionPass * createAMDGPUISelDag(TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a AMDGPU-specific.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
unsigned M0(unsigned Val)
Definition VE.h:393
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
Extended Value Type.
Definition ValueTypes.h:35
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:144
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:294
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static unsigned getSubRegFromChannel(unsigned Channel)
bool hasNoUnsignedWrap() const
This represents a list of ValueType's that has been intern'd by a SelectionDAG.