1//===-- NVPTXISelLowering.cpp - NVPTX DAG Lowering Implementation ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that NVPTX uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "NVPTXISelLowering.h"
15#include "MCTargetDesc/NVPTXBaseInfo.h"
16#include "NVPTX.h"
17#include "NVPTXISelDAGToDAG.h"
18#include "NVPTXMachineFunctionInfo.h"
19#include "NVPTXSelectionDAGInfo.h"
20#include "NVPTXSubtarget.h"
21#include "NVPTXTargetMachine.h"
22#include "NVPTXTargetObjectFile.h"
23#include "NVPTXUtilities.h"
24#include "NVVMProperties.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/CodeGen/Analysis.h"
31#include "llvm/CodeGen/ISDOpcodes.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineMemOperand.h"
35#include "llvm/CodeGen/SDPatternMatch.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/CodeGen/SelectionDAGNodes.h"
38#include "llvm/CodeGen/TargetCallingConv.h"
39#include "llvm/CodeGen/TargetLowering.h"
40#include "llvm/CodeGen/ValueTypes.h"
41#include "llvm/CodeGenTypes/MachineValueType.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/DerivedTypes.h"
47#include "llvm/IR/DiagnosticInfo.h"
48#include "llvm/IR/FPEnv.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicsNVPTX.h"
55#include "llvm/IR/Module.h"
56#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
58#include "llvm/Support/Alignment.h"
59#include "llvm/Support/AtomicOrdering.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/CodeGen.h"
62#include "llvm/Support/CommandLine.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/KnownBits.h"
65#include "llvm/Support/NVPTXAddrSpace.h"
66#include "llvm/Support/raw_ostream.h"
67#include "llvm/Target/TargetMachine.h"
68#include "llvm/Target/TargetOptions.h"
69#include <algorithm>
70#include <cassert>
71#include <cmath>
72#include <cstdint>
73#include <iterator>
74#include <optional>
75#include <string>
76#include <tuple>
77#include <utility>
78#include <vector>
79
80#define DEBUG_TYPE "nvptx-lower"
81
82using namespace llvm;
83
84static cl::opt<bool> sched4reg(
85 "nvptx-sched4reg",
86 cl::desc("NVPTX Specific: schedule for register pressue"), cl::init(Val: false));
87
88static cl::opt<unsigned> FMAContractLevelOpt(
89 "nvptx-fma-level", cl::Hidden,
90 cl::desc("NVPTX Specific: FMA contraction (0: don't do it"
91 " 1: do it 2: do it aggressively"),
92 cl::init(Val: 2));
93
94static cl::opt<NVPTX::DivPrecisionLevel> UsePrecDivF32(
95 "nvptx-prec-divf32", cl::Hidden,
96 cl::desc(
97 "NVPTX Specific: Override the precision of the lowering for f32 fdiv"),
98 cl::values(
99 clEnumValN(NVPTX::DivPrecisionLevel::Approx, "0", "Use div.approx"),
100 clEnumValN(NVPTX::DivPrecisionLevel::Full, "1", "Use div.full"),
101 clEnumValN(NVPTX::DivPrecisionLevel::IEEE754, "2",
102 "Use IEEE Compliant F32 div.rnd if available (default)"),
103 clEnumValN(NVPTX::DivPrecisionLevel::IEEE754_NoFTZ, "3",
104 "Use IEEE Compliant F32 div.rnd if available, no FTZ")),
105 cl::init(Val: NVPTX::DivPrecisionLevel::IEEE754));
106
107static cl::opt<bool> UsePrecSqrtF32(
108 "nvptx-prec-sqrtf32", cl::Hidden,
109 cl::desc("NVPTX Specific: 0 use sqrt.approx, 1 use sqrt.rn."),
110 cl::init(Val: true));
111
112// PTX atom.add.f32 has fixed FTZ behavior that may not match the function's
113// (see shouldExpandAtomicRMWInIR), so we'd normally fall back to a CAS loop
114// when they disagree. This option (enabled by default) allows using atom.add
115// anyway, trading correct denormal handling for the speed of the native
116// instruction.
117static cl::opt<bool> AllowFTZAtomics(
118 "nvptx-allow-ftz-atomics", cl::Hidden,
119 cl::desc("NVPTX Specific: Lower atomicrmw fadd to atom.add even when its "
120 "FTZ behavior does not match the function's denormal mode."),
121 cl::init(Val: true));
122
123/// Whereas CUDA's implementation (see libdevice) uses ex2.approx for exp2(), it
124/// does NOT use lg2.approx for log2, so this is disabled by default.
125static cl::opt<bool> UseApproxLog2F32(
126 "nvptx-approx-log2f32",
127 cl::desc("NVPTX Specific: whether to use lg2.approx for log2"),
128 cl::init(Val: false));
129
130NVPTX::DivPrecisionLevel
131NVPTXTargetLowering::getDivF32Level(const MachineFunction &MF,
132 const SDNode &N) const {
133 // If nvptx-prec-div32=N is used on the command-line, always honor it
134 if (UsePrecDivF32.getNumOccurrences() > 0)
135 return UsePrecDivF32;
136
137 const SDNodeFlags Flags = N.getFlags();
138 if (Flags.hasApproximateFuncs())
139 return NVPTX::DivPrecisionLevel::Approx;
140
141 return NVPTX::DivPrecisionLevel::IEEE754;
142}
143
144bool NVPTXTargetLowering::usePrecSqrtF32(const SDNode *N) const {
145 // If nvptx-prec-sqrtf32 is used on the command-line, always honor it
146 if (UsePrecSqrtF32.getNumOccurrences() > 0)
147 return UsePrecSqrtF32;
148
149 if (N) {
150 const SDNodeFlags Flags = N->getFlags();
151 if (Flags.hasApproximateFuncs())
152 return false;
153 }
154
155 return true;
156}
157
158bool NVPTXTargetLowering::useF32FTZ(const MachineFunction &MF) const {
159 return MF.getDenormalMode(FPType: APFloat::IEEEsingle()).Output ==
160 DenormalMode::PreserveSign;
161}
162
163static bool IsPTXVectorType(MVT VT) {
164 switch (VT.SimpleTy) {
165 default:
166 return false;
167 case MVT::v2i1:
168 case MVT::v4i1:
169 case MVT::v2i8:
170 case MVT::v4i8:
171 case MVT::v8i8: // <2 x i8x4>
172 case MVT::v16i8: // <4 x i8x4>
173 case MVT::v2i16:
174 case MVT::v4i16:
175 case MVT::v8i16: // <4 x i16x2>
176 case MVT::v2i32:
177 case MVT::v4i32:
178 case MVT::v2i64:
179 case MVT::v2f16:
180 case MVT::v4f16:
181 case MVT::v8f16: // <4 x f16x2>
182 case MVT::v2bf16:
183 case MVT::v4bf16:
184 case MVT::v8bf16: // <4 x bf16x2>
185 case MVT::v2f32:
186 case MVT::v4f32:
187 case MVT::v2f64:
188 case MVT::v4i64:
189 case MVT::v4f64:
190 case MVT::v8i32:
191 case MVT::v8f32:
192 case MVT::v16f16: // <8 x f16x2>
193 case MVT::v16bf16: // <8 x bf16x2>
194 case MVT::v16i16: // <8 x i16x2>
195 case MVT::v32i8: // <8 x i8x4>
196 return true;
197 }
198}
199
200// When legalizing vector loads/stores, this function is called, which does two
201// things:
202// 1. Determines Whether the vector is something we want to custom lower,
203// std::nullopt is returned if we do not want to custom lower it.
204// 2. If we do want to handle it, returns two parameters:
205// - unsigned int NumElts - The number of elements in the final vector
206// - EVT EltVT - The type of the elements in the final vector
207static std::optional<std::pair<unsigned int, MVT>>
208getVectorLoweringShape(EVT VectorEVT, const NVPTXSubtarget &STI,
209 unsigned AddressSpace) {
210 const bool CanLowerTo256Bit = STI.has256BitVectorLoadStore(AS: AddressSpace);
211
212 if (CanLowerTo256Bit && VectorEVT.isScalarInteger() &&
213 VectorEVT.getSizeInBits() == 256)
214 return {{4, MVT::i64}};
215
216 if (!VectorEVT.isSimple())
217 return std::nullopt;
218 const MVT VectorVT = VectorEVT.getSimpleVT();
219
220 if (!VectorVT.isVector()) {
221 if (VectorVT == MVT::i128 || VectorVT == MVT::f128)
222 return {{2, MVT::i64}};
223 return std::nullopt;
224 }
225
226 const MVT EltVT = VectorVT.getVectorElementType();
227 const unsigned NumElts = VectorVT.getVectorNumElements();
228
229 // The size of the PTX virtual register that holds a packed type.
230 unsigned PackRegSize;
231
232 // We only handle "native" vector sizes for now, e.g. <4 x double> is not
233 // legal. We can (and should) split that into 2 stores of <2 x double> here
234 // but I'm leaving that as a TODO for now.
235 switch (VectorVT.SimpleTy) {
236 default:
237 return std::nullopt;
238
239 case MVT::v4i64:
240 case MVT::v4f64:
241 // This is a "native" vector type iff the address space is global and the
242 // target supports 256-bit loads/stores
243 if (!CanLowerTo256Bit)
244 return std::nullopt;
245 [[fallthrough]];
246 case MVT::v2i8:
247 case MVT::v2i64:
248 case MVT::v2f64:
249 // This is a "native" vector type
250 return std::pair(NumElts, EltVT);
251
252 case MVT::v16f16: // <8 x f16x2>
253 case MVT::v16bf16: // <8 x bf16x2>
254 case MVT::v16i16: // <8 x i16x2>
255 case MVT::v32i8: // <8 x i8x4>
256 // This can be upsized into a "native" vector type iff the address space is
257 // global and the target supports 256-bit loads/stores.
258 if (!CanLowerTo256Bit)
259 return std::nullopt;
260 [[fallthrough]];
261 case MVT::v2i16: // <1 x i16x2>
262 case MVT::v2f16: // <1 x f16x2>
263 case MVT::v2bf16: // <1 x bf16x2>
264 case MVT::v4i8: // <1 x i8x4>
265 case MVT::v4i16: // <2 x i16x2>
266 case MVT::v4f16: // <2 x f16x2>
267 case MVT::v4bf16: // <2 x bf16x2>
268 case MVT::v8i8: // <2 x i8x4>
269 case MVT::v8f16: // <4 x f16x2>
270 case MVT::v8bf16: // <4 x bf16x2>
271 case MVT::v8i16: // <4 x i16x2>
272 case MVT::v16i8: // <4 x i8x4>
273 PackRegSize = 32;
274 break;
275
276 case MVT::v8f32: // <4 x f32x2>
277 case MVT::v8i32: // <4 x i32x2>
278 // This is a "native" vector type iff the address space is global and the
279 // target supports 256-bit loads/stores
280 if (!CanLowerTo256Bit)
281 return std::nullopt;
282 [[fallthrough]];
283 case MVT::v2f32: // <1 x f32x2>
284 case MVT::v4f32: // <2 x f32x2>
285 case MVT::v2i32: // <1 x i32x2>
286 case MVT::v4i32: // <2 x i32x2>
287 if (!STI.hasF32x2Instructions())
288 return std::pair(NumElts, EltVT);
289 PackRegSize = 64;
290 break;
291 }
292
293 // If we reach here, then we can pack 2 or more elements into a single 32-bit
294 // or 64-bit PTX register and treat the vector as a new vector containing
295 // packed elements.
296
297 // Number of elements to pack in one word.
298 const unsigned NPerReg = PackRegSize / EltVT.getSizeInBits();
299
300 return std::pair(NumElts / NPerReg, MVT::getVectorVT(VT: EltVT, NumElements: NPerReg));
301}
302
303/// ComputePTXValueVTs - For the given Type \p Ty, returns the set of primitive
304/// legal-ish MVTs that compose it. Unlike ComputeValueVTs, this will legalize
305/// the types as required by the calling convention (with special handling for
306/// i8s).
307/// NOTE: This is a band-aid for code that expects ComputeValueVTs to return the
308/// same number of types as the Ins/Outs arrays in LowerFormalArguments,
309/// LowerCall, and LowerReturn.
310static void ComputePTXValueVTs(const TargetLowering &TLI, const DataLayout &DL,
311 LLVMContext &Ctx, CallingConv::ID CallConv,
312 Type *Ty, SmallVectorImpl<EVT> &ValueVTs,
313 SmallVectorImpl<uint64_t> &Offsets,
314 uint64_t StartingOffset = 0) {
315 SmallVector<EVT, 16> TempVTs;
316 SmallVector<uint64_t, 16> TempOffsets;
317 ComputeValueVTs(TLI, DL, Ty, ValueVTs&: TempVTs, /*MemVTs=*/nullptr, FixedOffsets: &TempOffsets,
318 StartingOffset);
319
320 for (const auto [VT, Off] : zip(t&: TempVTs, u&: TempOffsets)) {
321 MVT RegisterVT = TLI.getRegisterTypeForCallingConv(Context&: Ctx, CC: CallConv, VT);
322 unsigned NumRegs = TLI.getNumRegistersForCallingConv(Context&: Ctx, CC: CallConv, VT);
323
324 // Since we actually can load/store b8, we need to ensure that we'll use
325 // the original sized type for any i8s or i8 vectors.
326 if (VT.getScalarType() == MVT::i8) {
327 if (RegisterVT == MVT::i16)
328 RegisterVT = MVT::i8;
329 else if (RegisterVT == MVT::v2i16)
330 RegisterVT = MVT::v2i8;
331 else
332 assert(RegisterVT == MVT::v4i8 &&
333 "Expected v4i8, v2i16, or i16 for i8 RegisterVT");
334 }
335
336 // TODO: This is horribly incorrect for cases where the vector elements are
337 // not a multiple of bytes (ex i1) and legal or i8. However, this problem
338 // has existed for as long as NVPTX has and no one has complained, so we'll
339 // leave it for now.
340 for (unsigned I : seq(Size: NumRegs)) {
341 ValueVTs.push_back(Elt: RegisterVT);
342 Offsets.push_back(Elt: Off + I * RegisterVT.getStoreSize());
343 }
344 }
345}
346
347// We return an EVT that can hold N VTs
348// If the VT is a vector, the resulting EVT is a flat vector with the same
349// element type as VT's element type.
350static EVT getVectorizedVT(EVT VT, unsigned N, LLVMContext &C) {
351 if (N == 1)
352 return VT;
353
354 return VT.isVector() ? EVT::getVectorVT(Context&: C, VT: VT.getScalarType(),
355 NumElements: VT.getVectorNumElements() * N)
356 : EVT::getVectorVT(Context&: C, VT, NumElements: N);
357}
358
359static SDValue getExtractVectorizedValue(SDValue V, unsigned I, EVT VT,
360 const SDLoc &dl, SelectionDAG &DAG) {
361 if (V.getValueType() == VT) {
362 assert(I == 0 && "Index must be 0 for scalar value");
363 return V;
364 }
365
366 if (!VT.isVector())
367 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT, N1: V,
368 N2: DAG.getVectorIdxConstant(Val: I, DL: dl));
369
370 return DAG.getNode(
371 Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT, N1: V,
372 N2: DAG.getVectorIdxConstant(Val: I * VT.getVectorNumElements(), DL: dl));
373}
374
375template <typename T>
376static inline SDValue getBuildVectorizedValue(unsigned N, const SDLoc &dl,
377 SelectionDAG &DAG, T GetElement) {
378 if (N == 1)
379 return GetElement(0);
380
381 SmallVector<SDValue, 8> Values;
382 for (const unsigned I : llvm::seq(Size: N)) {
383 SDValue Val = GetElement(I);
384 if (Val.getValueType().isVector())
385 DAG.ExtractVectorElements(Op: Val, Args&: Values);
386 else
387 Values.push_back(Elt: Val);
388 }
389
390 EVT VT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: Values[0].getValueType(),
391 NumElements: Values.size());
392 return DAG.getBuildVector(VT, DL: dl, Ops: Values);
393}
394
395/// PromoteScalarIntegerPTX
396/// Used to make sure the arguments/returns are suitable for passing
397/// and promote them to a larger size if they're not.
398///
399/// The promoted type is placed in \p PromoteVT if the function returns true.
400static EVT promoteScalarIntegerPTX(const EVT VT) {
401 if (VT.isScalarInteger()) {
402 switch (PowerOf2Ceil(A: VT.getFixedSizeInBits())) {
403 default:
404 llvm_unreachable(
405 "Promotion is not suitable for scalars of size larger than 64-bits");
406 case 1:
407 return MVT::i1;
408 case 2:
409 case 4:
410 case 8:
411 return MVT::i8;
412 case 16:
413 return MVT::i16;
414 case 32:
415 return MVT::i32;
416 case 64:
417 return MVT::i64;
418 }
419 }
420 return VT;
421}
422
423// Check whether we can merge loads/stores of some of the pieces of a
424// flattened function parameter or return value into a single vector
425// load/store.
426//
427// The flattened parameter is represented as a list of EVTs and
428// offsets, and the whole structure is aligned to ParamAlignment. This
429// function determines whether we can load/store pieces of the
430// parameter starting at index Idx using a single vectorized op of
431// size AccessSize. If so, it returns the number of param pieces
432// covered by the vector op. Otherwise, it returns 1.
433template <typename T>
434static unsigned canMergeParamLoadStoresStartingAt(
435 unsigned Idx, uint32_t AccessSize, const SmallVectorImpl<EVT> &ValueVTs,
436 const SmallVectorImpl<T> &Offsets, Align ParamAlignment) {
437
438 // Can't vectorize if param alignment is not sufficient.
439 if (ParamAlignment < AccessSize)
440 return 1;
441 // Can't vectorize if offset is not aligned.
442 if (Offsets[Idx] & (AccessSize - 1))
443 return 1;
444
445 EVT EltVT = ValueVTs[Idx];
446 unsigned EltSize = EltVT.getStoreSize();
447
448 // Element is too large to vectorize.
449 if (EltSize >= AccessSize)
450 return 1;
451
452 unsigned NumElts = AccessSize / EltSize;
453 // Can't vectorize if AccessBytes if not a multiple of EltSize.
454 if (AccessSize != EltSize * NumElts)
455 return 1;
456
457 // We don't have enough elements to vectorize.
458 if (Idx + NumElts > ValueVTs.size())
459 return 1;
460
461 // PTX ISA can only deal with 2- and 4-element vector ops.
462 if (NumElts != 4 && NumElts != 2)
463 return 1;
464
465 for (unsigned j = Idx + 1; j < Idx + NumElts; ++j) {
466 // Types do not match.
467 if (ValueVTs[j] != EltVT)
468 return 1;
469
470 // Elements are not contiguous.
471 if (Offsets[j] - Offsets[j - 1] != EltSize)
472 return 1;
473 }
474 // OK. We can vectorize ValueVTs[i..i+NumElts)
475 return NumElts;
476}
477
478// Computes whether and how we can vectorize the loads/stores of a
479// flattened function parameter or return value.
480//
481// The flattened parameter is represented as the list of ValueVTs and
482// Offsets, and is aligned to ParamAlignment bytes. We return a vector
483// of the same size as ValueVTs indicating how each piece should be
484// loaded/stored (i.e. as a scalar, or as part of a vector
485// load/store).
486template <typename T>
487static SmallVector<unsigned, 16>
488VectorizePTXValueVTs(const SmallVectorImpl<EVT> &ValueVTs,
489 const SmallVectorImpl<T> &Offsets, Align ParamAlignment,
490 bool IsVAArg = false) {
491 // Set vector size to match ValueVTs and mark all elements as
492 // scalars by default.
493
494 if (IsVAArg)
495 return SmallVector<unsigned>(ValueVTs.size(), 1);
496
497 SmallVector<unsigned, 16> VectorInfo;
498
499 const auto GetNumElts = [&](unsigned I) -> unsigned {
500 for (const unsigned AccessSize : {16, 8, 4, 2}) {
501 const unsigned NumElts = canMergeParamLoadStoresStartingAt(
502 I, AccessSize, ValueVTs, Offsets, ParamAlignment);
503 assert((NumElts == 1 || NumElts == 2 || NumElts == 4) &&
504 "Unexpected vectorization size");
505 if (NumElts != 1)
506 return NumElts;
507 }
508 return 1;
509 };
510
511 // Check what we can vectorize using 128/64/32-bit accesses.
512 for (unsigned I = 0, E = ValueVTs.size(); I != E;) {
513 const unsigned NumElts = GetNumElts(I);
514 VectorInfo.push_back(Elt: NumElts);
515 I += NumElts;
516 }
517 assert(std::accumulate(VectorInfo.begin(), VectorInfo.end(), 0u) ==
518 ValueVTs.size());
519 return VectorInfo;
520}
521
522// NVPTXTargetLowering Constructor.
523NVPTXTargetLowering::NVPTXTargetLowering(const NVPTXTargetMachine &TM,
524 const NVPTXSubtarget &STI)
525 : TargetLowering(TM, STI), nvTM(&TM), STI(STI), GlobalUniqueCallSite(0) {
526 // always lower memset, memcpy, and memmove intrinsics to load/store
527 // instructions, rather
528 // then generating calls to memset, mempcy or memmove.
529 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = (unsigned)0xFFFFFFFF;
530 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = (unsigned) 0xFFFFFFFF;
531 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = (unsigned) 0xFFFFFFFF;
532
533 setBooleanContents(ZeroOrNegativeOneBooleanContent);
534 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
535
536 // Jump is Expensive. Don't create extra control flow for 'and', 'or'
537 // condition branches.
538 setJumpIsExpensive(true);
539
540 // Wide divides are _very_ slow. Try to reduce the width of the divide if
541 // possible.
542 addBypassSlowDiv(SlowBitWidth: 64, FastBitWidth: 32);
543
544 // By default, use the Source scheduling
545 if (sched4reg)
546 setSchedulingPreference(Sched::RegPressure);
547 else
548 setSchedulingPreference(Sched::Source);
549
550 auto setFP16OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
551 LegalizeAction NoF16Action) {
552 bool IsOpSupported = STI.allowFP16Math();
553 switch (Op) {
554 // Several FP16 instructions are available on sm_80 only.
555 case ISD::FMINNUM:
556 case ISD::FMAXNUM:
557 case ISD::FMAXNUM_IEEE:
558 case ISD::FMINNUM_IEEE:
559 case ISD::FMAXIMUM:
560 case ISD::FMINIMUM:
561 case ISD::FMAXIMUMNUM:
562 case ISD::FMINIMUMNUM:
563 IsOpSupported &= STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 70;
564 break;
565 case ISD::FEXP2:
566 case ISD::FTANH:
567 IsOpSupported &= STI.getSmVersion() >= 75 && STI.getPTXVersion() >= 70;
568 break;
569 }
570 setOperationAction(Op, VT, Action: IsOpSupported ? Action : NoF16Action);
571 };
572
573 auto setBF16OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
574 LegalizeAction NoBF16Action) {
575 bool IsOpSupported = STI.hasNativeBF16Support(Opcode: Op);
576 setOperationAction(
577 Op, VT, Action: IsOpSupported ? Action : NoBF16Action);
578 };
579
580 auto setI16x2OperationAction = [&](unsigned Op, MVT VT, LegalizeAction Action,
581 LegalizeAction NoI16x2Action) {
582 bool IsOpSupported = false;
583 // instructions are available on sm_90 only
584 switch (Op) {
585 case ISD::ADD:
586 case ISD::SMAX:
587 case ISD::SMIN:
588 case ISD::UMIN:
589 case ISD::UMAX:
590 IsOpSupported = STI.getSmVersion() >= 90 && STI.getPTXVersion() >= 80;
591 break;
592 }
593 setOperationAction(Op, VT, Action: IsOpSupported ? Action : NoI16x2Action);
594 };
595
596 addRegisterClass(VT: MVT::i1, RC: &NVPTX::B1RegClass);
597 addRegisterClass(VT: MVT::i16, RC: &NVPTX::B16RegClass);
598 addRegisterClass(VT: MVT::v2i16, RC: &NVPTX::B32RegClass);
599 addRegisterClass(VT: MVT::v4i8, RC: &NVPTX::B32RegClass);
600 addRegisterClass(VT: MVT::i32, RC: &NVPTX::B32RegClass);
601 addRegisterClass(VT: MVT::i64, RC: &NVPTX::B64RegClass);
602 addRegisterClass(VT: MVT::f32, RC: &NVPTX::B32RegClass);
603 addRegisterClass(VT: MVT::f64, RC: &NVPTX::B64RegClass);
604 addRegisterClass(VT: MVT::f16, RC: &NVPTX::B16RegClass);
605 addRegisterClass(VT: MVT::v2f16, RC: &NVPTX::B32RegClass);
606 addRegisterClass(VT: MVT::bf16, RC: &NVPTX::B16RegClass);
607 addRegisterClass(VT: MVT::v2bf16, RC: &NVPTX::B32RegClass);
608
609 if (STI.hasF32x2Instructions()) {
610 addRegisterClass(VT: MVT::v2f32, RC: &NVPTX::B64RegClass);
611 addRegisterClass(VT: MVT::v2i32, RC: &NVPTX::B64RegClass);
612 }
613
614 // Conversion to/from FP16/FP16x2 is always legal.
615 setOperationAction(Op: ISD::BUILD_VECTOR, VT: MVT::v2f16, Action: Custom);
616 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT: MVT::v2f16, Action: Custom);
617 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT: MVT::v2f16, Action: Expand);
618 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT: MVT::v2f16, Action: Expand);
619
620 setOperationAction(Op: ISD::READCYCLECOUNTER, VT: MVT::i64, Action: Legal);
621 if (STI.getSmVersion() >= 30 && STI.getPTXVersion() > 31)
622 setOperationAction(Op: ISD::READSTEADYCOUNTER, VT: MVT::i64, Action: Legal);
623
624 setFP16OperationAction(ISD::SETCC, MVT::f16, Legal, Promote);
625 setFP16OperationAction(ISD::SETCC, MVT::v2f16, Legal, Expand);
626
627 // Conversion to/from BFP16/BFP16x2 is always legal.
628 setOperationAction(Op: ISD::BUILD_VECTOR, VT: MVT::v2bf16, Action: Custom);
629 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT: MVT::v2bf16, Action: Custom);
630 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT: MVT::v2bf16, Action: Expand);
631 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT: MVT::v2bf16, Action: Expand);
632
633 setBF16OperationAction(ISD::SETCC, MVT::v2bf16, Legal, Expand);
634 setBF16OperationAction(ISD::SETCC, MVT::bf16, Legal, Promote);
635 if (getOperationAction(Op: ISD::SETCC, VT: MVT::bf16) == Promote)
636 AddPromotedToType(Opc: ISD::SETCC, OrigVT: MVT::bf16, DestVT: MVT::f32);
637
638 // Conversion to/from i16/i16x2 is always legal.
639 setOperationAction(Op: ISD::BUILD_VECTOR, VT: MVT::v2i16, Action: Custom);
640 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT: MVT::v2i16, Action: Custom);
641 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT: MVT::v2i16, Action: Expand);
642 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT: MVT::v2i16, Action: Expand);
643
644 setOperationAction(Op: ISD::BUILD_VECTOR, VT: MVT::v4i8, Action: Custom);
645 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT: MVT::v4i8, Action: Custom);
646 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT: MVT::v4i8, Action: Custom);
647 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT: MVT::v4i8, Action: Custom);
648
649 // No support for these operations with v2f32/v2i32
650 setOperationAction(Ops: ISD::INSERT_VECTOR_ELT, VTs: {MVT::v2f32, MVT::v2i32}, Action: Expand);
651 setOperationAction(Ops: ISD::VECTOR_SHUFFLE, VTs: {MVT::v2f32, MVT::v2i32}, Action: Expand);
652
653 setOperationAction(Op: ISD::TRUNCATE, VT: MVT::v2i16, Action: Expand);
654 setOperationAction(Ops: {ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
655 VT: MVT::v2i32, Action: Expand);
656
657 // Need custom lowering in case the index is dynamic.
658 if (STI.hasF32x2Instructions())
659 setOperationAction(Ops: ISD::EXTRACT_VECTOR_ELT, VTs: {MVT::v2f32, MVT::v2i32},
660 Action: Custom);
661
662 // Custom conversions to/from v2i8.
663 setOperationAction(Op: ISD::BITCAST, VT: MVT::v2i8, Action: Custom);
664
665 // Only logical ops can be done on v4i8/v2i32 directly, others must be done
666 // elementwise.
667 setOperationAction(
668 Ops: {ISD::ABS, ISD::ADD, ISD::ADDC, ISD::ADDE,
669 ISD::BITREVERSE, ISD::CTLZ, ISD::CTPOP, ISD::CTTZ,
670 ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::FSHL, ISD::FSHR,
671 ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::PARITY,
672 ISD::ROTL, ISD::ROTR, ISD::SADDO, ISD::SADDO_CARRY,
673 ISD::SADDSAT, ISD::SDIV, ISD::SDIVREM, ISD::SELECT_CC,
674 ISD::SETCC, ISD::SHL, ISD::SINT_TO_FP, ISD::SMAX,
675 ISD::SMIN, ISD::SMULO, ISD::SMUL_LOHI, ISD::SRA,
676 ISD::SREM, ISD::SRL, ISD::SSHLSAT, ISD::SSUBO,
677 ISD::SSUBO_CARRY, ISD::SSUBSAT, ISD::SUB, ISD::SUBC,
678 ISD::SUBE, ISD::UADDO, ISD::UADDO_CARRY, ISD::UADDSAT,
679 ISD::UDIV, ISD::UDIVREM, ISD::UINT_TO_FP, ISD::UMAX,
680 ISD::UMIN, ISD::UMULO, ISD::UMUL_LOHI, ISD::UREM,
681 ISD::USHLSAT, ISD::USUBO, ISD::USUBO_CARRY, ISD::VSELECT,
682 ISD::USUBSAT},
683 VTs: {MVT::v4i8, MVT::v2i32}, Action: Expand);
684
685 // Operations not directly supported by NVPTX.
686 for (MVT VT : {MVT::bf16, MVT::f16, MVT::v2bf16, MVT::v2f16, MVT::f32,
687 MVT::v2f32, MVT::f64, MVT::i1, MVT::i8, MVT::i16, MVT::v2i16,
688 MVT::v4i8, MVT::i32, MVT::v2i32, MVT::i64}) {
689 setOperationAction(Op: ISD::SELECT_CC, VT, Action: Expand);
690 setOperationAction(Op: ISD::BR_CC, VT, Action: Expand);
691 }
692
693 // We don't want ops like FMINIMUM or UMAX to be lowered to SETCC+VSELECT.
694 setOperationAction(Ops: ISD::VSELECT, VTs: {MVT::v2f32, MVT::v2i32}, Action: Expand);
695
696 // Some SIGN_EXTEND_INREG can be done using cvt instruction.
697 // For others we will expand to a SHL/SRA pair.
698 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i64, Action: Legal);
699 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i32, Action: Legal);
700 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i16, Action: Legal);
701 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i8 , Action: Legal);
702 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i1, Action: Expand);
703 setOperationAction(Ops: ISD::SIGN_EXTEND_INREG, VTs: {MVT::v2i16, MVT::v2i32}, Action: Expand);
704
705 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i32 , Action: Custom);
706 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i32 , Action: Custom);
707 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i32 , Action: Custom);
708 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i64 , Action: Custom);
709 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i64 , Action: Custom);
710 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i64 , Action: Custom);
711
712 setOperationAction(Op: ISD::BITREVERSE, VT: MVT::i32, Action: Legal);
713 setOperationAction(Op: ISD::BITREVERSE, VT: MVT::i64, Action: Legal);
714
715 setOperationAction(Ops: {ISD::ROTL, ISD::ROTR},
716 VTs: {MVT::i8, MVT::i16, MVT::v2i16, MVT::i32, MVT::i64},
717 Action: Expand);
718
719 if (STI.hasHWROT32()) {
720 setOperationAction(Ops: {ISD::FSHL, ISD::FSHR}, VT: MVT::i32, Action: Legal);
721 setOperationAction(Ops: {ISD::ROTL, ISD::ROTR, ISD::FSHL, ISD::FSHR}, VT: MVT::i64,
722 Action: Custom);
723 }
724
725 setOperationAction(Op: ISD::BR_JT, VT: MVT::Other, Action: STI.hasBrx() ? Legal : Expand);
726 setOperationAction(Op: ISD::BRIND, VT: MVT::Other, Action: Expand);
727
728 // We want to legalize constant related memmove and memcopy
729 // intrinsics.
730 setOperationAction(Op: ISD::INTRINSIC_W_CHAIN, VT: MVT::Other, Action: Custom);
731
732 // FP extload/truncstore is not legal in PTX. We need to expand all these.
733 for (auto FloatVTs :
734 {MVT::fp_valuetypes(), MVT::fp_fixedlen_vector_valuetypes()}) {
735 for (MVT ValVT : FloatVTs) {
736 for (MVT MemVT : FloatVTs) {
737 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT, MemVT, Action: Expand);
738 setTruncStoreAction(ValVT, MemVT, Action: Expand);
739 }
740 }
741 }
742
743 // To improve CodeGen we'll legalize any-extend loads to zext loads. This is
744 // how they'll be lowered in ISel anyway, and by doing this a little earlier
745 // we allow for more DAG combine opportunities.
746 for (auto IntVTs :
747 {MVT::integer_valuetypes(), MVT::integer_fixedlen_vector_valuetypes()})
748 for (MVT ValVT : IntVTs)
749 for (MVT MemVT : IntVTs)
750 if (isTypeLegal(VT: ValVT))
751 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT, MemVT, Action: Custom);
752
753 // PTX does not support load / store predicate registers
754 setOperationAction(Ops: {ISD::LOAD, ISD::STORE}, VT: MVT::i1, Action: Custom);
755 for (MVT VT : MVT::integer_valuetypes()) {
756 setLoadExtAction(ExtTypes: {ISD::SEXTLOAD, ISD::ZEXTLOAD, ISD::EXTLOAD}, ValVT: VT, MemVT: MVT::i1,
757 Action: Promote);
758 setTruncStoreAction(ValVT: VT, MemVT: MVT::i1, Action: Expand);
759 }
760
761 // Disable generations of extload/truncstore for v2i32/v2i16/v2i8. The generic
762 // expansion for these nodes when they are unaligned is incorrect if the
763 // type is a vector.
764 //
765 // TODO: Fix the generic expansion for these nodes found in
766 // TargetLowering::expandUnalignedLoad/Store.
767 setLoadExtAction(ExtTypes: {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT: MVT::v2i16,
768 MemVT: MVT::v2i8, Action: Expand);
769 setLoadExtAction(ExtTypes: {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT: MVT::v2i32,
770 MemVTs: {MVT::v2i8, MVT::v2i16}, Action: Expand);
771 setTruncStoreAction(ValVT: MVT::v2i16, MemVT: MVT::v2i8, Action: Expand);
772 setTruncStoreAction(ValVT: MVT::v2i32, MemVT: MVT::v2i16, Action: Expand);
773 setTruncStoreAction(ValVT: MVT::v2i32, MemVT: MVT::v2i8, Action: Expand);
774
775 // Register custom handling for illegal type loads/stores. We'll try to custom
776 // lower almost all illegal types and logic in the lowering will discard cases
777 // we can't handle.
778 setOperationAction(Ops: {ISD::LOAD, ISD::STORE}, VTs: {MVT::i128, MVT::i256, MVT::f128},
779 Action: Custom);
780 for (MVT VT : MVT::fixedlen_vector_valuetypes())
781 if (!isTypeLegal(VT) && VT.getStoreSizeInBits() <= 256)
782 setOperationAction(Ops: {ISD::STORE, ISD::LOAD, ISD::MSTORE, ISD::MLOAD}, VT,
783 Action: Custom);
784
785 // Custom legalization for LDU intrinsics.
786 // TODO: The logic to lower these is not very robust and we should rewrite it.
787 // Perhaps LDU should not be represented as an intrinsic at all.
788 setOperationAction(Op: ISD::INTRINSIC_W_CHAIN, VT: MVT::i8, Action: Custom);
789 for (MVT VT : MVT::fixedlen_vector_valuetypes())
790 if (IsPTXVectorType(VT))
791 setOperationAction(Op: ISD::INTRINSIC_W_CHAIN, VT, Action: Custom);
792
793 setCondCodeAction(CCs: {ISD::SETNE, ISD::SETEQ, ISD::SETUGE, ISD::SETULE,
794 ISD::SETUGT, ISD::SETULT, ISD::SETGT, ISD::SETLT,
795 ISD::SETGE, ISD::SETLE},
796 VT: MVT::i1, Action: Expand);
797
798 // This is legal in NVPTX
799 setOperationAction(Op: ISD::ConstantFP, VT: MVT::f64, Action: Legal);
800 setOperationAction(Op: ISD::ConstantFP, VT: MVT::f32, Action: Legal);
801 setOperationAction(Op: ISD::ConstantFP, VT: MVT::f16, Action: Legal);
802 setOperationAction(Op: ISD::ConstantFP, VT: MVT::bf16, Action: Legal);
803
804 setOperationAction(Ops: ISD::DYNAMIC_STACKALLOC, VTs: {MVT::i32, MVT::i64}, Action: Custom);
805 setOperationAction(Ops: {ISD::STACKRESTORE, ISD::STACKSAVE}, VT: MVT::Other, Action: Custom);
806
807 // TRAP can be lowered to PTX trap
808 setOperationAction(Op: ISD::TRAP, VT: MVT::Other, Action: Legal);
809 // DEBUGTRAP can be lowered to PTX brkpt
810 setOperationAction(Op: ISD::DEBUGTRAP, VT: MVT::Other, Action: Legal);
811
812 // Support varargs.
813 setOperationAction(Op: ISD::VASTART, VT: MVT::Other, Action: Custom);
814 setOperationAction(Op: ISD::VAARG, VT: MVT::Other, Action: Custom);
815 setOperationAction(Op: ISD::VACOPY, VT: MVT::Other, Action: Expand);
816 setOperationAction(Op: ISD::VAEND, VT: MVT::Other, Action: Expand);
817
818 setOperationAction(Ops: {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX},
819 VTs: {MVT::i16, MVT::i32, MVT::i64}, Action: Legal);
820 // PTX abs.s is undefined for INT_MIN, so ISD::ABS (which requires
821 // abs(INT_MIN) == INT_MIN) must be expanded. ABS_MIN_POISON matches
822 // PTX abs semantics since INT_MIN input is poison/undefined.
823 setOperationAction(Ops: ISD::ABS, VTs: {MVT::i16, MVT::i32, MVT::i64}, Action: Expand);
824 setOperationAction(Ops: ISD::ABS_MIN_POISON, VTs: {MVT::i16, MVT::i32, MVT::i64},
825 Action: Legal);
826
827 setOperationAction(Ops: {ISD::CTPOP, ISD::CTLZ, ISD::CTLZ_ZERO_POISON}, VT: MVT::i16,
828 Action: Promote);
829 setOperationAction(Ops: {ISD::CTPOP, ISD::CTLZ}, VT: MVT::i32, Action: Legal);
830 setOperationAction(Ops: {ISD::CTPOP, ISD::CTLZ}, VT: MVT::i64, Action: Custom);
831
832 setI16x2OperationAction(ISD::ABS_MIN_POISON, MVT::v2i16, Legal, Custom);
833 setI16x2OperationAction(ISD::SMIN, MVT::v2i16, Legal, Custom);
834 setI16x2OperationAction(ISD::SMAX, MVT::v2i16, Legal, Custom);
835 setI16x2OperationAction(ISD::UMIN, MVT::v2i16, Legal, Custom);
836 setI16x2OperationAction(ISD::UMAX, MVT::v2i16, Legal, Custom);
837 setI16x2OperationAction(ISD::CTPOP, MVT::v2i16, Legal, Expand);
838 setI16x2OperationAction(ISD::CTLZ, MVT::v2i16, Legal, Expand);
839
840 setI16x2OperationAction(ISD::ADD, MVT::v2i16, Legal, Custom);
841 setI16x2OperationAction(ISD::SUB, MVT::v2i16, Legal, Custom);
842 setI16x2OperationAction(ISD::MUL, MVT::v2i16, Legal, Custom);
843 setI16x2OperationAction(ISD::SHL, MVT::v2i16, Legal, Custom);
844 setI16x2OperationAction(ISD::SREM, MVT::v2i16, Legal, Custom);
845 setI16x2OperationAction(ISD::UREM, MVT::v2i16, Legal, Custom);
846
847 // Other arithmetic and logic ops are unsupported.
848 setOperationAction(Ops: {ISD::SDIV, ISD::UDIV, ISD::SRA, ISD::SRL, ISD::MULHS,
849 ISD::MULHU, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
850 ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::SETCC},
851 VTs: {MVT::v2i16, MVT::v2i32}, Action: Expand);
852
853 // v2i32 is not supported for any arithmetic operations
854 setOperationAction(Ops: {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
855 ISD::CTPOP, ISD::CTLZ, ISD::ADD, ISD::SUB, ISD::MUL,
856 ISD::SHL, ISD::SRA, ISD::SRL, ISD::OR, ISD::AND, ISD::XOR,
857 ISD::SREM, ISD::UREM},
858 VT: MVT::v2i32, Action: Expand);
859
860 setOperationAction(Op: ISD::ADDC, VT: MVT::i32, Action: Legal);
861 setOperationAction(Op: ISD::ADDE, VT: MVT::i32, Action: Legal);
862 setOperationAction(Op: ISD::SUBC, VT: MVT::i32, Action: Legal);
863 setOperationAction(Op: ISD::SUBE, VT: MVT::i32, Action: Legal);
864 if (STI.getPTXVersion() >= 43) {
865 setOperationAction(Op: ISD::ADDC, VT: MVT::i64, Action: Legal);
866 setOperationAction(Op: ISD::ADDE, VT: MVT::i64, Action: Legal);
867 setOperationAction(Op: ISD::SUBC, VT: MVT::i64, Action: Legal);
868 setOperationAction(Op: ISD::SUBE, VT: MVT::i64, Action: Legal);
869 }
870
871 setOperationAction(Op: ISD::CTTZ, VT: MVT::i16, Action: Expand);
872 setOperationAction(Ops: ISD::CTTZ, VTs: {MVT::v2i16, MVT::v2i32}, Action: Expand);
873 setOperationAction(Op: ISD::CTTZ, VT: MVT::i32, Action: Expand);
874 setOperationAction(Op: ISD::CTTZ, VT: MVT::i64, Action: Expand);
875
876 // PTX does not directly support SELP of i1, so promote to i32 first
877 setOperationAction(Op: ISD::SELECT, VT: MVT::i1, Action: Custom);
878
879 // PTX cannot multiply two i64s in a single instruction.
880 setOperationAction(Op: ISD::SMUL_LOHI, VT: MVT::i64, Action: Expand);
881 setOperationAction(Op: ISD::UMUL_LOHI, VT: MVT::i64, Action: Expand);
882
883 // We have some custom DAG combine patterns for these nodes
884 setTargetDAGCombine({ISD::ADD,
885 ISD::AND,
886 ISD::EXTRACT_VECTOR_ELT,
887 ISD::FADD,
888 ISD::FMAXNUM,
889 ISD::FMINNUM,
890 ISD::FMAXIMUM,
891 ISD::FMINIMUM,
892 ISD::FMAXIMUMNUM,
893 ISD::FMINIMUMNUM,
894 ISD::MUL,
895 ISD::SELECT,
896 ISD::SHL,
897 ISD::SREM,
898 ISD::UREM,
899 ISD::VSELECT,
900 ISD::BUILD_VECTOR,
901 ISD::ADDRSPACECAST,
902 ISD::LOAD,
903 ISD::STORE,
904 ISD::ZERO_EXTEND,
905 ISD::SIGN_EXTEND,
906 ISD::INTRINSIC_WO_CHAIN});
907
908 // If the vector operands require register coalescing, scalarize instead
909 if (STI.hasF32x2Instructions())
910 setTargetDAGCombine({ISD::FMA, ISD::FMUL, ISD::FSUB});
911
912 // setcc for f16x2 and bf16x2 needs special handling to prevent
913 // legalizer's attempt to scalarize it due to v2i1 not being legal.
914 if (STI.allowFP16Math() || STI.hasBF16Math())
915 setTargetDAGCombine(ISD::SETCC);
916
917 // Vector reduction operations. These may be turned into shuffle or tree
918 // reductions depending on what instructions are available for each type.
919 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
920 MVT EltVT = VT.getVectorElementType();
921 if (EltVT == MVT::f32 || EltVT == MVT::f64) {
922 setOperationAction(Ops: {ISD::VECREDUCE_FMAX, ISD::VECREDUCE_FMIN,
923 ISD::VECREDUCE_FMAXIMUM, ISD::VECREDUCE_FMINIMUM},
924 VT, Action: Custom);
925 }
926 }
927
928 // Promote fp16 arithmetic if fp16 hardware isn't available or the
929 // user passed --nvptx-no-fp16-math. The flag is useful because,
930 // although sm_53+ GPUs have some sort of FP16 support in
931 // hardware, only sm_53 and sm_60 have full implementation. Others
932 // only have token amount of hardware and are likely to run faster
933 // by using fp32 units instead.
934 for (const auto &Op : {ISD::FADD, ISD::FMUL, ISD::FSUB, ISD::FMA}) {
935 setFP16OperationAction(Op, MVT::f16, Legal, Promote);
936 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
937 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
938 // bf16 must be promoted to f32.
939 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
940 if (getOperationAction(Op, VT: MVT::bf16) == Promote)
941 AddPromotedToType(Opc: Op, OrigVT: MVT::bf16, DestVT: MVT::f32);
942 setOperationAction(Op, VT: MVT::v2f32,
943 Action: STI.hasF32x2Instructions() ? Legal : Expand);
944 }
945
946 // On SM80, we select add/mul/sub as fma to avoid promotion to float
947 for (const auto &Op : {ISD::FADD, ISD::FMUL, ISD::FSUB}) {
948 for (const auto &VT : {MVT::bf16, MVT::v2bf16}) {
949 if (!STI.hasNativeBF16Support(Opcode: Op) && STI.hasNativeBF16Support(Opcode: ISD::FMA)) {
950 setOperationAction(Op, VT, Action: Custom);
951 }
952 }
953 }
954
955 // f16/f16x2 neg was introduced in PTX 60, SM_53.
956 const bool IsFP16FP16x2NegAvailable = STI.getSmVersion() >= 53 &&
957 STI.getPTXVersion() >= 60 &&
958 STI.allowFP16Math();
959 for (const auto &VT : {MVT::f16, MVT::v2f16})
960 setOperationAction(Op: ISD::FNEG, VT,
961 Action: IsFP16FP16x2NegAvailable ? Legal : Expand);
962
963 setBF16OperationAction(ISD::FNEG, MVT::bf16, Legal, Expand);
964 setBF16OperationAction(ISD::FNEG, MVT::v2bf16, Legal, Expand);
965 setOperationAction(Op: ISD::FNEG, VT: MVT::v2f32, Action: Expand);
966 // (would be) Library functions.
967
968 // These map to conversion instructions for scalar FP types.
969 for (const auto &Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, ISD::FRINT,
970 ISD::FROUNDEVEN, ISD::FTRUNC}) {
971 setOperationAction(Op, VT: MVT::f16, Action: Legal);
972 setOperationAction(Op, VT: MVT::f32, Action: Legal);
973 setOperationAction(Op, VT: MVT::f64, Action: Legal);
974 setOperationAction(Op, VT: MVT::v2f16, Action: Expand);
975 setOperationAction(Op, VT: MVT::v2bf16, Action: Expand);
976 setOperationAction(Op, VT: MVT::v2f32, Action: Expand);
977 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
978 if (getOperationAction(Op, VT: MVT::bf16) == Promote)
979 AddPromotedToType(Opc: Op, OrigVT: MVT::bf16, DestVT: MVT::f32);
980 }
981
982 if (STI.getSmVersion() < 80 || STI.getPTXVersion() < 71) {
983 setOperationAction(Op: ISD::BF16_TO_FP, VT: MVT::f32, Action: Expand);
984 }
985 if (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78) {
986 for (MVT VT : {MVT::bf16, MVT::f32, MVT::f64}) {
987 setOperationAction(Op: ISD::FP_EXTEND, VT, Action: Custom);
988 setOperationAction(Op: ISD::FP_ROUND, VT, Action: Custom);
989 }
990 }
991
992 // Expand v2f32 = fp_extend
993 setOperationAction(Op: ISD::FP_EXTEND, VT: MVT::v2f32, Action: Expand);
994 // Expand v2[b]f16 = fp_round v2f32
995 setOperationAction(Ops: ISD::FP_ROUND, VTs: {MVT::v2bf16, MVT::v2f16}, Action: Expand);
996
997 // sm_80 only has conversions between f32 and bf16. Custom lower all other
998 // bf16 conversions.
999 if (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78) {
1000 for (MVT VT : {MVT::i1, MVT::i16, MVT::i32, MVT::i64}) {
1001 setOperationAction(
1002 Ops: {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
1003 VT, Action: Custom);
1004 }
1005 setOperationAction(
1006 Ops: {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
1007 VT: MVT::bf16, Action: Custom);
1008 }
1009
1010 setOperationAction(Ops: {ISD::FP_TO_SINT, ISD::FP_TO_UINT}, VT: MVT::i1, Action: Custom);
1011 setOperationAction(Op: ISD::FROUND, VT: MVT::f16, Action: Promote);
1012 setOperationAction(Op: ISD::FROUND, VT: MVT::v2f16, Action: Expand);
1013 setOperationAction(Op: ISD::FROUND, VT: MVT::v2bf16, Action: Expand);
1014 setOperationAction(Op: ISD::FROUND, VT: MVT::f32, Action: Custom);
1015 setOperationAction(Op: ISD::FROUND, VT: MVT::f64, Action: Custom);
1016 setOperationAction(Op: ISD::FROUND, VT: MVT::bf16, Action: Promote);
1017 AddPromotedToType(Opc: ISD::FROUND, OrigVT: MVT::bf16, DestVT: MVT::f32);
1018
1019 setOperationAction(Ops: {ISD::LROUND, ISD::LLROUND}, VTs: {MVT::f32, MVT::f64}, Action: Expand);
1020
1021 // 'Expand' implements FCOPYSIGN without calling an external library.
1022 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f16, Action: Expand);
1023 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::v2f16, Action: Expand);
1024 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::bf16, Action: Expand);
1025 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::v2bf16, Action: Expand);
1026 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f32, Action: Custom);
1027 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f64, Action: Custom);
1028
1029 // These map to corresponding instructions for f32/f64. f16 must be
1030 // promoted to f32. v2f16 is expanded to f16, which is then promoted
1031 // to f32.
1032 for (const auto &Op :
1033 {ISD::FDIV, ISD::FREM, ISD::FSQRT, ISD::FSIN, ISD::FCOS}) {
1034 setOperationAction(Op, VT: MVT::f16, Action: Promote);
1035 setOperationAction(Op, VT: MVT::f32, Action: Legal);
1036 // only div/rem/sqrt are legal for f64
1037 if (Op == ISD::FDIV || Op == ISD::FREM || Op == ISD::FSQRT) {
1038 setOperationAction(Op, VT: MVT::f64, Action: Legal);
1039 }
1040 setOperationAction(Ops: Op, VTs: {MVT::v2f16, MVT::v2bf16, MVT::v2f32}, Action: Expand);
1041 setOperationAction(Op, VT: MVT::bf16, Action: Promote);
1042 AddPromotedToType(Opc: Op, OrigVT: MVT::bf16, DestVT: MVT::f32);
1043 }
1044 setOperationAction(Ops: ISD::FREM, VTs: {MVT::f32, MVT::f64}, Action: Custom);
1045
1046 // FTANH support:
1047 // - f32 (sm_75+, PTX 7.0+)
1048 // - f16/f16x2 (sm_75+, PTX 7.0+)
1049 // - bf16/bf16x2 (sm_90+, PTX 7.8+)
1050 // When f16/bf16 types aren't supported, they are promoted/expanded to f32.
1051 if (STI.getSmVersion() >= 75 && STI.getPTXVersion() >= 70)
1052 setOperationAction(Op: ISD::FTANH, VT: MVT::f32, Action: Legal);
1053 setOperationAction(Op: ISD::FTANH, VT: MVT::v2f32, Action: Expand);
1054
1055 // Scalar f16/bf16: promote to f32 when not natively supported.
1056 setFP16OperationAction(ISD::FTANH, MVT::f16, Legal, Promote);
1057 setBF16OperationAction(ISD::FTANH, MVT::bf16, Legal, Promote);
1058 if (getOperationAction(Op: ISD::FTANH, VT: MVT::bf16) == Promote)
1059 AddPromotedToType(Opc: ISD::FTANH, OrigVT: MVT::bf16, DestVT: MVT::f32);
1060
1061 // Vector v2f16/v2bf16: expand when not natively supported.
1062 setFP16OperationAction(ISD::FTANH, MVT::v2f16, Legal, Expand);
1063 setBF16OperationAction(ISD::FTANH, MVT::v2bf16, Legal, Expand);
1064
1065 setOperationAction(Ops: ISD::FABS, VTs: {MVT::f32, MVT::f64}, Action: Legal);
1066 setOperationAction(Op: ISD::FABS, VT: MVT::v2f32, Action: Expand);
1067 if (STI.getPTXVersion() >= 65) {
1068 setFP16OperationAction(ISD::FABS, MVT::f16, Legal, Promote);
1069 setFP16OperationAction(ISD::FABS, MVT::v2f16, Legal, Expand);
1070 } else {
1071 setOperationAction(Op: ISD::FABS, VT: MVT::f16, Action: Promote);
1072 setOperationAction(Op: ISD::FABS, VT: MVT::v2f16, Action: Expand);
1073 }
1074 setBF16OperationAction(ISD::FABS, MVT::v2bf16, Legal, Expand);
1075 setBF16OperationAction(ISD::FABS, MVT::bf16, Legal, Promote);
1076 if (getOperationAction(Op: ISD::FABS, VT: MVT::bf16) == Promote)
1077 AddPromotedToType(Opc: ISD::FABS, OrigVT: MVT::bf16, DestVT: MVT::f32);
1078
1079 for (const auto &Op :
1080 {ISD::FMINNUM, ISD::FMAXNUM, ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM}) {
1081 setOperationAction(Op, VT: MVT::f32, Action: Legal);
1082 setOperationAction(Op, VT: MVT::f64, Action: Legal);
1083 setFP16OperationAction(Op, MVT::f16, Legal, Promote);
1084 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
1085 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
1086 setBF16OperationAction(Op, MVT::bf16, Legal, Promote);
1087 if (getOperationAction(Op, VT: MVT::bf16) == Promote)
1088 AddPromotedToType(Opc: Op, OrigVT: MVT::bf16, DestVT: MVT::f32);
1089 setOperationAction(Op, VT: MVT::v2f32, Action: Expand);
1090 }
1091 bool SupportsF32MinMaxNaN =
1092 STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 70;
1093 for (const auto &Op : {ISD::FMINIMUM, ISD::FMAXIMUM}) {
1094 setOperationAction(Op, VT: MVT::f32, Action: SupportsF32MinMaxNaN ? Legal : Expand);
1095 setFP16OperationAction(Op, MVT::f16, Legal, Expand);
1096 setFP16OperationAction(Op, MVT::v2f16, Legal, Expand);
1097 setBF16OperationAction(Op, MVT::bf16, Legal, Expand);
1098 setBF16OperationAction(Op, MVT::v2bf16, Legal, Expand);
1099 setOperationAction(Op, VT: MVT::v2f32, Action: Expand);
1100 }
1101
1102 // Custom lowering for inline asm with 128-bit operands
1103 setOperationAction(Op: ISD::CopyToReg, VT: MVT::i128, Action: Custom);
1104 setOperationAction(Op: ISD::CopyFromReg, VT: MVT::i128, Action: Custom);
1105
1106 // FEXP2 support:
1107 // - f32
1108 // - f16/f16x2 (sm_70+, PTX 7.0+)
1109 // - bf16/bf16x2 (sm_90+, PTX 7.8+)
1110 // When f16/bf16 types aren't supported, they are promoted/expanded to f32.
1111 setOperationAction(Op: ISD::FEXP2, VT: MVT::f32, Action: Legal);
1112 setOperationAction(Op: ISD::FEXP2, VT: MVT::v2f32, Action: Expand);
1113 setFP16OperationAction(ISD::FEXP2, MVT::f16, Legal, Promote);
1114 setFP16OperationAction(ISD::FEXP2, MVT::v2f16, Legal, Expand);
1115 setBF16OperationAction(ISD::FEXP2, MVT::bf16, Legal, Promote);
1116 setBF16OperationAction(ISD::FEXP2, MVT::v2bf16, Legal, Expand);
1117
1118 // FLOG2 supports f32 only
1119 // f16/bf16 types aren't supported, but they are promoted/expanded to f32.
1120 if (UseApproxLog2F32) {
1121 setOperationAction(Op: ISD::FLOG2, VT: MVT::f32, Action: Legal);
1122 setOperationPromotedToType(Opc: ISD::FLOG2, OrigVT: MVT::f16, DestVT: MVT::f32);
1123 setOperationPromotedToType(Opc: ISD::FLOG2, OrigVT: MVT::bf16, DestVT: MVT::f32);
1124 setOperationAction(Ops: ISD::FLOG2, VTs: {MVT::v2f16, MVT::v2bf16, MVT::v2f32},
1125 Action: Expand);
1126 }
1127
1128 setOperationAction(Ops: ISD::ADDRSPACECAST, VTs: {MVT::i32, MVT::i64}, Action: Custom);
1129
1130 setOperationAction(Ops: ISD::ATOMIC_LOAD_SUB, VTs: {MVT::i32, MVT::i64}, Action: Expand);
1131
1132 // atom.b128 is legal in PTX but since we don't represent i128 as a legal
1133 // type, we need to custom lower it.
1134 setOperationAction(Ops: {ISD::ATOMIC_CMP_SWAP, ISD::ATOMIC_SWAP}, VT: MVT::i128,
1135 Action: Custom);
1136
1137 // Now deduce the information based on the above mentioned
1138 // actions
1139 computeRegisterProperties(TRI: STI.getRegisterInfo());
1140
1141 // PTX support for 16-bit CAS is emulated. Only use 32+
1142 setMinCmpXchgSizeInBits(STI.getMinCmpXchgSizeInBits());
1143 setMaxAtomicSizeInBitsSupported(STI.hasAtomSwap128() ? 128 : 64);
1144 setMaxDivRemBitWidthSupported(64);
1145 setMaxLargeFPConvertBitWidthSupported(64);
1146
1147 // Custom lowering for tcgen05.ld vector operands
1148 setOperationAction(Ops: ISD::INTRINSIC_W_CHAIN,
1149 VTs: {MVT::v1i32, MVT::v2i32, MVT::v4i32, MVT::v8i32,
1150 MVT::v16i32, MVT::v32i32, MVT::v64i32, MVT::v128i32,
1151 MVT::v2f32, MVT::v4f32, MVT::v8f32, MVT::v16f32,
1152 MVT::v32f32, MVT::v64f32, MVT::v128f32},
1153 Action: Custom);
1154
1155 // Custom lowering for tcgen05.st vector operands and the st.async
1156 // i128 (.b128) operand. MVT::i8 is needed for the st.async.{sys,gpu} b8
1157 // variant.
1158 setOperationAction(Ops: ISD::INTRINSIC_VOID,
1159 VTs: {MVT::i8, MVT::v1i32, MVT::v2i32, MVT::v4i32, MVT::v8i32,
1160 MVT::v16i32, MVT::v32i32, MVT::v64i32, MVT::v128i32,
1161 MVT::i128, MVT::Other},
1162 Action: Custom);
1163
1164 // Enable custom lowering for the following:
1165 // * MVT::i128 - clusterlaunchcontrol
1166 // * MVT::i32 - prmt
1167 // * MVT::v4f32 - cvt_rs fp{4/6/8}x4 intrinsics
1168 // * MVT::Other - internal.addrspace.wrap
1169 setOperationAction(Ops: ISD::INTRINSIC_WO_CHAIN,
1170 VTs: {MVT::i32, MVT::i128, MVT::v4f32, MVT::Other}, Action: Custom);
1171
1172 // Custom lowering for bswap
1173 setOperationAction(Ops: ISD::BSWAP, VTs: {MVT::i16, MVT::i32, MVT::i64, MVT::v2i16},
1174 Action: Custom);
1175}
1176
1177TargetLoweringBase::LegalizeTypeAction
1178NVPTXTargetLowering::getPreferredVectorAction(MVT VT) const {
1179 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1180 VT.getScalarType() == MVT::i1)
1181 return TypeSplitVector;
1182 return TargetLoweringBase::getPreferredVectorAction(VT);
1183}
1184
1185SDValue NVPTXTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
1186 int Enabled, int &ExtraSteps,
1187 bool &UseOneConst,
1188 bool Reciprocal) const {
1189 if (!(Enabled == ReciprocalEstimate::Enabled ||
1190 (Enabled == ReciprocalEstimate::Unspecified && !usePrecSqrtF32())))
1191 return SDValue();
1192
1193 if (ExtraSteps == ReciprocalEstimate::Unspecified)
1194 ExtraSteps = 0;
1195
1196 SDLoc DL(Operand);
1197 EVT VT = Operand.getValueType();
1198 bool Ftz = useF32FTZ(MF: DAG.getMachineFunction());
1199
1200 auto MakeIntrinsicCall = [&](Intrinsic::ID IID) {
1201 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT,
1202 N1: DAG.getConstant(Val: IID, DL, VT: MVT::i32), N2: Operand);
1203 };
1204
1205 // The sqrt and rsqrt refinement processes assume we always start out with an
1206 // approximation of the rsqrt. Therefore, if we're going to do any refinement
1207 // (i.e. ExtraSteps > 0), we must return an rsqrt. But if we're *not* doing
1208 // any refinement, we must return a regular sqrt.
1209 if (Reciprocal || ExtraSteps > 0) {
1210 if (VT == MVT::f32)
1211 return MakeIntrinsicCall(Ftz ? Intrinsic::nvvm_rsqrt_approx_ftz_f
1212 : Intrinsic::nvvm_rsqrt_approx_f);
1213 else if (VT == MVT::f64)
1214 return MakeIntrinsicCall(Intrinsic::nvvm_rsqrt_approx_d);
1215 else
1216 return SDValue();
1217 } else {
1218 if (VT == MVT::f32)
1219 return MakeIntrinsicCall(Ftz ? Intrinsic::nvvm_sqrt_approx_ftz_f
1220 : Intrinsic::nvvm_sqrt_approx_f);
1221 else {
1222 // There's no sqrt.approx.f64 instruction, so we emit
1223 // reciprocal(rsqrt(x)). This is faster than
1224 // select(x == 0, 0, x * rsqrt(x)). (In fact, it's faster than plain
1225 // x * rsqrt(x).)
1226 return DAG.getNode(
1227 Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT,
1228 N1: DAG.getConstant(Val: Intrinsic::nvvm_rcp_approx_ftz_d, DL, VT: MVT::i32),
1229 N2: MakeIntrinsicCall(Intrinsic::nvvm_rsqrt_approx_d));
1230 }
1231 }
1232}
1233
1234static MachinePointerInfo refinePtrAS(SDValue &Ptr, SelectionDAG &DAG,
1235 const DataLayout &DL,
1236 const TargetLowering &TL) {
1237 if (Ptr->getOpcode() == ISD::FrameIndex) {
1238 auto Ty = TL.getPointerTy(DL, AS: ADDRESS_SPACE_LOCAL);
1239 Ptr = DAG.getAddrSpaceCast(dl: SDLoc(), VT: Ty, Ptr, SrcAS: ADDRESS_SPACE_GENERIC,
1240 DestAS: ADDRESS_SPACE_LOCAL);
1241
1242 return MachinePointerInfo(ADDRESS_SPACE_LOCAL);
1243 }
1244
1245 // Peel of an addrspacecast to generic and load directly from the specific
1246 // address space.
1247 if (Ptr->getOpcode() == ISD::ADDRSPACECAST) {
1248 const auto *ASC = cast<AddrSpaceCastSDNode>(Val&: Ptr);
1249 if (ASC->getDestAddressSpace() == ADDRESS_SPACE_GENERIC) {
1250 Ptr = ASC->getOperand(Num: 0);
1251 return MachinePointerInfo(ASC->getSrcAddressSpace());
1252 }
1253 }
1254
1255 return MachinePointerInfo();
1256}
1257
1258static ISD::NodeType getExtOpcode(const ISD::ArgFlagsTy &Flags) {
1259 if (Flags.isSExt())
1260 return ISD::SIGN_EXTEND;
1261 if (Flags.isZExt())
1262 return ISD::ZERO_EXTEND;
1263 return ISD::ANY_EXTEND;
1264}
1265
1266static SDValue correctParamType(SDValue V, EVT ExpectedVT,
1267 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1268 SDLoc dl) {
1269 const EVT ActualVT = V.getValueType();
1270 assert((ActualVT == ExpectedVT ||
1271 (ExpectedVT.isInteger() && ActualVT.isInteger())) &&
1272 "Non-integer argument type size mismatch");
1273 if (ExpectedVT.bitsGT(VT: ActualVT))
1274 return DAG.getNode(Opcode: getExtOpcode(Flags), DL: dl, VT: ExpectedVT, Operand: V);
1275 if (ExpectedVT.bitsLT(VT: ActualVT))
1276 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ExpectedVT, Operand: V);
1277
1278 return V;
1279}
1280
1281SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1282 SmallVectorImpl<SDValue> &InVals) const {
1283
1284 if (CLI.IsVarArg && (STI.getPTXVersion() < 60 || STI.getSmVersion() < 30))
1285 report_fatal_error(
1286 reason: "Support for variadic functions (unsized array parameter) introduced "
1287 "in PTX ISA version 6.0 and requires target sm_30.");
1288
1289 SelectionDAG &DAG = CLI.DAG;
1290 SDLoc dl = CLI.DL;
1291 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1292 SDValue Callee = CLI.Callee;
1293 ArgListTy &Args = CLI.getArgs();
1294 Type *RetTy = CLI.RetTy;
1295 const CallBase *CB = CLI.CB;
1296 const DataLayout &DL = DAG.getDataLayout();
1297 LLVMContext &Ctx = *DAG.getContext();
1298
1299 const auto GetI32 = [&](const unsigned I) {
1300 return DAG.getConstant(Val: I, DL: dl, VT: MVT::i32);
1301 };
1302
1303 const unsigned UniqueCallSite = GlobalUniqueCallSite++;
1304 const SDValue CallChain = CLI.Chain;
1305 const SDValue StartChain =
1306 DAG.getCALLSEQ_START(Chain: CallChain, InSize: UniqueCallSite, OutSize: 0, DL: dl);
1307 SDValue DeclareGlue = StartChain.getValue(R: 1);
1308
1309 SmallVector<SDValue, 16> CallPrereqs{StartChain};
1310
1311 const auto MakeDeclareScalarParam = [&](SDValue Symbol, unsigned Size) {
1312 // PTX ABI requires integral types to be at least 32 bits in size. FP16 is
1313 // loaded/stored using i16, so it's handled here as well.
1314 const unsigned SizeBits = promoteScalarArgumentSize(size: Size * 8);
1315 SDValue Declare =
1316 DAG.getNode(Opcode: NVPTXISD::DeclareScalarParam, DL: dl, ResultTys: {MVT::Other, MVT::Glue},
1317 Ops: {StartChain, Symbol, GetI32(SizeBits), DeclareGlue});
1318 CallPrereqs.push_back(Elt: Declare);
1319 DeclareGlue = Declare.getValue(R: 1);
1320 return Declare;
1321 };
1322
1323 const auto MakeDeclareArrayParam = [&](SDValue Symbol, Align Align,
1324 unsigned Size) {
1325 SDValue Declare = DAG.getNode(
1326 Opcode: NVPTXISD::DeclareArrayParam, DL: dl, ResultTys: {MVT::Other, MVT::Glue},
1327 Ops: {StartChain, Symbol, GetI32(Align.value()), GetI32(Size), DeclareGlue});
1328 CallPrereqs.push_back(Elt: Declare);
1329 DeclareGlue = Declare.getValue(R: 1);
1330 return Declare;
1331 };
1332
1333 // Variadic arguments.
1334 //
1335 // Normally, for each argument, we declare a param scalar or a param
1336 // byte array in the .param space, and store the argument value to that
1337 // param scalar or array starting at offset 0.
1338 //
1339 // In the case of the first variadic argument, we declare a vararg byte array
1340 // with size 0. The exact size of this array isn't known at this point, so
1341 // it'll be patched later. All the variadic arguments will be stored to this
1342 // array at a certain offset (which gets tracked by 'VAOffset'). The offset is
1343 // initially set to 0, so it can be used for non-variadic arguments (which use
1344 // 0 offset) to simplify the code.
1345 //
1346 // After all vararg is processed, 'VAOffset' holds the size of the
1347 // vararg byte array.
1348 assert((CLI.IsVarArg || CLI.Args.size() <= CLI.NumFixedArgs) &&
1349 "Non-VarArg function with extra arguments");
1350
1351 const unsigned FirstVAArg = CLI.NumFixedArgs; // position of first variadic
1352 unsigned VAOffset = 0; // current offset in the param array
1353
1354 const SDValue VADeclareParam =
1355 CLI.Args.size() > FirstVAArg
1356 ? MakeDeclareArrayParam(getCallParamSymbol(DAG, I: FirstVAArg, T: MVT::i32),
1357 Align(STI.getMaxRequiredAlignment()), 0)
1358 : SDValue();
1359
1360 // Args.size() and Outs.size() need not match.
1361 // Outs.size() will be larger
1362 // * if there is an aggregate argument with multiple fields (each field
1363 // showing up separately in Outs)
1364 // * if there is a vector argument with more than typical vector-length
1365 // elements (generally if more than 4) where each vector element is
1366 // individually present in Outs.
1367 // So a different index should be used for indexing into Outs/OutVals.
1368 // See similar issue in LowerFormalArguments.
1369 auto AllOuts = ArrayRef(CLI.Outs);
1370 auto AllOutVals = ArrayRef(CLI.OutVals);
1371 assert(AllOuts.size() == AllOutVals.size() &&
1372 "Outs and OutVals must be the same size");
1373 // Declare the .params or .reg need to pass values
1374 // to the function
1375 for (const auto E : llvm::enumerate(First&: Args)) {
1376 const auto ArgI = E.index();
1377 const auto Arg = E.value();
1378 const auto ArgOuts =
1379 AllOuts.take_while(Pred: [&](auto O) { return O.OrigArgIndex == ArgI; });
1380 const auto ArgOutVals = AllOutVals.take_front(N: ArgOuts.size());
1381 AllOuts = AllOuts.drop_front(N: ArgOuts.size());
1382 AllOutVals = AllOutVals.drop_front(N: ArgOuts.size());
1383
1384 const bool IsVAArg = (ArgI >= FirstVAArg);
1385 const bool IsByVal = Arg.IsByVal;
1386
1387 const SDValue ParamSymbol =
1388 getCallParamSymbol(DAG, I: IsVAArg ? FirstVAArg : ArgI, T: MVT::i32);
1389
1390 assert((!IsByVal || Arg.IndirectType) &&
1391 "byval arg must have indirect type");
1392 Type *ETy = (IsByVal ? Arg.IndirectType : Arg.Ty);
1393
1394 const Align ArgAlign = [&]() {
1395 const unsigned ParamIdx = ArgI + AttributeList::FirstArgIndex;
1396 if (IsByVal)
1397 return getDeviceByValParamAlign(CB, ArgTy: ETy, AttrIdx: ParamIdx, DL);
1398 return getPTXParamAlign(CB, Ty: Arg.Ty, AttrIdx: ParamIdx, DL);
1399 }();
1400
1401 const unsigned TySize = DL.getTypeAllocSize(Ty: ETy);
1402 assert((!IsByVal || TySize == ArgOuts[0].Flags.getByValSize()) &&
1403 "type size mismatch");
1404
1405 const SDValue ArgDeclare = [&]() {
1406 if (IsVAArg)
1407 return VADeclareParam;
1408
1409 if (IsByVal || shouldPassAsArray(Ty: Arg.Ty))
1410 return MakeDeclareArrayParam(ParamSymbol, ArgAlign, TySize);
1411
1412 assert(ArgOuts.size() == 1 && "We must pass only one value as non-array");
1413 assert((ArgOuts[0].VT.isInteger() || ArgOuts[0].VT.isFloatingPoint()) &&
1414 "Only int and float types are supported as non-array arguments");
1415
1416 return MakeDeclareScalarParam(ParamSymbol, TySize);
1417 }();
1418
1419 if (IsByVal) {
1420 assert(ArgOutVals.size() == 1 && "We must pass only one value as byval");
1421 SDValue SrcPtr = ArgOutVals[0];
1422 const auto PointerInfo = refinePtrAS(Ptr&: SrcPtr, DAG, DL, TL: *this);
1423 // Don't use Flags.getNonZeroByValAlign as this includes the stackalign,
1424 // which does not apply to the source pointer.
1425 const Align BaseSrcAlign = [&]() {
1426 // The align attribute on a byval argument indicates the known alignment
1427 // of the pointer passed to the function.
1428 if (CB)
1429 if (const MaybeAlign A = CB->getParamAlign(ArgNo: ArgI))
1430 return *A;
1431 // Fall back to the default alignment for the type.
1432 // TODO: This might be too aggressive but we haven't had a problem with
1433 // it yet.
1434 return getPTXParamTypeAlign(ArgTy: ETy, DL);
1435 }();
1436
1437 if (IsVAArg)
1438 VAOffset = alignTo(Size: VAOffset, A: ArgAlign);
1439
1440 SmallVector<EVT, 4> ValueVTs, MemVTs;
1441 SmallVector<TypeSize, 4> Offsets;
1442 ComputeValueVTs(TLI: *this, DL, Ty: ETy, ValueVTs, MemVTs: &MemVTs, Offsets: &Offsets);
1443
1444 unsigned J = 0;
1445 const auto VI = VectorizePTXValueVTs(ValueVTs: MemVTs, Offsets, ParamAlignment: ArgAlign, IsVAArg);
1446 for (const unsigned NumElts : VI) {
1447 EVT LoadVT = getVectorizedVT(VT: MemVTs[J], N: NumElts, C&: Ctx);
1448 Align SrcAlign = commonAlignment(A: BaseSrcAlign, Offset: Offsets[J]);
1449 SDValue SrcAddr = DAG.getObjectPtrOffset(SL: dl, Ptr: SrcPtr, Offset: Offsets[J]);
1450 SDValue SrcLoad =
1451 DAG.getLoad(VT: LoadVT, dl, Chain: CallChain, Ptr: SrcAddr, PtrInfo: PointerInfo, Alignment: SrcAlign);
1452
1453 TypeSize ParamOffset = Offsets[J].getWithIncrement(RHS: VAOffset);
1454 Align ParamAlign = commonAlignment(A: ArgAlign, Offset: ParamOffset);
1455 SDValue ParamAddr =
1456 DAG.getObjectPtrOffset(SL: dl, Ptr: ParamSymbol, Offset: ParamOffset);
1457 SDValue StoreParam = DAG.getStore(
1458 Chain: ArgDeclare, dl, Val: SrcLoad, Ptr: ParamAddr,
1459 PtrInfo: MachinePointerInfo(NVPTX::AddressSpace::DeviceParam), Alignment: ParamAlign);
1460 CallPrereqs.push_back(Elt: StoreParam);
1461
1462 J += NumElts;
1463 }
1464 if (IsVAArg)
1465 VAOffset += TySize;
1466 } else {
1467 SmallVector<EVT, 16> VTs;
1468 SmallVector<uint64_t, 16> Offsets;
1469 ComputePTXValueVTs(TLI: *this, DL, Ctx, CallConv: CLI.CallConv, Ty: Arg.Ty, ValueVTs&: VTs, Offsets,
1470 StartingOffset: VAOffset);
1471 assert(VTs.size() == Offsets.size() && "Size mismatch");
1472 assert(VTs.size() == ArgOuts.size() && "Size mismatch");
1473
1474 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter
1475 // than 32-bits are sign extended or zero extended, depending on
1476 // whether they are signed or unsigned types. This case applies
1477 // only to scalar parameters and not to aggregate values.
1478 const bool ExtendIntegerParam =
1479 Arg.Ty->isIntegerTy() && DL.getTypeAllocSizeInBits(Ty: Arg.Ty) < 32;
1480
1481 const auto GetStoredValue = [&](const unsigned I) {
1482 SDValue StVal = ArgOutVals[I];
1483 assert(promoteScalarIntegerPTX(StVal.getValueType()) ==
1484 StVal.getValueType() &&
1485 "OutVal type should always be legal");
1486
1487 const EVT VTI = promoteScalarIntegerPTX(VT: VTs[I]);
1488 const EVT StoreVT =
1489 ExtendIntegerParam ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
1490
1491 return correctParamType(V: StVal, ExpectedVT: StoreVT, Flags: ArgOuts[I].Flags, DAG, dl);
1492 };
1493
1494 unsigned J = 0;
1495 const auto VI = VectorizePTXValueVTs(ValueVTs: VTs, Offsets, ParamAlignment: ArgAlign, IsVAArg);
1496 for (const unsigned NumElts : VI) {
1497 const EVT EltVT = promoteScalarIntegerPTX(VT: VTs[J]);
1498
1499 unsigned Offset;
1500 if (IsVAArg) {
1501 // TODO: We may need to support vector types that can be passed
1502 // as scalars in variadic arguments.
1503 assert(NumElts == 1 &&
1504 "Vectorization should be disabled for vaargs.");
1505
1506 // Align each part of the variadic argument to their type.
1507 VAOffset = alignTo(Size: VAOffset, A: DAG.getEVTAlign(MemoryVT: EltVT));
1508 Offset = VAOffset;
1509
1510 const EVT TheStoreType = ExtendIntegerParam ? MVT::i32 : EltVT;
1511 VAOffset += DL.getTypeAllocSize(Ty: TheStoreType.getTypeForEVT(Context&: Ctx));
1512 } else {
1513 assert(VAOffset == 0 && "VAOffset must be 0 for non-VA args");
1514 Offset = Offsets[J];
1515 }
1516
1517 SDValue Ptr =
1518 DAG.getObjectPtrOffset(SL: dl, Ptr: ParamSymbol, Offset: TypeSize::getFixed(ExactSize: Offset));
1519
1520 const MaybeAlign CurrentAlign = ExtendIntegerParam
1521 ? MaybeAlign(std::nullopt)
1522 : commonAlignment(A: ArgAlign, Offset);
1523
1524 SDValue Val =
1525 getBuildVectorizedValue(N: NumElts, dl, DAG, GetElement: [&](unsigned K) {
1526 return GetStoredValue(J + K);
1527 });
1528
1529 SDValue StoreParam = DAG.getStore(
1530 Chain: ArgDeclare, dl, Val, Ptr,
1531 PtrInfo: MachinePointerInfo(NVPTX::AddressSpace::DeviceParam), Alignment: CurrentAlign);
1532 CallPrereqs.push_back(Elt: StoreParam);
1533
1534 J += NumElts;
1535 }
1536 }
1537 }
1538
1539 // Handle Result
1540 if (!Ins.empty()) {
1541 const SDValue RetSymbol = DAG.getExternalSymbol(Sym: "retval0", VT: MVT::i32);
1542 const unsigned ResultSize = DL.getTypeAllocSize(Ty: RetTy);
1543 if (shouldPassAsArray(Ty: RetTy)) {
1544 const Align RetAlign =
1545 getPTXParamAlign(CB, Ty: RetTy, AttrIdx: AttributeList::ReturnIndex, DL);
1546 MakeDeclareArrayParam(RetSymbol, RetAlign, ResultSize);
1547 } else {
1548 MakeDeclareScalarParam(RetSymbol, ResultSize);
1549 }
1550 }
1551
1552 // Set the size of the vararg param byte array if the callee is a variadic
1553 // function and the variadic part is not empty.
1554 if (VADeclareParam) {
1555 SDValue DeclareParamOps[] = {VADeclareParam.getOperand(i: 0),
1556 VADeclareParam.getOperand(i: 1),
1557 VADeclareParam.getOperand(i: 2), GetI32(VAOffset),
1558 VADeclareParam.getOperand(i: 4)};
1559 DAG.MorphNodeTo(N: VADeclareParam.getNode(), Opc: VADeclareParam.getOpcode(),
1560 VTs: VADeclareParam->getVTList(), Ops: DeclareParamOps);
1561 }
1562
1563 const auto *Func = dyn_cast<GlobalAddressSDNode>(Val: Callee.getNode());
1564 const auto *CalleeF = Func ? dyn_cast<Function>(Val: Func->getGlobal()) : nullptr;
1565
1566 // If the type of the callsite does not match that of the function, convert
1567 // the callsite to an indirect call.
1568 const bool ConvertToIndirectCall =
1569 CalleeF && CB->getFunctionType() != CalleeF->getFunctionType();
1570
1571 // Both indirect calls and libcalls have nullptr Func. In order to distinguish
1572 // between them we must rely on the call site value which is valid for
1573 // indirect calls but is always null for libcalls.
1574 const bool IsIndirectCall = (!Func && CB) || ConvertToIndirectCall;
1575
1576 if (isa<ExternalSymbolSDNode>(Val: Callee)) {
1577 Function* CalleeFunc = nullptr;
1578
1579 // Try to find the callee in the current module.
1580 Callee = DAG.getSymbolFunctionGlobalAddress(Op: Callee, TargetFunction: &CalleeFunc);
1581 assert(CalleeFunc != nullptr && "Libcall callee must be set.");
1582
1583 // Set the "libcall callee" attribute to indicate that the function
1584 // must always have a declaration.
1585 CalleeFunc->addFnAttr(Kind: "nvptx-libcall-callee", Val: "true");
1586 }
1587
1588 // In the indirect function call case, PTX requires a prototype of the form:
1589 // proto_0 : .callprototype(.param .b32 _) _ (.param .b32 _);
1590 // Where the label is to be used as the last arg of the call instruction.
1591 // We record the call site here and emit all prototypes at the
1592 // start of the function in the AsmPrinter.
1593 if (IsIndirectCall)
1594 DAG.getMachineFunction()
1595 .getInfo<NVPTXMachineFunctionInfo>()
1596 ->addCallPrototype(Id: UniqueCallSite, CB);
1597
1598 const bool IsUnknownIntrinsic =
1599 CalleeF && CalleeF->isIntrinsic() &&
1600 CalleeF->getIntrinsicID() == Intrinsic::not_intrinsic;
1601 if (IsUnknownIntrinsic) {
1602 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
1603 DAG.getMachineFunction().getFunction(),
1604 "call to unknown intrinsic '" + CalleeF->getName() +
1605 "' cannot be lowered by the NVPTX backend",
1606 dl.getDebugLoc()));
1607 }
1608
1609 const unsigned Proto = IsIndirectCall ? UniqueCallSite : 0;
1610 const unsigned NumArgs =
1611 std::min<unsigned>(a: CLI.NumFixedArgs + 1, b: Args.size());
1612 /// CALL(Chain, IsConvergent, IsIndirectCall/IsUniform, NumReturns,
1613 /// NumParams, Callee, Proto)
1614 const SDValue CallToken = DAG.getTokenFactor(DL: dl, Vals&: CallPrereqs);
1615 const SDValue Call = DAG.getNode(
1616 Opcode: NVPTXISD::CALL, DL: dl, VT: MVT::Other,
1617 Ops: {CallToken, GetI32(CLI.IsConvergent), GetI32(IsIndirectCall),
1618 GetI32(Ins.empty() ? 0 : 1), GetI32(NumArgs), Callee, GetI32(Proto)});
1619
1620 SmallVector<SDValue, 16> LoadChains{Call};
1621 SmallVector<SDValue, 16> ProxyRegOps;
1622 if (!Ins.empty()) {
1623 SmallVector<EVT, 16> VTs;
1624 SmallVector<uint64_t, 16> Offsets;
1625 ComputePTXValueVTs(TLI: *this, DL, Ctx, CallConv: CLI.CallConv, Ty: RetTy, ValueVTs&: VTs, Offsets);
1626 assert(VTs.size() == Ins.size() && "Bad value decomposition");
1627
1628 const Align RetAlign =
1629 getPTXParamAlign(CB, Ty: RetTy, AttrIdx: AttributeList::ReturnIndex, DL);
1630 const SDValue RetSymbol = DAG.getExternalSymbol(Sym: "retval0", VT: MVT::i32);
1631
1632 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter than
1633 // 32-bits are sign extended or zero extended, depending on whether
1634 // they are signed or unsigned types.
1635 const bool ExtendIntegerRetVal =
1636 RetTy->isIntegerTy() && DL.getTypeAllocSizeInBits(Ty: RetTy) < 32;
1637
1638 unsigned I = 0;
1639 const auto VI = VectorizePTXValueVTs(ValueVTs: VTs, Offsets, ParamAlignment: RetAlign);
1640 for (const unsigned NumElts : VI) {
1641 const MaybeAlign CurrentAlign =
1642 ExtendIntegerRetVal ? MaybeAlign(std::nullopt)
1643 : commonAlignment(A: RetAlign, Offset: Offsets[I]);
1644
1645 const EVT VTI = promoteScalarIntegerPTX(VT: VTs[I]);
1646 const EVT LoadVT =
1647 ExtendIntegerRetVal ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
1648 const EVT VecVT = getVectorizedVT(VT: LoadVT, N: NumElts, C&: Ctx);
1649 SDValue Ptr =
1650 DAG.getObjectPtrOffset(SL: dl, Ptr: RetSymbol, Offset: TypeSize::getFixed(ExactSize: Offsets[I]));
1651
1652 SDValue R = DAG.getLoad(
1653 VT: VecVT, dl, Chain: Call, Ptr,
1654 PtrInfo: MachinePointerInfo(NVPTX::AddressSpace::DeviceParam), Alignment: CurrentAlign);
1655
1656 LoadChains.push_back(Elt: R.getValue(R: 1));
1657 for (const unsigned J : llvm::seq(Size: NumElts))
1658 ProxyRegOps.push_back(Elt: getExtractVectorizedValue(V: R, I: J, VT: LoadVT, dl, DAG));
1659 I += NumElts;
1660 }
1661 }
1662
1663 const SDValue EndToken = DAG.getTokenFactor(DL: dl, Vals&: LoadChains);
1664 const SDValue CallEnd = DAG.getCALLSEQ_END(Chain: EndToken, Size1: UniqueCallSite,
1665 Size2: UniqueCallSite + 1, Glue: SDValue(), DL: dl);
1666
1667 // Append ProxyReg instructions to the chain to make sure that `callseq_end`
1668 // will not get lost. Otherwise, during libcalls expansion, the nodes can become
1669 // dangling.
1670 for (const auto [I, Reg] : llvm::enumerate(First&: ProxyRegOps)) {
1671 SDValue Proxy =
1672 DAG.getNode(Opcode: NVPTXISD::ProxyReg, DL: dl, VT: Reg.getValueType(), Ops: {CallEnd, Reg});
1673 SDValue Ret = correctParamType(V: Proxy, ExpectedVT: Ins[I].VT, Flags: Ins[I].Flags, DAG, dl);
1674 InVals.push_back(Elt: Ret);
1675 }
1676
1677 // set IsTailCall to false for now, until we figure out how to express
1678 // tail call optimization in PTX
1679 CLI.IsTailCall = false;
1680 return CallEnd;
1681}
1682
1683SDValue NVPTXTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1684 SelectionDAG &DAG) const {
1685
1686 if (STI.getPTXVersion() < 73 || STI.getSmVersion() < 52) {
1687 const Function &Fn = DAG.getMachineFunction().getFunction();
1688
1689 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
1690 Fn,
1691 "Support for dynamic alloca introduced in PTX ISA version 7.3 and "
1692 "requires target sm_52.",
1693 SDLoc(Op).getDebugLoc()));
1694 auto Ops = {DAG.getConstant(Val: 0, DL: SDLoc(), VT: Op.getValueType()),
1695 Op.getOperand(i: 0)};
1696 return DAG.getMergeValues(Ops, dl: SDLoc());
1697 }
1698
1699 SDLoc DL(Op.getNode());
1700 SDValue Chain = Op.getOperand(i: 0);
1701 SDValue Size = Op.getOperand(i: 1);
1702 uint64_t Align = Op.getConstantOperandVal(i: 2);
1703
1704 // The alignment on a ISD::DYNAMIC_STACKALLOC node may be 0 to indicate that
1705 // the default stack alignment should be used.
1706 if (Align == 0)
1707 Align = DAG.getSubtarget().getFrameLowering()->getStackAlign().value();
1708
1709 // The size for ptx alloca instruction is 64-bit for m64 and 32-bit for m32.
1710 const MVT LocalVT = getPointerTy(DL: DAG.getDataLayout(), AS: ADDRESS_SPACE_LOCAL);
1711
1712 SDValue Alloc =
1713 DAG.getNode(Opcode: NVPTXISD::DYNAMIC_STACKALLOC, DL, ResultTys: {LocalVT, MVT::Other},
1714 Ops: {Chain, DAG.getZExtOrTrunc(Op: Size, DL, VT: LocalVT),
1715 DAG.getTargetConstant(Val: Align, DL, VT: MVT::i32)});
1716
1717 SDValue ASC = DAG.getAddrSpaceCast(
1718 dl: DL, VT: Op.getValueType(), Ptr: Alloc, SrcAS: ADDRESS_SPACE_LOCAL, DestAS: ADDRESS_SPACE_GENERIC);
1719
1720 return DAG.getMergeValues(Ops: {ASC, SDValue(Alloc.getNode(), 1)}, dl: DL);
1721}
1722
1723SDValue NVPTXTargetLowering::LowerSTACKRESTORE(SDValue Op,
1724 SelectionDAG &DAG) const {
1725 SDLoc DL(Op.getNode());
1726 if (STI.getPTXVersion() < 73 || STI.getSmVersion() < 52) {
1727 const Function &Fn = DAG.getMachineFunction().getFunction();
1728
1729 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
1730 Fn,
1731 "Support for stackrestore requires PTX ISA version >= 7.3 and target "
1732 ">= sm_52.",
1733 DL.getDebugLoc()));
1734 return Op.getOperand(i: 0);
1735 }
1736
1737 const MVT LocalVT = getPointerTy(DL: DAG.getDataLayout(), AS: ADDRESS_SPACE_LOCAL);
1738 SDValue Chain = Op.getOperand(i: 0);
1739 SDValue Ptr = Op.getOperand(i: 1);
1740 SDValue ASC = DAG.getAddrSpaceCast(dl: DL, VT: LocalVT, Ptr, SrcAS: ADDRESS_SPACE_GENERIC,
1741 DestAS: ADDRESS_SPACE_LOCAL);
1742 return DAG.getNode(Opcode: NVPTXISD::STACKRESTORE, DL, VT: MVT::Other, Ops: {Chain, ASC});
1743}
1744
1745SDValue NVPTXTargetLowering::LowerSTACKSAVE(SDValue Op,
1746 SelectionDAG &DAG) const {
1747 SDLoc DL(Op.getNode());
1748 if (STI.getPTXVersion() < 73 || STI.getSmVersion() < 52) {
1749 const Function &Fn = DAG.getMachineFunction().getFunction();
1750
1751 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
1752 Fn,
1753 "Support for stacksave requires PTX ISA version >= 7.3 and target >= "
1754 "sm_52.",
1755 DL.getDebugLoc()));
1756 auto Ops = {DAG.getConstant(Val: 0, DL, VT: Op.getValueType()), Op.getOperand(i: 0)};
1757 return DAG.getMergeValues(Ops, dl: DL);
1758 }
1759
1760 const MVT LocalVT = getPointerTy(DL: DAG.getDataLayout(), AS: ADDRESS_SPACE_LOCAL);
1761 SDValue Chain = Op.getOperand(i: 0);
1762 SDValue SS =
1763 DAG.getNode(Opcode: NVPTXISD::STACKSAVE, DL, ResultTys: {LocalVT, MVT::Other}, Ops: Chain);
1764 SDValue ASC = DAG.getAddrSpaceCast(
1765 dl: DL, VT: Op.getValueType(), Ptr: SS, SrcAS: ADDRESS_SPACE_LOCAL, DestAS: ADDRESS_SPACE_GENERIC);
1766 return DAG.getMergeValues(Ops: {ASC, SDValue(SS.getNode(), 1)}, dl: DL);
1767}
1768
1769// By default CONCAT_VECTORS is lowered by ExpandVectorBuildThroughStack()
1770// (see LegalizeDAG.cpp). This is slow and uses local memory.
1771// We use extract/insert/build vector just as what LegalizeOp() does in llvm 2.5
1772SDValue
1773NVPTXTargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
1774 SDNode *Node = Op.getNode();
1775 SDLoc dl(Node);
1776 SmallVector<SDValue, 8> Ops;
1777 unsigned NumOperands = Node->getNumOperands();
1778 for (unsigned i = 0; i < NumOperands; ++i) {
1779 SDValue SubOp = Node->getOperand(Num: i);
1780 EVT VVT = SubOp.getNode()->getValueType(ResNo: 0);
1781 EVT EltVT = VVT.getVectorElementType();
1782 unsigned NumSubElem = VVT.getVectorNumElements();
1783 for (unsigned j = 0; j < NumSubElem; ++j) {
1784 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: SubOp,
1785 N2: DAG.getIntPtrConstant(Val: j, DL: dl)));
1786 }
1787 }
1788 return DAG.getBuildVector(VT: Node->getValueType(ResNo: 0), DL: dl, Ops);
1789}
1790
1791static SDValue getPRMT(SDValue A, SDValue B, SDValue Selector, SDLoc DL,
1792 SelectionDAG &DAG,
1793 unsigned Mode = NVPTX::PTXPrmtMode::NONE) {
1794 assert(A.getValueType() == MVT::i32 && B.getValueType() == MVT::i32 &&
1795 Selector.getValueType() == MVT::i32 && "PRMT must have i32 operands");
1796 return DAG.getNode(Opcode: NVPTXISD::PRMT, DL, VT: MVT::i32,
1797 Ops: {A, B, Selector, DAG.getConstant(Val: Mode, DL, VT: MVT::i32)});
1798}
1799
1800static SDValue getPRMT(SDValue A, SDValue B, uint64_t Selector, SDLoc DL,
1801 SelectionDAG &DAG,
1802 unsigned Mode = NVPTX::PTXPrmtMode::NONE) {
1803 return getPRMT(A, B, Selector: DAG.getConstant(Val: Selector, DL, VT: MVT::i32), DL, DAG, Mode);
1804}
1805
1806/// Reduces the elements using the scalar operations provided. The operations
1807/// are sorted descending in number of inputs they take. The flags on the
1808/// original reduction operation will be propagated to each scalar operation.
1809/// Nearby elements are grouped in tree reduction, unlike the shuffle reduction
1810/// used in ExpandReductions and SelectionDAG.
1811static SDValue buildTreeReduction(
1812 const SmallVector<SDValue> &Elements, EVT EltTy,
1813 ArrayRef<std::pair<unsigned /*NodeType*/, unsigned /*NumInputs*/>> Ops,
1814 const SDLoc &DL, const SDNodeFlags Flags, SelectionDAG &DAG) {
1815 // Build the reduction tree at each level, starting with all the elements.
1816 SmallVector<SDValue> Level = Elements;
1817
1818 unsigned OpIdx = 0;
1819 while (Level.size() > 1) {
1820 // Try to reduce this level using the current operator.
1821 const auto [Op, NumInputs] = Ops[OpIdx];
1822
1823 // Build the next level by partially reducing all elements.
1824 SmallVector<SDValue> ReducedLevel;
1825 unsigned I = 0, E = Level.size();
1826 for (; I + NumInputs <= E; I += NumInputs) {
1827 // Reduce elements in groups of [NumInputs], as much as possible.
1828 ReducedLevel.push_back(Elt: DAG.getNode(
1829 Opcode: Op, DL, VT: EltTy, Ops: ArrayRef<SDValue>(Level).slice(N: I, M: NumInputs), Flags));
1830 }
1831
1832 if (I < E) {
1833 // Handle leftover elements.
1834
1835 if (ReducedLevel.empty()) {
1836 // We didn't reduce anything at this level. We need to pick a smaller
1837 // operator.
1838 ++OpIdx;
1839 assert(OpIdx < Ops.size() && "no smaller operators for reduction");
1840 continue;
1841 }
1842
1843 // We reduced some things but there's still more left, meaning the
1844 // operator's number of inputs doesn't evenly divide this level size. Move
1845 // these elements to the next level.
1846 for (; I < E; ++I)
1847 ReducedLevel.push_back(Elt: Level[I]);
1848 }
1849
1850 // Process the next level.
1851 Level = ReducedLevel;
1852 }
1853
1854 return *Level.begin();
1855}
1856
1857// Get scalar reduction opcode
1858static ISD::NodeType getScalarOpcodeForReduction(unsigned ReductionOpcode) {
1859 switch (ReductionOpcode) {
1860 case ISD::VECREDUCE_FMAX:
1861 return ISD::FMAXNUM;
1862 case ISD::VECREDUCE_FMIN:
1863 return ISD::FMINNUM;
1864 case ISD::VECREDUCE_FMAXIMUM:
1865 return ISD::FMAXIMUM;
1866 case ISD::VECREDUCE_FMINIMUM:
1867 return ISD::FMINIMUM;
1868 default:
1869 llvm_unreachable("unhandled reduction opcode");
1870 }
1871}
1872
1873/// Get 3-input scalar reduction opcode
1874static std::optional<unsigned>
1875getScalar3OpcodeForReduction(unsigned ReductionOpcode) {
1876 switch (ReductionOpcode) {
1877 case ISD::VECREDUCE_FMAX:
1878 return NVPTXISD::FMAXNUM3;
1879 case ISD::VECREDUCE_FMIN:
1880 return NVPTXISD::FMINNUM3;
1881 case ISD::VECREDUCE_FMAXIMUM:
1882 return NVPTXISD::FMAXIMUM3;
1883 case ISD::VECREDUCE_FMINIMUM:
1884 return NVPTXISD::FMINIMUM3;
1885 default:
1886 return std::nullopt;
1887 }
1888}
1889
1890/// Lower reductions to either a sequence of operations or a tree if
1891/// reassociations are allowed. This method will use larger operations like
1892/// max3/min3 when the target supports them.
1893SDValue NVPTXTargetLowering::LowerVECREDUCE(SDValue Op,
1894 SelectionDAG &DAG) const {
1895 SDLoc DL(Op);
1896 const SDNodeFlags Flags = Op->getFlags();
1897 SDValue Vector = Op.getOperand(i: 0);
1898
1899 const unsigned Opcode = Op->getOpcode();
1900 const EVT EltTy = Vector.getValueType().getVectorElementType();
1901
1902 // Whether we can use 3-input min/max when expanding the reduction.
1903 const bool CanUseMinMax3 =
1904 EltTy == MVT::f32 && STI.getSmVersion() >= 100 &&
1905 STI.getPTXVersion() >= 88 &&
1906 (Opcode == ISD::VECREDUCE_FMAX || Opcode == ISD::VECREDUCE_FMIN ||
1907 Opcode == ISD::VECREDUCE_FMAXIMUM || Opcode == ISD::VECREDUCE_FMINIMUM);
1908
1909 // A list of SDNode opcodes with equivalent semantics, sorted descending by
1910 // number of inputs they take.
1911 SmallVector<std::pair<unsigned /*Op*/, unsigned /*NumIn*/>, 2> ScalarOps;
1912
1913 if (auto Opcode3Elem = getScalar3OpcodeForReduction(ReductionOpcode: Opcode);
1914 CanUseMinMax3 && Opcode3Elem)
1915 ScalarOps.push_back(Elt: {*Opcode3Elem, 3});
1916 ScalarOps.push_back(Elt: {getScalarOpcodeForReduction(ReductionOpcode: Opcode), 2});
1917
1918 SmallVector<SDValue> Elements;
1919 DAG.ExtractVectorElements(Op: Vector, Args&: Elements);
1920
1921 return buildTreeReduction(Elements, EltTy, Ops: ScalarOps, DL, Flags, DAG);
1922}
1923
1924SDValue NVPTXTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
1925 // Handle bitcasting from v2i8 without hitting the default promotion
1926 // strategy which goes through stack memory.
1927 EVT FromVT = Op->getOperand(Num: 0)->getValueType(ResNo: 0);
1928 if (FromVT != MVT::v2i8) {
1929 return Op;
1930 }
1931
1932 // Pack vector elements into i16 and bitcast to final type
1933 SDLoc DL(Op);
1934 SDValue Vec0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i8,
1935 N1: Op->getOperand(Num: 0), N2: DAG.getIntPtrConstant(Val: 0, DL));
1936 SDValue Vec1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i8,
1937 N1: Op->getOperand(Num: 0), N2: DAG.getIntPtrConstant(Val: 1, DL));
1938 SDValue Extend0 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: MVT::i16, Operand: Vec0);
1939 SDValue Extend1 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: MVT::i16, Operand: Vec1);
1940 SDValue Const8 = DAG.getConstant(Val: 8, DL, VT: MVT::i16);
1941 SDValue AsInt = DAG.getNode(
1942 Opcode: ISD::OR, DL, VT: MVT::i16,
1943 Ops: {Extend0, DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i16, Ops: {Extend1, Const8})});
1944 EVT ToVT = Op->getValueType(ResNo: 0);
1945 return DAG.getBitcast(VT: ToVT, V: AsInt);
1946}
1947
1948// We can init constant f16x2/v2i16/v4i8 with a single .b32 move. Normally it
1949// would get lowered as two constant loads and vector-packing move.
1950// Instead we want just a constant move:
1951// mov.b32 %r2, 0x40003C00
1952SDValue NVPTXTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1953 SelectionDAG &DAG) const {
1954 EVT VT = Op->getValueType(ResNo: 0);
1955 if (!(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector()))
1956 return Op;
1957 SDLoc DL(Op);
1958
1959 if (!llvm::all_of(Range: Op->ops(), P: [](SDValue Operand) {
1960 return Operand->isUndef() || isa<ConstantSDNode>(Val: Operand) ||
1961 isa<ConstantFPSDNode>(Val: Operand);
1962 })) {
1963 if (VT != MVT::v4i8)
1964 return Op;
1965 // Lower non-const v4i8 vector as byte-wise constructed i32, which allows us
1966 // to optimize calculation of constant parts.
1967 auto GetPRMT = [&](const SDValue Left, const SDValue Right, bool Cast,
1968 uint64_t SelectionValue) -> SDValue {
1969 SDValue L = Left;
1970 SDValue R = Right;
1971 if (Cast) {
1972 L = DAG.getAnyExtOrTrunc(Op: L, DL, VT: MVT::i32);
1973 R = DAG.getAnyExtOrTrunc(Op: R, DL, VT: MVT::i32);
1974 }
1975 return getPRMT(A: L, B: R, Selector: SelectionValue, DL, DAG);
1976 };
1977 auto PRMT__10 = GetPRMT(Op->getOperand(Num: 0), Op->getOperand(Num: 1), true, 0x3340);
1978 auto PRMT__32 = GetPRMT(Op->getOperand(Num: 2), Op->getOperand(Num: 3), true, 0x3340);
1979 auto PRMT3210 = GetPRMT(PRMT__10, PRMT__32, false, 0x5410);
1980 return DAG.getBitcast(VT, V: PRMT3210);
1981 }
1982
1983 // Get value or the Nth operand as an APInt(32). Undef values treated as 0.
1984 auto GetOperand = [](SDValue Op, int N) -> APInt {
1985 const SDValue &Operand = Op->getOperand(Num: N);
1986 EVT VT = Op->getValueType(ResNo: 0);
1987 if (Operand->isUndef())
1988 return APInt(32, 0);
1989 APInt Value;
1990 if (VT == MVT::v2f16 || VT == MVT::v2bf16)
1991 Value = cast<ConstantFPSDNode>(Val: Operand)->getValueAPF().bitcastToAPInt();
1992 else if (VT == MVT::v2i16 || VT == MVT::v4i8)
1993 Value = Operand->getAsAPIntVal();
1994 else
1995 llvm_unreachable("Unsupported type");
1996 // i8 values are carried around as i16, so we need to zero out upper bits,
1997 // so they do not get in the way of combining individual byte values
1998 if (VT == MVT::v4i8)
1999 Value = Value.trunc(width: 8);
2000 return Value.zext(width: 32);
2001 };
2002
2003 // Construct a 32-bit constant by shifting into place smaller values
2004 // (elements of the vector type VT).
2005 // For example, if VT has 2 elements, then N == 2:
2006 // ShiftAmount = 32 / N = 16
2007 // Value |= Op0 (b16) << 0
2008 // Value |= Op1 (b16) << 16
2009 // If N == 4:
2010 // ShiftAmount = 32 / N = 8
2011 // Value |= Op0 (b8) << 0
2012 // Value |= Op1 (b8) << 8
2013 // Value |= Op2 (b8) << 16
2014 // Value |= Op3 (b8) << 24
2015 // ...etc
2016 APInt Value(32, 0);
2017 const unsigned NumElements = VT.getVectorNumElements();
2018 assert(32 % NumElements == 0 && "must evenly divide bit length");
2019 const unsigned ShiftAmount = 32 / NumElements;
2020 for (unsigned ElementNo : seq(Size: NumElements))
2021 Value |= GetOperand(Op, ElementNo).shl(shiftAmt: ElementNo * ShiftAmount);
2022 SDValue Const = DAG.getConstant(Val: Value, DL, VT: MVT::i32);
2023 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: Op->getValueType(ResNo: 0), Operand: Const);
2024}
2025
2026SDValue NVPTXTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
2027 SelectionDAG &DAG) const {
2028 SDValue Index = Op->getOperand(Num: 1);
2029 SDValue Vector = Op->getOperand(Num: 0);
2030 SDLoc DL(Op);
2031 EVT VectorVT = Vector.getValueType();
2032
2033 if (VectorVT == MVT::v4i8) {
2034 SDValue Selector = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32,
2035 N1: DAG.getZExtOrTrunc(Op: Index, DL, VT: MVT::i32),
2036 N2: DAG.getConstant(Val: 0x7770, DL, VT: MVT::i32));
2037 SDValue PRMT = getPRMT(A: DAG.getBitcast(VT: MVT::i32, V: Vector),
2038 B: DAG.getConstant(Val: 0, DL, VT: MVT::i32), Selector, DL, DAG);
2039 SDValue Ext = DAG.getAnyExtOrTrunc(Op: PRMT, DL, VT: Op->getValueType(ResNo: 0));
2040 SDNodeFlags Flags;
2041 Flags.setNoSignedWrap(Ext.getScalarValueSizeInBits() > 8);
2042 Flags.setNoUnsignedWrap(Ext.getScalarValueSizeInBits() >= 8);
2043 Ext->setFlags(Flags);
2044 return Ext;
2045 }
2046
2047 // Constant index will be matched by tablegen.
2048 if (isa<ConstantSDNode>(Val: Index.getNode()))
2049 return Op;
2050
2051 // Extract individual elements and select one of them.
2052 assert(NVPTX::isPackedVectorTy(VectorVT) &&
2053 VectorVT.getVectorNumElements() == 2 && "Unexpected vector type.");
2054 EVT EltVT = VectorVT.getVectorElementType();
2055
2056 SDLoc dl(Op.getNode());
2057 SDValue E0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Vector,
2058 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
2059 SDValue E1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Vector,
2060 N2: DAG.getIntPtrConstant(Val: 1, DL: dl));
2061 return DAG.getSelectCC(DL: dl, LHS: Index, RHS: DAG.getIntPtrConstant(Val: 0, DL: dl), True: E0, False: E1,
2062 Cond: ISD::CondCode::SETEQ);
2063}
2064
2065SDValue NVPTXTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
2066 SelectionDAG &DAG) const {
2067 SDValue Vector = Op->getOperand(Num: 0);
2068 EVT VectorVT = Vector.getValueType();
2069
2070 if (VectorVT != MVT::v4i8)
2071 return Op;
2072 SDLoc DL(Op);
2073 SDValue Value = Op->getOperand(Num: 1);
2074 if (Value->isUndef())
2075 return Vector;
2076
2077 SDValue Index = Op->getOperand(Num: 2);
2078
2079 SDValue BFI =
2080 DAG.getNode(Opcode: NVPTXISD::BFI, DL, VT: MVT::i32,
2081 Ops: {DAG.getZExtOrTrunc(Op: Value, DL, VT: MVT::i32), Vector,
2082 DAG.getNode(Opcode: ISD::MUL, DL, VT: MVT::i32,
2083 N1: DAG.getZExtOrTrunc(Op: Index, DL, VT: MVT::i32),
2084 N2: DAG.getConstant(Val: 8, DL, VT: MVT::i32)),
2085 DAG.getConstant(Val: 8, DL, VT: MVT::i32)});
2086 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: Op->getValueType(ResNo: 0), Operand: BFI);
2087}
2088
2089SDValue NVPTXTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
2090 SelectionDAG &DAG) const {
2091 SDValue V1 = Op.getOperand(i: 0);
2092 EVT VectorVT = V1.getValueType();
2093 if (VectorVT != MVT::v4i8 || Op.getValueType() != MVT::v4i8)
2094 return Op;
2095
2096 // Lower shuffle to PRMT instruction.
2097 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: Op.getNode());
2098 SDValue V2 = Op.getOperand(i: 1);
2099 uint32_t Selector = 0;
2100 for (auto I : llvm::enumerate(First: SVN->getMask())) {
2101 if (I.value() != -1) // -1 is a placeholder for undef.
2102 Selector |= (I.value() << (I.index() * 4));
2103 }
2104
2105 SDLoc DL(Op);
2106 SDValue PRMT = getPRMT(A: DAG.getBitcast(VT: MVT::i32, V: V1),
2107 B: DAG.getBitcast(VT: MVT::i32, V: V2), Selector, DL, DAG);
2108 return DAG.getBitcast(VT: Op.getValueType(), V: PRMT);
2109}
2110/// LowerShiftRightParts - Lower SRL_PARTS, SRA_PARTS, which
2111/// 1) returns two i32 values and take a 2 x i32 value to shift plus a shift
2112/// amount, or
2113/// 2) returns two i64 values and take a 2 x i64 value to shift plus a shift
2114/// amount.
2115SDValue NVPTXTargetLowering::LowerShiftRightParts(SDValue Op,
2116 SelectionDAG &DAG) const {
2117 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2118 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
2119
2120 EVT VT = Op.getValueType();
2121 unsigned VTBits = VT.getSizeInBits();
2122 SDLoc dl(Op);
2123 SDValue ShOpLo = Op.getOperand(i: 0);
2124 SDValue ShOpHi = Op.getOperand(i: 1);
2125 SDValue ShAmt = Op.getOperand(i: 2);
2126 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
2127
2128 if (VTBits == 32 && STI.getSmVersion() >= 35) {
2129 // For 32bit and sm35, we can use the funnel shift 'shf' instruction.
2130 // {dHi, dLo} = {aHi, aLo} >> Amt
2131 // dHi = aHi >> Amt
2132 // dLo = shf.r.clamp aLo, aHi, Amt
2133
2134 SDValue Hi = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
2135 SDValue Lo =
2136 DAG.getNode(Opcode: NVPTXISD::FSHR_CLAMP, DL: dl, VT, N1: ShOpHi, N2: ShOpLo, N3: ShAmt);
2137
2138 SDValue Ops[2] = { Lo, Hi };
2139 return DAG.getMergeValues(Ops, dl);
2140 }
2141 else {
2142 // {dHi, dLo} = {aHi, aLo} >> Amt
2143 // - if (Amt>=size) then
2144 // dLo = aHi >> (Amt-size)
2145 // dHi = aHi >> Amt (this is either all 0 or all 1)
2146 // else
2147 // dLo = (aLo >>logic Amt) | (aHi << (size-Amt))
2148 // dHi = aHi >> Amt
2149
2150 SDValue RevShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
2151 N1: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32),
2152 N2: ShAmt);
2153 SDValue Tmp1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
2154 SDValue ExtraShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: ShAmt,
2155 N2: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32));
2156 SDValue Tmp2 = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpHi, N2: RevShAmt);
2157 SDValue FalseVal = DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: Tmp1, N2: Tmp2);
2158 SDValue TrueVal = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ExtraShAmt);
2159
2160 SDValue Cmp = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: ShAmt,
2161 RHS: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32),
2162 Cond: ISD::SETGE);
2163 SDValue Hi = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
2164 SDValue Lo = DAG.getNode(Opcode: ISD::SELECT, DL: dl, VT, N1: Cmp, N2: TrueVal, N3: FalseVal);
2165
2166 SDValue Ops[2] = { Lo, Hi };
2167 return DAG.getMergeValues(Ops, dl);
2168 }
2169}
2170
2171/// LowerShiftLeftParts - Lower SHL_PARTS, which
2172/// 1) returns two i32 values and take a 2 x i32 value to shift plus a shift
2173/// amount, or
2174/// 2) returns two i64 values and take a 2 x i64 value to shift plus a shift
2175/// amount.
2176SDValue NVPTXTargetLowering::LowerShiftLeftParts(SDValue Op,
2177 SelectionDAG &DAG) const {
2178 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2179 assert(Op.getOpcode() == ISD::SHL_PARTS);
2180
2181 EVT VT = Op.getValueType();
2182 unsigned VTBits = VT.getSizeInBits();
2183 SDLoc dl(Op);
2184 SDValue ShOpLo = Op.getOperand(i: 0);
2185 SDValue ShOpHi = Op.getOperand(i: 1);
2186 SDValue ShAmt = Op.getOperand(i: 2);
2187
2188 if (VTBits == 32 && STI.getSmVersion() >= 35) {
2189 // For 32bit and sm35, we can use the funnel shift 'shf' instruction.
2190 // {dHi, dLo} = {aHi, aLo} << Amt
2191 // dHi = shf.l.clamp aLo, aHi, Amt
2192 // dLo = aLo << Amt
2193
2194 SDValue Hi =
2195 DAG.getNode(Opcode: NVPTXISD::FSHL_CLAMP, DL: dl, VT, N1: ShOpHi, N2: ShOpLo, N3: ShAmt);
2196 SDValue Lo = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
2197
2198 SDValue Ops[2] = { Lo, Hi };
2199 return DAG.getMergeValues(Ops, dl);
2200 }
2201 else {
2202 // {dHi, dLo} = {aHi, aLo} << Amt
2203 // - if (Amt>=size) then
2204 // dLo = aLo << Amt (all 0)
2205 // dLo = aLo << (Amt-size)
2206 // else
2207 // dLo = aLo << Amt
2208 // dHi = (aHi << Amt) | (aLo >> (size-Amt))
2209
2210 SDValue RevShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
2211 N1: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32),
2212 N2: ShAmt);
2213 SDValue Tmp1 = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
2214 SDValue ExtraShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: ShAmt,
2215 N2: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32));
2216 SDValue Tmp2 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: ShOpLo, N2: RevShAmt);
2217 SDValue FalseVal = DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: Tmp1, N2: Tmp2);
2218 SDValue TrueVal = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ExtraShAmt);
2219
2220 SDValue Cmp = DAG.getSetCC(DL: dl, VT: MVT::i1, LHS: ShAmt,
2221 RHS: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32),
2222 Cond: ISD::SETGE);
2223 SDValue Lo = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
2224 SDValue Hi = DAG.getNode(Opcode: ISD::SELECT, DL: dl, VT, N1: Cmp, N2: TrueVal, N3: FalseVal);
2225
2226 SDValue Ops[2] = { Lo, Hi };
2227 return DAG.getMergeValues(Ops, dl);
2228 }
2229}
2230
2231/// If the types match, convert the generic copysign to the NVPTXISD version,
2232/// otherwise bail ensuring that mismatched cases are properly expaned.
2233SDValue NVPTXTargetLowering::LowerFCOPYSIGN(SDValue Op,
2234 SelectionDAG &DAG) const {
2235 EVT VT = Op.getValueType();
2236 SDLoc DL(Op);
2237
2238 SDValue In1 = Op.getOperand(i: 0);
2239 SDValue In2 = Op.getOperand(i: 1);
2240 EVT SrcVT = In2.getValueType();
2241
2242 if (!SrcVT.bitsEq(VT))
2243 return SDValue();
2244
2245 return DAG.getNode(Opcode: NVPTXISD::FCOPYSIGN, DL, VT, N1: In1, N2: In2);
2246}
2247
2248SDValue NVPTXTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2249 EVT VT = Op.getValueType();
2250
2251 if (VT == MVT::f32)
2252 return LowerFROUND32(Op, DAG);
2253
2254 if (VT == MVT::f64)
2255 return LowerFROUND64(Op, DAG);
2256
2257 llvm_unreachable("unhandled type");
2258}
2259
2260// This is the the rounding method used in CUDA libdevice in C like code:
2261// float roundf(float A)
2262// {
2263// float RoundedA = (float) (int) ( A > 0 ? (A + 0.5f) : (A - 0.5f));
2264// RoundedA = abs(A) > 0x1.0p23 ? A : RoundedA;
2265// return abs(A) < 0.5 ? (float)(int)A : RoundedA;
2266// }
2267SDValue NVPTXTargetLowering::LowerFROUND32(SDValue Op,
2268 SelectionDAG &DAG) const {
2269 SDLoc SL(Op);
2270 SDValue A = Op.getOperand(i: 0);
2271 EVT VT = Op.getValueType();
2272
2273 SDValue AbsA = DAG.getNode(Opcode: ISD::FABS, DL: SL, VT, Operand: A);
2274
2275 // RoundedA = (float) (int) ( A > 0 ? (A + 0.5f) : (A - 0.5f))
2276 SDValue Bitcast = DAG.getNode(Opcode: ISD::BITCAST, DL: SL, VT: MVT::i32, Operand: A);
2277 const unsigned SignBitMask = 0x80000000;
2278 SDValue Sign = DAG.getNode(Opcode: ISD::AND, DL: SL, VT: MVT::i32, N1: Bitcast,
2279 N2: DAG.getConstant(Val: SignBitMask, DL: SL, VT: MVT::i32));
2280 const unsigned PointFiveInBits = 0x3F000000;
2281 SDValue PointFiveWithSignRaw =
2282 DAG.getNode(Opcode: ISD::OR, DL: SL, VT: MVT::i32, N1: Sign,
2283 N2: DAG.getConstant(Val: PointFiveInBits, DL: SL, VT: MVT::i32));
2284 SDValue PointFiveWithSign =
2285 DAG.getNode(Opcode: ISD::BITCAST, DL: SL, VT, Operand: PointFiveWithSignRaw);
2286 SDValue AdjustedA = DAG.getNode(Opcode: ISD::FADD, DL: SL, VT, N1: A, N2: PointFiveWithSign);
2287 SDValue RoundedA = DAG.getNode(Opcode: ISD::FTRUNC, DL: SL, VT, Operand: AdjustedA);
2288
2289 // RoundedA = abs(A) > 0x1.0p23 ? A : RoundedA;
2290 EVT SetCCVT = getSetCCResultType(DL: DAG.getDataLayout(), Ctx&: *DAG.getContext(), VT);
2291 SDValue IsLarge =
2292 DAG.getSetCC(DL: SL, VT: SetCCVT, LHS: AbsA, RHS: DAG.getConstantFP(Val: pow(x: 2.0, y: 23.0), DL: SL, VT),
2293 Cond: ISD::SETOGT);
2294 RoundedA = DAG.getNode(Opcode: ISD::SELECT, DL: SL, VT, N1: IsLarge, N2: A, N3: RoundedA);
2295
2296 // return abs(A) < 0.5 ? (float)(int)A : RoundedA;
2297 SDValue IsSmall =DAG.getSetCC(DL: SL, VT: SetCCVT, LHS: AbsA,
2298 RHS: DAG.getConstantFP(Val: 0.5, DL: SL, VT), Cond: ISD::SETOLT);
2299 SDValue RoundedAForSmallA = DAG.getNode(Opcode: ISD::FTRUNC, DL: SL, VT, Operand: A);
2300 return DAG.getNode(Opcode: ISD::SELECT, DL: SL, VT, N1: IsSmall, N2: RoundedAForSmallA, N3: RoundedA);
2301}
2302
2303// The implementation of round(double) is similar to that of round(float) in
2304// that they both separate the value range into three regions and use a method
2305// specific to the region to round the values. However, round(double) first
2306// calculates the round of the absolute value and then adds the sign back while
2307// round(float) directly rounds the value with sign.
2308SDValue NVPTXTargetLowering::LowerFROUND64(SDValue Op,
2309 SelectionDAG &DAG) const {
2310 SDLoc SL(Op);
2311 SDValue A = Op.getOperand(i: 0);
2312 EVT VT = Op.getValueType();
2313
2314 SDValue AbsA = DAG.getNode(Opcode: ISD::FABS, DL: SL, VT, Operand: A);
2315
2316 // double RoundedA = (double) (int) (abs(A) + 0.5f);
2317 SDValue AdjustedA = DAG.getNode(Opcode: ISD::FADD, DL: SL, VT, N1: AbsA,
2318 N2: DAG.getConstantFP(Val: 0.5, DL: SL, VT));
2319 SDValue RoundedA = DAG.getNode(Opcode: ISD::FTRUNC, DL: SL, VT, Operand: AdjustedA);
2320
2321 // RoundedA = abs(A) < 0.5 ? (double)0 : RoundedA;
2322 EVT SetCCVT = getSetCCResultType(DL: DAG.getDataLayout(), Ctx&: *DAG.getContext(), VT);
2323 SDValue IsSmall =DAG.getSetCC(DL: SL, VT: SetCCVT, LHS: AbsA,
2324 RHS: DAG.getConstantFP(Val: 0.5, DL: SL, VT), Cond: ISD::SETOLT);
2325 RoundedA = DAG.getNode(Opcode: ISD::SELECT, DL: SL, VT, N1: IsSmall,
2326 N2: DAG.getConstantFP(Val: 0, DL: SL, VT),
2327 N3: RoundedA);
2328
2329 // Add sign to rounded_A
2330 RoundedA = DAG.getNode(Opcode: ISD::FCOPYSIGN, DL: SL, VT, N1: RoundedA, N2: A);
2331 DAG.getNode(Opcode: ISD::FTRUNC, DL: SL, VT, Operand: A);
2332
2333 // RoundedA = abs(A) > 0x1.0p52 ? A : RoundedA;
2334 SDValue IsLarge =
2335 DAG.getSetCC(DL: SL, VT: SetCCVT, LHS: AbsA, RHS: DAG.getConstantFP(Val: pow(x: 2.0, y: 52.0), DL: SL, VT),
2336 Cond: ISD::SETOGT);
2337 return DAG.getNode(Opcode: ISD::SELECT, DL: SL, VT, N1: IsLarge, N2: A, N3: RoundedA);
2338}
2339
2340static SDValue PromoteBinOpToF32(SDNode *N, SelectionDAG &DAG) {
2341 EVT VT = N->getValueType(ResNo: 0);
2342 EVT NVT = MVT::f32;
2343 if (VT.isVector()) {
2344 NVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: NVT, EC: VT.getVectorElementCount());
2345 }
2346 SDLoc DL(N);
2347 SDValue Tmp0 = DAG.getFPExtendOrRound(Op: N->getOperand(Num: 0), DL, VT: NVT);
2348 SDValue Tmp1 = DAG.getFPExtendOrRound(Op: N->getOperand(Num: 1), DL, VT: NVT);
2349 SDValue Res = DAG.getNode(Opcode: N->getOpcode(), DL, VT: NVT, N1: Tmp0, N2: Tmp1, Flags: N->getFlags());
2350 return DAG.getFPExtendOrRound(Op: Res, DL, VT);
2351}
2352
2353SDValue NVPTXTargetLowering::PromoteBinOpIfF32FTZ(SDValue Op,
2354 SelectionDAG &DAG) const {
2355 if (useF32FTZ(MF: DAG.getMachineFunction())) {
2356 return PromoteBinOpToF32(N: Op.getNode(), DAG);
2357 }
2358 return Op;
2359}
2360
2361SDValue NVPTXTargetLowering::LowerINT_TO_FP(SDValue Op,
2362 SelectionDAG &DAG) const {
2363 assert(STI.getSmVersion() < 90 || STI.getPTXVersion() < 78);
2364
2365 if (Op.getValueType() == MVT::bf16) {
2366 SDLoc Loc(Op);
2367 return DAG.getNode(
2368 Opcode: ISD::FP_ROUND, DL: Loc, VT: MVT::bf16,
2369 N1: DAG.getNode(Opcode: Op.getOpcode(), DL: Loc, VT: MVT::f32, Operand: Op.getOperand(i: 0)),
2370 N2: DAG.getIntPtrConstant(Val: 0, DL: Loc, /*isTarget=*/true));
2371 }
2372
2373 // Everything else is considered legal.
2374 return Op;
2375}
2376
2377SDValue NVPTXTargetLowering::LowerFP_TO_INT(SDValue Op,
2378 SelectionDAG &DAG) const {
2379 assert(STI.getSmVersion() < 90 || STI.getPTXVersion() < 78);
2380
2381 if (Op.getOperand(i: 0).getValueType() == MVT::bf16) {
2382 SDLoc Loc(Op);
2383 return DAG.getNode(
2384 Opcode: Op.getOpcode(), DL: Loc, VT: Op.getValueType(),
2385 Operand: DAG.getNode(Opcode: ISD::FP_EXTEND, DL: Loc, VT: MVT::f32, Operand: Op.getOperand(i: 0)));
2386 }
2387
2388 // Everything else is considered legal.
2389 return Op;
2390}
2391
2392SDValue NVPTXTargetLowering::LowerFP_ROUND(SDValue Op,
2393 SelectionDAG &DAG) const {
2394 EVT NarrowVT = Op.getValueType();
2395 SDValue Wide = Op.getOperand(i: 0);
2396 EVT WideVT = Wide.getValueType();
2397 if (NarrowVT.getScalarType() == MVT::bf16) {
2398 const TargetLowering *TLI = STI.getTargetLowering();
2399 if (STI.getSmVersion() < 80 || STI.getPTXVersion() < 70) {
2400 return TLI->expandFP_ROUND(Node: Op.getNode(), DAG);
2401 }
2402 if (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78) {
2403 // This combination was the first to support f32 -> bf16.
2404 if (STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 70) {
2405 if (WideVT.getScalarType() == MVT::f32) {
2406 return Op;
2407 }
2408 if (WideVT.getScalarType() == MVT::f64) {
2409 SDLoc Loc(Op);
2410 // Round-inexact-to-odd f64 to f32, then do the final rounding using
2411 // the hardware f32 -> bf16 instruction.
2412 SDValue rod = TLI->expandRoundInexactToOdd(
2413 ResultVT: WideVT.changeElementType(Context&: *DAG.getContext(), EltVT: MVT::f32), Op: Wide, DL: Loc,
2414 DAG);
2415 return DAG.getFPExtendOrRound(Op: rod, DL: Loc, VT: NarrowVT);
2416 }
2417 }
2418 return TLI->expandFP_ROUND(Node: Op.getNode(), DAG);
2419 }
2420 }
2421
2422 // Everything else is considered legal.
2423 return Op;
2424}
2425
2426SDValue NVPTXTargetLowering::LowerFP_EXTEND(SDValue Op,
2427 SelectionDAG &DAG) const {
2428 SDValue Narrow = Op.getOperand(i: 0);
2429 EVT NarrowVT = Narrow.getValueType();
2430 EVT WideVT = Op.getValueType();
2431 if (NarrowVT.getScalarType() == MVT::bf16) {
2432 if (WideVT.getScalarType() == MVT::f32 &&
2433 (STI.getSmVersion() < 80 || STI.getPTXVersion() < 71)) {
2434 SDLoc Loc(Op);
2435 return DAG.getNode(Opcode: ISD::BF16_TO_FP, DL: Loc, VT: WideVT, Operand: Narrow);
2436 }
2437 if (WideVT.getScalarType() == MVT::f64 &&
2438 (STI.getSmVersion() < 90 || STI.getPTXVersion() < 78)) {
2439 EVT F32 = NarrowVT.changeElementType(Context&: *DAG.getContext(), EltVT: MVT::f32);
2440 SDLoc Loc(Op);
2441 if (STI.getSmVersion() >= 80 && STI.getPTXVersion() >= 71) {
2442 Op = DAG.getNode(Opcode: ISD::FP_EXTEND, DL: Loc, VT: F32, Operand: Narrow);
2443 } else {
2444 Op = DAG.getNode(Opcode: ISD::BF16_TO_FP, DL: Loc, VT: F32, Operand: Narrow);
2445 }
2446 return DAG.getNode(Opcode: ISD::FP_EXTEND, DL: Loc, VT: WideVT, Operand: Op);
2447 }
2448 }
2449
2450 // Everything else is considered legal.
2451 return Op;
2452}
2453
2454static SDValue LowerVectorArith(SDValue Op, SelectionDAG &DAG) {
2455 SDLoc DL(Op);
2456 if (Op.getValueType() != MVT::v2i16)
2457 return Op;
2458 EVT EltVT = Op.getValueType().getVectorElementType();
2459 SmallVector<SDValue> VecElements;
2460 for (int I = 0, E = Op.getValueType().getVectorNumElements(); I < E; I++) {
2461 SmallVector<SDValue> ScalarArgs;
2462 llvm::transform(Range: Op->ops(), d_first: std::back_inserter(x&: ScalarArgs),
2463 F: [&](const SDUse &O) {
2464 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT,
2465 N1: O.get(), N2: DAG.getIntPtrConstant(Val: I, DL));
2466 });
2467 VecElements.push_back(Elt: DAG.getNode(Opcode: Op.getOpcode(), DL, VT: EltVT, Ops: ScalarArgs));
2468 }
2469 SDValue V =
2470 DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT: Op.getValueType(), Ops: VecElements);
2471 return V;
2472}
2473
2474static SDValue lowerTcgen05St(SDValue Op, SelectionDAG &DAG,
2475 bool hasOffset = false) {
2476 // skip lowering if the vector operand is already legalized
2477 if (!Op->getOperand(Num: hasOffset ? 4 : 3).getValueType().isVector())
2478 return Op;
2479
2480 SDNode *N = Op.getNode();
2481 SDLoc DL(N);
2482 SmallVector<SDValue, 32> Ops;
2483
2484 // split the vector argument
2485 for (size_t I = 0; I < N->getNumOperands(); I++) {
2486 SDValue Val = N->getOperand(Num: I);
2487 EVT ValVT = Val.getValueType();
2488 if (ValVT.isVector()) {
2489 EVT EltVT = ValVT.getVectorElementType();
2490 for (unsigned J = 0, NElts = ValVT.getVectorNumElements(); J < NElts; J++)
2491 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Val,
2492 N2: DAG.getIntPtrConstant(Val: J, DL)));
2493 } else
2494 Ops.push_back(Elt: Val);
2495 }
2496
2497 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(Val: N);
2498 SDValue Tcgen05StNode =
2499 DAG.getMemIntrinsicNode(Opcode: ISD::INTRINSIC_VOID, dl: DL, VTList: N->getVTList(), Ops,
2500 MemVT: MemSD->getMemoryVT(), MMO: MemSD->getMemOperand());
2501
2502 return Tcgen05StNode;
2503}
2504
2505static SDValue lowerBSWAP(SDValue Op, SelectionDAG &DAG) {
2506 SDLoc DL(Op);
2507 SDValue Src = Op.getOperand(i: 0);
2508 EVT VT = Op.getValueType();
2509
2510 switch (VT.getSimpleVT().SimpleTy) {
2511 case MVT::i16: {
2512 SDValue Extended = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: MVT::i32, Operand: Src);
2513 SDValue Swapped =
2514 getPRMT(A: Extended, B: DAG.getConstant(Val: 0, DL, VT: MVT::i32), Selector: 0x7701, DL, DAG);
2515 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::i16, Operand: Swapped);
2516 }
2517 case MVT::i32: {
2518 return getPRMT(A: Src, B: DAG.getConstant(Val: 0, DL, VT: MVT::i32), Selector: 0x0123, DL, DAG);
2519 }
2520 case MVT::v2i16: {
2521 SDValue Converted = DAG.getBitcast(VT: MVT::i32, V: Src);
2522 SDValue Swapped =
2523 getPRMT(A: Converted, B: DAG.getConstant(Val: 0, DL, VT: MVT::i32), Selector: 0x2301, DL, DAG);
2524 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2i16, Operand: Swapped);
2525 }
2526 case MVT::i64: {
2527 SDValue UnpackSrc =
2528 DAG.getNode(Opcode: NVPTXISD::UNPACK_VECTOR, DL, ResultTys: {MVT::i32, MVT::i32}, Ops: Src);
2529 SDValue SwappedLow =
2530 getPRMT(A: UnpackSrc.getValue(R: 0), B: DAG.getConstant(Val: 0, DL, VT: MVT::i32), Selector: 0x0123,
2531 DL, DAG);
2532 SDValue SwappedHigh =
2533 getPRMT(A: UnpackSrc.getValue(R: 1), B: DAG.getConstant(Val: 0, DL, VT: MVT::i32), Selector: 0x0123,
2534 DL, DAG);
2535 return DAG.getNode(Opcode: NVPTXISD::BUILD_VECTOR, DL, VT: MVT::i64,
2536 Ops: {SwappedHigh, SwappedLow});
2537 }
2538 default:
2539 llvm_unreachable("unsupported type for bswap");
2540 }
2541}
2542
2543static SDValue lowerStAsyncWithMbarrier(SDValue Op, SelectionDAG &DAG) {
2544 const Function &Fn = DAG.getMachineFunction().getFunction();
2545 SDNode *N = Op.getNode();
2546 SDLoc DL(N);
2547 Intrinsic::ID IntrinsicID = N->getConstantOperandVal(Num: 1);
2548 SDValue DestAddr = N->getOperand(Num: 2);
2549 SDValue Value = N->getOperand(Num: 3);
2550 SDValue MbarAddr = N->getOperand(Num: 4);
2551
2552 MVT ValueVT = Value.getSimpleValueType();
2553
2554 if (ValueVT == MVT::i32 || ValueVT == MVT::i64)
2555 return Op;
2556
2557 if (ValueVT == MVT::i128) {
2558 SDValue Cast = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2i64, Operand: Value);
2559 SDValue ValueLo = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i64, N1: Cast,
2560 N2: DAG.getIntPtrConstant(Val: 0, DL));
2561 SDValue ValueHi = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i64, N1: Cast,
2562 N2: DAG.getIntPtrConstant(Val: 1, DL));
2563 SDValue Ops[] = {N->getOperand(Num: 0), DestAddr, ValueLo, ValueHi, MbarAddr};
2564 return DAG.getNode(Opcode: NVPTXISD::ST_ASYNC_MBARRIER_B128, DL, VT: MVT::Other, Ops);
2565 }
2566
2567 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
2568 Fn,
2569 Twine("unsupported argument type ") + llvm::EVT(ValueVT).getEVTString() +
2570 " for " + llvm::Intrinsic::getName(id: IntrinsicID) + " intrinsic",
2571 DiagnosticLocation(DL.getDebugLoc())));
2572 return Op.getOperand(i: 0); // Return only the chain
2573}
2574
2575static SDValue lowerStAsyncRelease(SDValue Op, SelectionDAG &DAG) {
2576 const Function &Fn = DAG.getMachineFunction().getFunction();
2577 SDNode *N = Op.getNode();
2578 SDLoc DL(N);
2579 Intrinsic::ID IntrinsicID = N->getConstantOperandVal(Num: 1);
2580 SDValue DestAddr = N->getOperand(Num: 2);
2581 SDValue Value = N->getOperand(Num: 3);
2582
2583 MVT ValueVT = Value.getSimpleValueType();
2584
2585 if (ValueVT == MVT::i16 || ValueVT == MVT::i32 || ValueVT == MVT::i64)
2586 return Op;
2587
2588 if (ValueVT == MVT::i8) {
2589 unsigned OpCode;
2590 switch (IntrinsicID) {
2591 case Intrinsic::nvvm_st_async_sys:
2592 OpCode = NVPTXISD::ST_ASYNC_SYS_B8;
2593 break;
2594 case Intrinsic::nvvm_st_async_gpu:
2595 OpCode = NVPTXISD::ST_ASYNC_GPU_B8;
2596 break;
2597 case Intrinsic::nvvm_st_async_mmio_sys:
2598 OpCode = NVPTXISD::ST_ASYNC_MMIO_SYS_B8;
2599 break;
2600 default:
2601 llvm_unreachable("unexpected intrinsic ID for st.async.release");
2602 }
2603
2604 Value = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: MVT::i16, Operand: Value);
2605
2606 // The `.mmio` variant has no multimem form and therefore no `isMultimem`
2607 // operand.
2608 if (IntrinsicID == Intrinsic::nvvm_st_async_mmio_sys) {
2609 SDValue Ops[] = {N->getOperand(Num: 0), DestAddr, Value};
2610 return DAG.getNode(Opcode: OpCode, DL, VT: MVT::Other, Ops);
2611 }
2612
2613 SDValue IsMultimem =
2614 DAG.getTargetConstant(Val: N->getConstantOperandVal(Num: 4), DL, VT: MVT::i1);
2615 SDValue Ops[] = {N->getOperand(Num: 0), DestAddr, Value, IsMultimem};
2616 return DAG.getNode(Opcode: OpCode, DL, VT: MVT::Other, Ops);
2617 }
2618
2619 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
2620 Fn,
2621 Twine("unsupported argument type ") + llvm::EVT(ValueVT).getEVTString() +
2622 " for " + llvm::Intrinsic::getName(id: IntrinsicID) + " intrinsic",
2623 DiagnosticLocation(DL.getDebugLoc())));
2624 return Op.getOperand(i: 0); // Return only the chain
2625}
2626
2627static unsigned getTcgen05MMADisableOutputLane(unsigned IID) {
2628 switch (IID) {
2629 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
2630 return NVPTXISD::TCGEN05_MMA_SHARED_DISABLE_OUTPUT_LANE_CG1;
2631 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
2632 return NVPTXISD::TCGEN05_MMA_SHARED_DISABLE_OUTPUT_LANE_CG2;
2633 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
2634 return NVPTXISD::TCGEN05_MMA_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2635 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
2636 return NVPTXISD::TCGEN05_MMA_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2637 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
2638 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG1;
2639 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
2640 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG2;
2641 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
2642 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2643 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
2644 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2645 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
2646 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2647 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
2648 return NVPTXISD::TCGEN05_MMA_TENSOR_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2649 case Intrinsic::
2650 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
2651 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2652 case Intrinsic::
2653 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
2654 return NVPTXISD::TCGEN05_MMA_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2655 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
2656 return NVPTXISD::TCGEN05_MMA_SP_SHARED_DISABLE_OUTPUT_LANE_CG1;
2657 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
2658 return NVPTXISD::TCGEN05_MMA_SP_SHARED_DISABLE_OUTPUT_LANE_CG2;
2659 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
2660 return NVPTXISD::TCGEN05_MMA_SP_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2661 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
2662 return NVPTXISD::TCGEN05_MMA_SP_SHARED_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2663 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
2664 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG1;
2665 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
2666 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG2;
2667 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
2668 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2669 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
2670 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2671 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
2672 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1;
2673 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
2674 return NVPTXISD::TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2;
2675 case Intrinsic::
2676 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift:
2677 return NVPTXISD::
2678 TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG1_ASHIFT;
2679 case Intrinsic::
2680 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift:
2681 return NVPTXISD::
2682 TCGEN05_MMA_SP_TENSOR_SCALE_D_DISABLE_OUTPUT_LANE_CG2_ASHIFT;
2683 };
2684 llvm_unreachable("unhandled tcgen05.mma.disable_output_lane intrinsic");
2685}
2686
2687static SDValue LowerTcgen05MMADisableOutputLane(SDValue Op, SelectionDAG &DAG) {
2688 SDNode *N = Op.getNode();
2689 SDLoc DL(N);
2690 unsigned IID = cast<ConstantSDNode>(Val: N->getOperand(Num: 1))->getZExtValue();
2691
2692 SmallVector<SDValue, 16> Ops;
2693 // split the vector argument
2694 for (size_t I = 0; I < N->getNumOperands(); I++) {
2695 if (I == 1)
2696 continue; // skip IID
2697 SDValue Val = N->getOperand(Num: I);
2698 EVT ValVT = Val.getValueType();
2699 if (ValVT.isVector()) {
2700 EVT EltVT = ValVT.getVectorElementType();
2701 for (unsigned J = 0, NElts = ValVT.getVectorNumElements(); J < NElts; J++)
2702 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Val,
2703 N2: DAG.getIntPtrConstant(Val: J, DL)));
2704 } else
2705 Ops.push_back(Elt: Val);
2706 }
2707
2708 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(Val: N);
2709 SDValue Tcgen05MMANode = DAG.getMemIntrinsicNode(
2710 Opcode: getTcgen05MMADisableOutputLane(IID), dl: DL, VTList: N->getVTList(), Ops,
2711 MemVT: MemSD->getMemoryVT(), MMO: MemSD->getMemOperand());
2712
2713 return Tcgen05MMANode;
2714}
2715
2716// Lower vector return type of tcgen05.ld intrinsics
2717static std::optional<std::pair<SDValue, SDValue>>
2718lowerTcgen05Ld(SDNode *N, SelectionDAG &DAG, bool HasOffset = false) {
2719 SDLoc DL(N);
2720 EVT ResVT = N->getValueType(ResNo: 0);
2721 if (!ResVT.isVector())
2722 return {}; // already legalized.
2723
2724 const unsigned NumElts = ResVT.getVectorNumElements();
2725
2726 // Create the return type of the instructions
2727 SmallVector<EVT, 5> ListVTs;
2728 for (unsigned i = 0; i < NumElts; ++i)
2729 ListVTs.push_back(Elt: MVT::i32);
2730
2731 ListVTs.push_back(Elt: N->getValueType(ResNo: 1)); // Chain
2732
2733 SDVTList ResVTs = DAG.getVTList(VTs: ListVTs);
2734
2735 SmallVector<SDValue, 8> Ops{N->getOperand(Num: 0), N->getOperand(Num: 1),
2736 N->getOperand(Num: 2)};
2737
2738 if (HasOffset) {
2739 Ops.push_back(Elt: N->getOperand(Num: 3)); // offset
2740 Ops.push_back(Elt: N->getOperand(Num: 4)); // Pack flag
2741 } else
2742 Ops.push_back(Elt: N->getOperand(Num: 3)); // Pack flag
2743
2744 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(Val: N);
2745 SDValue NewNode =
2746 DAG.getMemIntrinsicNode(Opcode: ISD::INTRINSIC_W_CHAIN, dl: DL, VTList: ResVTs, Ops,
2747 MemVT: MemSD->getMemoryVT(), MMO: MemSD->getMemOperand());
2748
2749 // split the vector result
2750 SmallVector<SDValue, 4> ScalarRes;
2751 for (unsigned i = 0; i < NumElts; ++i) {
2752 SDValue Res = NewNode.getValue(R: i);
2753 ScalarRes.push_back(Elt: Res);
2754 }
2755
2756 SDValue Chain = NewNode.getValue(R: NumElts);
2757 SDValue BuildVector = DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT: ResVT, Ops: ScalarRes);
2758 return {{BuildVector, Chain}};
2759}
2760
2761static SDValue reportInvalidTensormapReplaceUsage(SDValue Op, SelectionDAG &DAG,
2762 unsigned Val) {
2763 SDNode *N = Op.getNode();
2764 SDLoc DL(N);
2765
2766 const Function &Fn = DAG.getMachineFunction().getFunction();
2767
2768 unsigned AS = 0;
2769 if (auto *MemN = dyn_cast<MemIntrinsicSDNode>(Val: N))
2770 AS = MemN->getAddressSpace();
2771 Type *PtrTy = PointerType::get(C&: *DAG.getContext(), AddressSpace: AS);
2772 Module *M = DAG.getMachineFunction().getFunction().getParent();
2773
2774 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
2775 Fn,
2776 "Intrinsic " +
2777 Intrinsic::getName(Id: N->getConstantOperandVal(Num: 1), OverloadTys: {PtrTy}, M) +
2778 " with value " + Twine(Val) +
2779 " is not supported on the given target.",
2780 DL.getDebugLoc()));
2781 return Op.getOperand(i: 0);
2782}
2783
2784static SDValue lowerTensormapReplaceElemtype(SDValue Op, SelectionDAG &DAG) {
2785 SDNode *N = Op.getNode();
2786 SDLoc DL(N);
2787
2788 // immediate argument representing elemtype
2789 unsigned Val = N->getConstantOperandVal(Num: 3);
2790
2791 if (!DAG.getSubtarget<NVPTXSubtarget>().hasTensormapReplaceElemtypeSupport(
2792 value: Val))
2793 return reportInvalidTensormapReplaceUsage(Op, DAG, Val);
2794
2795 return Op;
2796}
2797
2798static SDValue lowerTensormapReplaceSwizzleMode(SDValue Op, SelectionDAG &DAG) {
2799 SDNode *N = Op.getNode();
2800 SDLoc DL(N);
2801
2802 // immediate argument representing swizzle mode
2803 unsigned Val = N->getConstantOperandVal(Num: 3);
2804
2805 if (!DAG.getSubtarget<NVPTXSubtarget>().hasTensormapReplaceSwizzleModeSupport(
2806 value: Val))
2807 return reportInvalidTensormapReplaceUsage(Op, DAG, Val);
2808
2809 return Op;
2810}
2811
2812static SDValue lowerIntrinsicVoid(SDValue Op, SelectionDAG &DAG) {
2813 SDNode *N = Op.getNode();
2814 SDValue Intrin = N->getOperand(Num: 1);
2815
2816 // Get the intrinsic ID
2817 unsigned IntrinNo = cast<ConstantSDNode>(Val: Intrin.getNode())->getZExtValue();
2818 switch (IntrinNo) {
2819 default:
2820 break;
2821 case Intrinsic::nvvm_st_async:
2822 return lowerStAsyncWithMbarrier(Op, DAG);
2823 case Intrinsic::nvvm_st_async_sys:
2824 case Intrinsic::nvvm_st_async_gpu:
2825 case Intrinsic::nvvm_st_async_mmio_sys:
2826 return lowerStAsyncRelease(Op, DAG);
2827
2828 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
2829 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
2830 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
2831 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
2832 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
2833 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
2834 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
2835 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
2836 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
2837 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
2838 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
2839 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
2840 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
2841 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
2842 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
2843 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
2844 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
2845 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
2846 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
2847 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
2848 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
2849 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
2850 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
2851 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
2852 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
2853 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
2854 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
2855 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
2856 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
2857 return lowerTcgen05St(Op, DAG);
2858 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1:
2859 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2:
2860 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4:
2861 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8:
2862 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16:
2863 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32:
2864 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64:
2865 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128:
2866 return lowerTcgen05St(Op, DAG, /* hasOffset */ true);
2867 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
2868 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
2869 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
2870 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
2871 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
2872 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
2873 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
2874 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
2875 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
2876 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
2877 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
2878 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
2879 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
2880 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
2881 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
2882 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
2883 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
2884 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
2885 case Intrinsic::
2886 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
2887 case Intrinsic::
2888 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
2889 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
2890 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
2891 case Intrinsic::
2892 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift:
2893 case Intrinsic::
2894 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift:
2895 return LowerTcgen05MMADisableOutputLane(Op, DAG);
2896 case Intrinsic::nvvm_tensormap_replace_elemtype:
2897 return lowerTensormapReplaceElemtype(Op, DAG);
2898 case Intrinsic::nvvm_tensormap_replace_swizzle_mode:
2899 return lowerTensormapReplaceSwizzleMode(Op, DAG);
2900 }
2901 return Op;
2902}
2903
2904static SDValue LowerClusterLaunchControlQueryCancel(SDValue Op,
2905 SelectionDAG &DAG) {
2906
2907 SDNode *N = Op.getNode();
2908 if (N->getOperand(Num: 1).getValueType() != MVT::i128) {
2909 // return, if the operand is already lowered
2910 return SDValue();
2911 }
2912
2913 unsigned IID =
2914 cast<ConstantSDNode>(Val: N->getOperand(Num: 0).getNode())->getZExtValue();
2915 auto Opcode = [&]() {
2916 switch (IID) {
2917 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_is_canceled:
2918 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_IS_CANCELED;
2919 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_x:
2920 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_X;
2921 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_y:
2922 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Y;
2923 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_z:
2924 return NVPTXISD::CLUSTERLAUNCHCONTROL_QUERY_CANCEL_GET_FIRST_CTAID_Z;
2925 default:
2926 llvm_unreachable("unsupported/unhandled intrinsic");
2927 }
2928 }();
2929
2930 SDLoc DL(N);
2931 SDValue TryCancelResponse = N->getOperand(Num: 1);
2932 SDValue Cast = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2i64, Operand: TryCancelResponse);
2933 SDValue TryCancelResponse0 =
2934 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i64, N1: Cast,
2935 N2: DAG.getIntPtrConstant(Val: 0, DL));
2936 SDValue TryCancelResponse1 =
2937 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i64, N1: Cast,
2938 N2: DAG.getIntPtrConstant(Val: 1, DL));
2939
2940 return DAG.getNode(Opcode, DL, VTList: N->getVTList(),
2941 Ops: {TryCancelResponse0, TryCancelResponse1});
2942}
2943
2944static SDValue lowerCvtRSIntrinsics(SDValue Op, SelectionDAG &DAG) {
2945 SDNode *N = Op.getNode();
2946 SDLoc DL(N);
2947 SDValue F32Vec = N->getOperand(Num: 1);
2948 SDValue RBits = N->getOperand(Num: 2);
2949
2950 unsigned IntrinsicID = N->getConstantOperandVal(Num: 0);
2951
2952 // Extract the 4 float elements from the vector
2953 SmallVector<SDValue, 6> Ops;
2954 for (unsigned i = 0; i < 4; ++i)
2955 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: F32Vec,
2956 N2: DAG.getIntPtrConstant(Val: i, DL)));
2957
2958 using NVPTX::PTXCvtMode::CvtMode;
2959
2960 auto [OpCode, RetTy, CvtModeFlag] =
2961 [&]() -> std::tuple<unsigned, MVT::SimpleValueType, uint32_t> {
2962 switch (IntrinsicID) {
2963 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_relu_satfinite:
2964 return {NVPTXISD::CVT_E4M3X4_F32X4_RS_SF, MVT::v4i8,
2965 CvtMode::RS | CvtMode::RELU_FLAG};
2966 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_satfinite:
2967 return {NVPTXISD::CVT_E4M3X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
2968 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_relu_satfinite:
2969 return {NVPTXISD::CVT_E5M2X4_F32X4_RS_SF, MVT::v4i8,
2970 CvtMode::RS | CvtMode::RELU_FLAG};
2971 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_satfinite:
2972 return {NVPTXISD::CVT_E5M2X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
2973 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_relu_satfinite:
2974 return {NVPTXISD::CVT_E2M3X4_F32X4_RS_SF, MVT::v4i8,
2975 CvtMode::RS | CvtMode::RELU_FLAG};
2976 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_satfinite:
2977 return {NVPTXISD::CVT_E2M3X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
2978 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_relu_satfinite:
2979 return {NVPTXISD::CVT_E3M2X4_F32X4_RS_SF, MVT::v4i8,
2980 CvtMode::RS | CvtMode::RELU_FLAG};
2981 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_satfinite:
2982 return {NVPTXISD::CVT_E3M2X4_F32X4_RS_SF, MVT::v4i8, CvtMode::RS};
2983 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_relu_satfinite:
2984 return {NVPTXISD::CVT_E2M1X4_F32X4_RS_SF, MVT::i16,
2985 CvtMode::RS | CvtMode::RELU_FLAG};
2986 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_satfinite:
2987 return {NVPTXISD::CVT_E2M1X4_F32X4_RS_SF, MVT::i16, CvtMode::RS};
2988 default:
2989 llvm_unreachable("unsupported/unhandled intrinsic");
2990 }
2991 }();
2992
2993 Ops.push_back(Elt: RBits);
2994 Ops.push_back(Elt: DAG.getConstant(Val: CvtModeFlag, DL, VT: MVT::i32));
2995
2996 return DAG.getNode(Opcode: OpCode, DL, VT: RetTy, Ops);
2997}
2998
2999static SDValue lowerPrmtIntrinsic(SDValue Op, SelectionDAG &DAG) {
3000 const unsigned Mode = [&]() {
3001 switch (Op->getConstantOperandVal(Num: 0)) {
3002 case Intrinsic::nvvm_prmt:
3003 return NVPTX::PTXPrmtMode::NONE;
3004 case Intrinsic::nvvm_prmt_b4e:
3005 return NVPTX::PTXPrmtMode::B4E;
3006 case Intrinsic::nvvm_prmt_ecl:
3007 return NVPTX::PTXPrmtMode::ECL;
3008 case Intrinsic::nvvm_prmt_ecr:
3009 return NVPTX::PTXPrmtMode::ECR;
3010 case Intrinsic::nvvm_prmt_f4e:
3011 return NVPTX::PTXPrmtMode::F4E;
3012 case Intrinsic::nvvm_prmt_rc16:
3013 return NVPTX::PTXPrmtMode::RC16;
3014 case Intrinsic::nvvm_prmt_rc8:
3015 return NVPTX::PTXPrmtMode::RC8;
3016 default:
3017 llvm_unreachable("unsupported/unhandled intrinsic");
3018 }
3019 }();
3020 SDLoc DL(Op);
3021 SDValue A = Op->getOperand(Num: 1);
3022 SDValue B = Op.getNumOperands() == 4 ? Op.getOperand(i: 2)
3023 : DAG.getConstant(Val: 0, DL, VT: MVT::i32);
3024 SDValue Selector = (Op->op_end() - 1)->get();
3025 return getPRMT(A, B, Selector, DL, DAG, Mode);
3026}
3027
3028#define TCGEN05_LD_RED_INTR(SHAPE, NUM, TYPE) \
3029 Intrinsic::nvvm_tcgen05_ld_red_##SHAPE##_x##NUM##_##TYPE
3030
3031#define TCGEN05_LD_RED_INST(SHAPE, NUM, TYPE) \
3032 NVPTXISD::TCGEN05_LD_RED_##SHAPE##_X##NUM##_##TYPE
3033
3034static unsigned getTcgen05LdRedID(Intrinsic::ID IID) {
3035 switch (IID) {
3036 case TCGEN05_LD_RED_INTR(32x32b, 2, f32):
3037 return TCGEN05_LD_RED_INST(32x32b, 2, F32);
3038 case TCGEN05_LD_RED_INTR(32x32b, 4, f32):
3039 return TCGEN05_LD_RED_INST(32x32b, 4, F32);
3040 case TCGEN05_LD_RED_INTR(32x32b, 8, f32):
3041 return TCGEN05_LD_RED_INST(32x32b, 8, F32);
3042 case TCGEN05_LD_RED_INTR(32x32b, 16, f32):
3043 return TCGEN05_LD_RED_INST(32x32b, 16, F32);
3044 case TCGEN05_LD_RED_INTR(32x32b, 32, f32):
3045 return TCGEN05_LD_RED_INST(32x32b, 32, F32);
3046 case TCGEN05_LD_RED_INTR(32x32b, 64, f32):
3047 return TCGEN05_LD_RED_INST(32x32b, 64, F32);
3048 case TCGEN05_LD_RED_INTR(32x32b, 128, f32):
3049 return TCGEN05_LD_RED_INST(32x32b, 128, F32);
3050 case TCGEN05_LD_RED_INTR(16x32bx2, 2, f32):
3051 return TCGEN05_LD_RED_INST(16x32bx2, 2, F32);
3052 case TCGEN05_LD_RED_INTR(16x32bx2, 4, f32):
3053 return TCGEN05_LD_RED_INST(16x32bx2, 4, F32);
3054 case TCGEN05_LD_RED_INTR(16x32bx2, 8, f32):
3055 return TCGEN05_LD_RED_INST(16x32bx2, 8, F32);
3056 case TCGEN05_LD_RED_INTR(16x32bx2, 16, f32):
3057 return TCGEN05_LD_RED_INST(16x32bx2, 16, F32);
3058 case TCGEN05_LD_RED_INTR(16x32bx2, 32, f32):
3059 return TCGEN05_LD_RED_INST(16x32bx2, 32, F32);
3060 case TCGEN05_LD_RED_INTR(16x32bx2, 64, f32):
3061 return TCGEN05_LD_RED_INST(16x32bx2, 64, F32);
3062 case TCGEN05_LD_RED_INTR(16x32bx2, 128, f32):
3063 return TCGEN05_LD_RED_INST(16x32bx2, 128, F32);
3064 case TCGEN05_LD_RED_INTR(32x32b, 2, i32):
3065 return TCGEN05_LD_RED_INST(32x32b, 2, I32);
3066 case TCGEN05_LD_RED_INTR(32x32b, 4, i32):
3067 return TCGEN05_LD_RED_INST(32x32b, 4, I32);
3068 case TCGEN05_LD_RED_INTR(32x32b, 8, i32):
3069 return TCGEN05_LD_RED_INST(32x32b, 8, I32);
3070 case TCGEN05_LD_RED_INTR(32x32b, 16, i32):
3071 return TCGEN05_LD_RED_INST(32x32b, 16, I32);
3072 case TCGEN05_LD_RED_INTR(32x32b, 32, i32):
3073 return TCGEN05_LD_RED_INST(32x32b, 32, I32);
3074 case TCGEN05_LD_RED_INTR(32x32b, 64, i32):
3075 return TCGEN05_LD_RED_INST(32x32b, 64, I32);
3076 case TCGEN05_LD_RED_INTR(32x32b, 128, i32):
3077 return TCGEN05_LD_RED_INST(32x32b, 128, I32);
3078 case TCGEN05_LD_RED_INTR(16x32bx2, 2, i32):
3079 return TCGEN05_LD_RED_INST(16x32bx2, 2, I32);
3080 case TCGEN05_LD_RED_INTR(16x32bx2, 4, i32):
3081 return TCGEN05_LD_RED_INST(16x32bx2, 4, I32);
3082 case TCGEN05_LD_RED_INTR(16x32bx2, 8, i32):
3083 return TCGEN05_LD_RED_INST(16x32bx2, 8, I32);
3084 case TCGEN05_LD_RED_INTR(16x32bx2, 16, i32):
3085 return TCGEN05_LD_RED_INST(16x32bx2, 16, I32);
3086 case TCGEN05_LD_RED_INTR(16x32bx2, 32, i32):
3087 return TCGEN05_LD_RED_INST(16x32bx2, 32, I32);
3088 case TCGEN05_LD_RED_INTR(16x32bx2, 64, i32):
3089 return TCGEN05_LD_RED_INST(16x32bx2, 64, I32);
3090 case TCGEN05_LD_RED_INTR(16x32bx2, 128, i32):
3091 return TCGEN05_LD_RED_INST(16x32bx2, 128, I32);
3092 default:
3093 llvm_unreachable("Invalid tcgen05.ld.red intrinsic ID");
3094 }
3095}
3096
3097// Lower vector return type of tcgen05.ld intrinsics
3098static std::optional<std::tuple<SDValue, SDValue, SDValue>>
3099lowerTcgen05LdRed(SDNode *N, SelectionDAG &DAG) {
3100 SDLoc DL(N);
3101 EVT ResVT = N->getValueType(ResNo: 0);
3102 if (!ResVT.isVector())
3103 return {}; // already legalized.
3104
3105 const unsigned NumElts = ResVT.getVectorNumElements();
3106
3107 // Create the return type of the instructions
3108 // +1 represents the reduction value
3109 SmallVector<EVT, 132> ListVTs{
3110 NumElts + 1,
3111 ResVT.getVectorElementType().isFloatingPoint() ? MVT::f32 : MVT::i32};
3112
3113 ListVTs.push_back(Elt: MVT::Other); // Chain
3114
3115 SDVTList ResVTs = DAG.getVTList(VTs: ListVTs);
3116
3117 // Prepare the Operands
3118 SmallVector<SDValue, 8> Ops{N->getOperand(Num: 0)}; // Chain
3119
3120 // skip IID at index 1
3121 for (unsigned i = 2; i < N->getNumOperands(); i++)
3122 Ops.push_back(Elt: N->getOperand(Num: i));
3123
3124 unsigned IID = cast<ConstantSDNode>(Val: N->getOperand(Num: 1))->getZExtValue();
3125 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(Val: N);
3126 SDValue NewNode =
3127 DAG.getMemIntrinsicNode(Opcode: getTcgen05LdRedID(IID), dl: DL, VTList: ResVTs, Ops,
3128 MemVT: MemSD->getMemoryVT(), MMO: MemSD->getMemOperand());
3129
3130 // Split vector result
3131 SmallVector<SDValue, 132> ScalarRes;
3132 for (unsigned i = 0; i < NumElts; ++i) {
3133 SDValue Res = NewNode.getValue(R: i);
3134 ScalarRes.push_back(Elt: Res);
3135 }
3136
3137 SDValue BuildVector = DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT: ResVT, Ops: ScalarRes);
3138 SDValue RedResult = NewNode.getValue(R: NumElts);
3139 SDValue Chain = NewNode.getValue(R: NumElts + 1);
3140 return {{BuildVector, RedResult, Chain}};
3141}
3142
3143static SDValue lowerIntrinsicWChain(SDValue Op, SelectionDAG &DAG) {
3144 switch (Op->getConstantOperandVal(Num: 1)) {
3145 default:
3146 return Op;
3147
3148 // These tcgen05 intrinsics return a v2i32, which is legal, so we have to
3149 // lower them through LowerOperation() instead of ReplaceNodeResults().
3150 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
3151 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
3152 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
3153 if (auto Res = lowerTcgen05Ld(N: Op.getNode(), DAG))
3154 return DAG.getMergeValues(Ops: {Res->first, Res->second}, dl: SDLoc(Op));
3155 return SDValue();
3156
3157 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2:
3158 if (auto Res = lowerTcgen05Ld(N: Op.getNode(), DAG, /*HasOffset=*/true))
3159 return DAG.getMergeValues(Ops: {Res->first, Res->second}, dl: SDLoc(Op));
3160 return SDValue();
3161
3162 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_f32:
3163 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_i32:
3164 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_f32:
3165 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_i32:
3166 if (auto Res = lowerTcgen05LdRed(N: Op.getNode(), DAG))
3167 return DAG.getMergeValues(
3168 Ops: {std::get<0>(t&: *Res), std::get<1>(t&: *Res), std::get<2>(t&: *Res)}, dl: SDLoc(Op));
3169 return SDValue();
3170 }
3171}
3172
3173static SDValue lowerIntrinsicWOChain(SDValue Op, SelectionDAG &DAG) {
3174 switch (Op->getConstantOperandVal(Num: 0)) {
3175 default:
3176 return Op;
3177 case Intrinsic::nvvm_prmt:
3178 case Intrinsic::nvvm_prmt_b4e:
3179 case Intrinsic::nvvm_prmt_ecl:
3180 case Intrinsic::nvvm_prmt_ecr:
3181 case Intrinsic::nvvm_prmt_f4e:
3182 case Intrinsic::nvvm_prmt_rc16:
3183 case Intrinsic::nvvm_prmt_rc8:
3184 return lowerPrmtIntrinsic(Op, DAG);
3185 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_is_canceled:
3186 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_x:
3187 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_y:
3188 case Intrinsic::nvvm_clusterlaunchcontrol_query_cancel_get_first_ctaid_z:
3189 return LowerClusterLaunchControlQueryCancel(Op, DAG);
3190 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_satfinite:
3191 case Intrinsic::nvvm_f32x4_to_e4m3x4_rs_relu_satfinite:
3192 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_satfinite:
3193 case Intrinsic::nvvm_f32x4_to_e5m2x4_rs_relu_satfinite:
3194 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_satfinite:
3195 case Intrinsic::nvvm_f32x4_to_e2m3x4_rs_relu_satfinite:
3196 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_satfinite:
3197 case Intrinsic::nvvm_f32x4_to_e3m2x4_rs_relu_satfinite:
3198 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_satfinite:
3199 case Intrinsic::nvvm_f32x4_to_e2m1x4_rs_relu_satfinite:
3200 return lowerCvtRSIntrinsics(Op, DAG);
3201 }
3202}
3203
3204// In PTX 64-bit CTLZ and CTPOP are supported, but they return a 32-bit value.
3205// Lower these into a node returning the correct type which is zero-extended
3206// back to the correct size.
3207static SDValue lowerCTLZCTPOP(SDValue Op, SelectionDAG &DAG) {
3208 SDValue V = Op->getOperand(Num: 0);
3209 assert(V.getValueType() == MVT::i64 &&
3210 "Unexpected CTLZ/CTPOP type to legalize");
3211
3212 SDLoc DL(Op);
3213 SDValue CT = DAG.getNode(Opcode: Op->getOpcode(), DL, VT: MVT::i32, Operand: V);
3214 return DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL, VT: MVT::i64, Operand: CT, Flags: SDNodeFlags::NonNeg);
3215}
3216
3217static SDValue expandFSH64(SDValue A, SDValue B, SDValue ShiftAmount, SDLoc DL,
3218 unsigned Opcode, SelectionDAG &DAG) {
3219 assert(A.getValueType() == MVT::i64 && B.getValueType() == MVT::i64);
3220
3221 const auto *AmtConst = dyn_cast<ConstantSDNode>(Val&: ShiftAmount);
3222 if (!AmtConst)
3223 return SDValue();
3224 const auto Amt = AmtConst->getZExtValue() & 63;
3225
3226 SDValue UnpackA =
3227 DAG.getNode(Opcode: NVPTXISD::UNPACK_VECTOR, DL, ResultTys: {MVT::i32, MVT::i32}, Ops: A);
3228 SDValue UnpackB =
3229 DAG.getNode(Opcode: NVPTXISD::UNPACK_VECTOR, DL, ResultTys: {MVT::i32, MVT::i32}, Ops: B);
3230
3231 // Arch is Little endiain: 0 = low bits, 1 = high bits
3232 SDValue ALo = UnpackA.getValue(R: 0);
3233 SDValue AHi = UnpackA.getValue(R: 1);
3234 SDValue BLo = UnpackB.getValue(R: 0);
3235 SDValue BHi = UnpackB.getValue(R: 1);
3236
3237 // The bitfeild consists of { AHi : ALo : BHi : BLo }
3238 //
3239 // * FSHL, Amt < 32 - The window will contain { AHi : ALo : BHi }
3240 // * FSHL, Amt >= 32 - The window will contain { ALo : BHi : BLo }
3241 // * FSHR, Amt < 32 - The window will contain { ALo : BHi : BLo }
3242 // * FSHR, Amt >= 32 - The window will contain { AHi : ALo : BHi }
3243 //
3244 // Note that Amt = 0 and Amt = 32 are special cases where 32-bit funnel shifts
3245 // are not needed at all. Amt = 0 is a no-op producing either A or B depending
3246 // on the direction. Amt = 32 can be implemented by a packing and unpacking
3247 // move to select and arrange the 32bit values. For simplicity, these cases
3248 // are not handled here explicitly and instead we rely on DAGCombiner to
3249 // remove the no-op funnel shifts we insert.
3250 auto [High, Mid, Low] = ((Opcode == ISD::FSHL) == (Amt < 32))
3251 ? std::make_tuple(args&: AHi, args&: ALo, args&: BHi)
3252 : std::make_tuple(args&: ALo, args&: BHi, args&: BLo);
3253
3254 SDValue NewAmt = DAG.getConstant(Val: Amt & 31, DL, VT: MVT::i32);
3255 SDValue RHi = DAG.getNode(Opcode, DL, VT: MVT::i32, Ops: {High, Mid, NewAmt});
3256 SDValue RLo = DAG.getNode(Opcode, DL, VT: MVT::i32, Ops: {Mid, Low, NewAmt});
3257
3258 return DAG.getNode(Opcode: NVPTXISD::BUILD_VECTOR, DL, VT: MVT::i64, Ops: {RLo, RHi});
3259}
3260
3261static SDValue lowerFSH(SDValue Op, SelectionDAG &DAG) {
3262 return expandFSH64(A: Op->getOperand(Num: 0), B: Op->getOperand(Num: 1), ShiftAmount: Op->getOperand(Num: 2),
3263 DL: SDLoc(Op), Opcode: Op->getOpcode(), DAG);
3264}
3265
3266static SDValue lowerROT(SDValue Op, SelectionDAG &DAG) {
3267 unsigned Opcode = Op->getOpcode() == ISD::ROTL ? ISD::FSHL : ISD::FSHR;
3268 return expandFSH64(A: Op->getOperand(Num: 0), B: Op->getOperand(Num: 0), ShiftAmount: Op->getOperand(Num: 1),
3269 DL: SDLoc(Op), Opcode, DAG);
3270}
3271
3272static SDValue lowerFREM(SDValue Op, SelectionDAG &DAG) {
3273 // Lower (frem x, y) into (sub x, (mul (ftrunc (div x, y)) y)),
3274 // i.e. "poor man's fmod()". When y is infinite, x is returned. This matches
3275 // the semantics of LLVM's frem.
3276 SDLoc DL(Op);
3277 SDValue X = Op->getOperand(Num: 0);
3278 SDValue Y = Op->getOperand(Num: 1);
3279 EVT Ty = Op.getValueType();
3280 SDNodeFlags Flags = Op->getFlags();
3281
3282 SDValue Div = DAG.getNode(Opcode: ISD::FDIV, DL, VT: Ty, N1: X, N2: Y, Flags);
3283 SDValue Trunc = DAG.getNode(Opcode: ISD::FTRUNC, DL, VT: Ty, Operand: Div, Flags);
3284 SDValue Mul = DAG.getNode(Opcode: ISD::FMUL, DL, VT: Ty, N1: Trunc, N2: Y,
3285 Flags: Flags | SDNodeFlags::AllowContract);
3286 SDValue Sub = DAG.getNode(Opcode: ISD::FSUB, DL, VT: Ty, N1: X, N2: Mul,
3287 Flags: Flags | SDNodeFlags::AllowContract);
3288
3289 if (Flags.hasNoInfs())
3290 return Sub;
3291
3292 // If Y is infinite, return X
3293 SDValue AbsY = DAG.getNode(Opcode: ISD::FABS, DL, VT: Ty, Operand: Y);
3294 SDValue Inf =
3295 DAG.getConstantFP(Val: APFloat::getInf(Sem: Ty.getFltSemantics()), DL, VT: Ty);
3296 SDValue IsInf = DAG.getSetCC(DL, VT: MVT::i1, LHS: AbsY, RHS: Inf, Cond: ISD::SETEQ);
3297 return DAG.getSelect(DL, VT: Ty, Cond: IsInf, LHS: X, RHS: Sub);
3298}
3299
3300static SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG) {
3301 assert(Op.getValueType() == MVT::i1 && "Custom lowering enabled only for i1");
3302
3303 SDValue Cond = Op->getOperand(Num: 0);
3304 SDValue TrueVal = Op->getOperand(Num: 1);
3305 SDValue FalseVal = Op->getOperand(Num: 2);
3306 SDLoc DL(Op);
3307
3308 // If both operands are truncated, we push the select through the truncates.
3309 if (TrueVal.getOpcode() == ISD::TRUNCATE &&
3310 FalseVal.getOpcode() == ISD::TRUNCATE) {
3311 TrueVal = TrueVal.getOperand(i: 0);
3312 FalseVal = FalseVal.getOperand(i: 0);
3313
3314 EVT VT = TrueVal.getSimpleValueType().bitsLE(VT: FalseVal.getSimpleValueType())
3315 ? TrueVal.getValueType()
3316 : FalseVal.getValueType();
3317 TrueVal = DAG.getAnyExtOrTrunc(Op: TrueVal, DL, VT);
3318 FalseVal = DAG.getAnyExtOrTrunc(Op: FalseVal, DL, VT);
3319 SDValue Select = DAG.getSelect(DL, VT, Cond, LHS: TrueVal, RHS: FalseVal);
3320 return DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::i1, Operand: Select);
3321 }
3322
3323 // Otherwise, expand the select into a series of logical operations. These
3324 // often can be folded into other operations either by us or ptxas.
3325 TrueVal = DAG.getFreeze(V: TrueVal);
3326 FalseVal = DAG.getFreeze(V: FalseVal);
3327 SDValue And1 = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i1, N1: Cond, N2: TrueVal);
3328 SDValue NotCond = DAG.getNOT(DL, Val: Cond, VT: MVT::i1);
3329 SDValue And2 = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i1, N1: NotCond, N2: FalseVal);
3330 SDValue Or = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i1, N1: And1, N2: And2);
3331 return Or;
3332}
3333
3334static SDValue lowerMSTORE(SDValue Op, SelectionDAG &DAG) {
3335 SDNode *N = Op.getNode();
3336
3337 SDValue Chain = N->getOperand(Num: 0);
3338 SDValue Val = N->getOperand(Num: 1);
3339 SDValue BasePtr = N->getOperand(Num: 2);
3340 SDValue Offset = N->getOperand(Num: 3);
3341 SDValue Mask = N->getOperand(Num: 4);
3342
3343 SDLoc DL(N);
3344 EVT ValVT = Val.getValueType();
3345 MemSDNode *MemSD = cast<MemSDNode>(Val: N);
3346 assert(ValVT.isVector() && "Masked vector store must have vector type");
3347 assert(MemSD->getAlign() >= DAG.getEVTAlign(ValVT) &&
3348 "Unexpected alignment for masked store");
3349
3350 unsigned Opcode = 0;
3351 switch (ValVT.getSimpleVT().SimpleTy) {
3352 default:
3353 llvm_unreachable("Unexpected masked vector store type");
3354 case MVT::v4i64:
3355 case MVT::v4f64: {
3356 Opcode = NVPTXISD::StoreV4;
3357 break;
3358 }
3359 case MVT::v8i32:
3360 case MVT::v8f32: {
3361 Opcode = NVPTXISD::StoreV8;
3362 break;
3363 }
3364 }
3365
3366 SmallVector<SDValue, 8> Ops;
3367
3368 // Construct the new SDNode. First operand is the chain.
3369 Ops.push_back(Elt: Chain);
3370
3371 // The next N operands are the values to store. Encode the mask into the
3372 // values using the sentinel register 0 to represent a masked-off element.
3373 assert(Mask.getValueType().isVector() &&
3374 Mask.getValueType().getVectorElementType() == MVT::i1 &&
3375 "Mask must be a vector of i1");
3376 assert(Mask.getOpcode() == ISD::BUILD_VECTOR &&
3377 "Mask expected to be a BUILD_VECTOR");
3378 assert(Mask.getValueType().getVectorNumElements() ==
3379 ValVT.getVectorNumElements() &&
3380 "Mask size must be the same as the vector size");
3381 for (auto [I, Op] : enumerate(First: Mask->ops())) {
3382 // Mask elements must be constants.
3383 if (Op.getNode()->getAsZExtVal() == 0) {
3384 // Append a sentinel register 0 to the Ops vector to represent a masked
3385 // off element, this will be handled in tablegen
3386 Ops.push_back(Elt: DAG.getRegister(Reg: MCRegister::NoRegister,
3387 VT: ValVT.getVectorElementType()));
3388 } else {
3389 // Extract the element from the vector to store
3390 SDValue ExtVal =
3391 DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: ValVT.getVectorElementType(),
3392 N1: Val, N2: DAG.getIntPtrConstant(Val: I, DL));
3393 Ops.push_back(Elt: ExtVal);
3394 }
3395 }
3396
3397 // Next, the pointer operand.
3398 Ops.push_back(Elt: BasePtr);
3399
3400 // Finally, the offset operand. We expect this to always be undef, and it will
3401 // be ignored in lowering, but to mirror the handling of the other vector
3402 // store instructions we include it in the new SDNode.
3403 assert(Offset.getOpcode() == ISD::UNDEF &&
3404 "Offset operand expected to be undef");
3405 Ops.push_back(Elt: Offset);
3406
3407 SDValue NewSt =
3408 DAG.getMemIntrinsicNode(Opcode, dl: DL, VTList: DAG.getVTList(VT: MVT::Other), Ops,
3409 MemVT: MemSD->getMemoryVT(), MMO: MemSD->getMemOperand());
3410
3411 return NewSt;
3412}
3413
3414SDValue
3415NVPTXTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3416 switch (Op.getOpcode()) {
3417 case ISD::RETURNADDR:
3418 return SDValue();
3419 case ISD::FRAMEADDR:
3420 return SDValue();
3421 case ISD::ADDRSPACECAST:
3422 return LowerADDRSPACECAST(Op, DAG);
3423 case ISD::INTRINSIC_W_CHAIN:
3424 return lowerIntrinsicWChain(Op, DAG);
3425 case ISD::INTRINSIC_WO_CHAIN:
3426 return lowerIntrinsicWOChain(Op, DAG);
3427 case ISD::INTRINSIC_VOID:
3428 return lowerIntrinsicVoid(Op, DAG);
3429 case ISD::BUILD_VECTOR:
3430 return LowerBUILD_VECTOR(Op, DAG);
3431 case ISD::BITCAST:
3432 return LowerBITCAST(Op, DAG);
3433 case ISD::EXTRACT_SUBVECTOR:
3434 return Op;
3435 case ISD::EXTRACT_VECTOR_ELT:
3436 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3437 case ISD::INSERT_VECTOR_ELT:
3438 return LowerINSERT_VECTOR_ELT(Op, DAG);
3439 case ISD::VECTOR_SHUFFLE:
3440 return LowerVECTOR_SHUFFLE(Op, DAG);
3441 case ISD::CONCAT_VECTORS:
3442 return LowerCONCAT_VECTORS(Op, DAG);
3443 case ISD::VECREDUCE_FMAX:
3444 case ISD::VECREDUCE_FMIN:
3445 case ISD::VECREDUCE_FMAXIMUM:
3446 case ISD::VECREDUCE_FMINIMUM:
3447 return LowerVECREDUCE(Op, DAG);
3448 case ISD::STORE:
3449 return LowerSTORE(Op, DAG);
3450 case ISD::MSTORE: {
3451 assert(STI.has256BitVectorLoadStore(
3452 cast<MemSDNode>(Op.getNode())->getAddressSpace()) &&
3453 "Masked store vector not supported on subtarget.");
3454 return lowerMSTORE(Op, DAG);
3455 }
3456 case ISD::LOAD:
3457 return LowerLOAD(Op, DAG);
3458 case ISD::MLOAD:
3459 return LowerMLOAD(Op, DAG);
3460 case ISD::SHL_PARTS:
3461 return LowerShiftLeftParts(Op, DAG);
3462 case ISD::SRA_PARTS:
3463 case ISD::SRL_PARTS:
3464 return LowerShiftRightParts(Op, DAG);
3465 case ISD::SELECT:
3466 return lowerSELECT(Op, DAG);
3467 case ISD::FROUND:
3468 return LowerFROUND(Op, DAG);
3469 case ISD::FCOPYSIGN:
3470 return LowerFCOPYSIGN(Op, DAG);
3471 case ISD::SINT_TO_FP:
3472 case ISD::UINT_TO_FP:
3473 return LowerINT_TO_FP(Op, DAG);
3474 case ISD::FP_TO_SINT:
3475 case ISD::FP_TO_UINT:
3476 // fptosi/fptoui to i1 truncate toward zero, so the only defined results
3477 // are {0,-1} (signed) and {0,1} (unsigned); every other input results in
3478 // poison. Thus we can simply lower to `x <= -1.0` or `x >= 1.0`.
3479 if (Op.getValueType() == MVT::i1) {
3480 SDLoc DL(Op);
3481 SDValue X = Op.getOperand(i: 0);
3482 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
3483 return DAG.getSetCC(
3484 DL, VT: MVT::i1, LHS: X,
3485 RHS: DAG.getConstantFP(Val: IsSigned ? -1.0 : 1.0, DL, VT: X.getValueType()),
3486 Cond: IsSigned ? ISD::SETOLE : ISD::SETOGE);
3487 }
3488 return LowerFP_TO_INT(Op, DAG);
3489 case ISD::FP_ROUND:
3490 return LowerFP_ROUND(Op, DAG);
3491 case ISD::FP_EXTEND:
3492 return LowerFP_EXTEND(Op, DAG);
3493 case ISD::VAARG:
3494 return LowerVAARG(Op, DAG);
3495 case ISD::VASTART:
3496 return LowerVASTART(Op, DAG);
3497 case ISD::FSHL:
3498 case ISD::FSHR:
3499 return lowerFSH(Op, DAG);
3500 case ISD::ROTL:
3501 case ISD::ROTR:
3502 return lowerROT(Op, DAG);
3503 case ISD::ABS:
3504 case ISD::ABS_MIN_POISON:
3505 case ISD::SMIN:
3506 case ISD::SMAX:
3507 case ISD::UMIN:
3508 case ISD::UMAX:
3509 case ISD::ADD:
3510 case ISD::SUB:
3511 case ISD::MUL:
3512 case ISD::SHL:
3513 case ISD::SREM:
3514 case ISD::UREM:
3515 return LowerVectorArith(Op, DAG);
3516 case ISD::DYNAMIC_STACKALLOC:
3517 return LowerDYNAMIC_STACKALLOC(Op, DAG);
3518 case ISD::STACKRESTORE:
3519 return LowerSTACKRESTORE(Op, DAG);
3520 case ISD::STACKSAVE:
3521 return LowerSTACKSAVE(Op, DAG);
3522 case ISD::CopyToReg:
3523 return LowerCopyToReg_128(Op, DAG);
3524 case ISD::FADD:
3525 case ISD::FSUB:
3526 case ISD::FMUL:
3527 // Used only for bf16 on SM80, where we select fma for non-ftz operation
3528 return PromoteBinOpIfF32FTZ(Op, DAG);
3529 case ISD::CTPOP:
3530 case ISD::CTLZ:
3531 return lowerCTLZCTPOP(Op, DAG);
3532 case ISD::FREM:
3533 return lowerFREM(Op, DAG);
3534 case ISD::BSWAP:
3535 return lowerBSWAP(Op, DAG);
3536 default:
3537 llvm_unreachable("Custom lowering not defined for operation");
3538 }
3539}
3540
3541// This will prevent AsmPrinter from trying to print the jump tables itself.
3542unsigned NVPTXTargetLowering::getJumpTableEncoding() const {
3543 return MachineJumpTableInfo::EK_Inline;
3544}
3545
3546SDValue NVPTXTargetLowering::LowerADDRSPACECAST(SDValue Op,
3547 SelectionDAG &DAG) const {
3548 AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Val: Op.getNode());
3549 unsigned SrcAS = N->getSrcAddressSpace();
3550 unsigned DestAS = N->getDestAddressSpace();
3551 if (SrcAS != llvm::ADDRESS_SPACE_GENERIC &&
3552 DestAS != llvm::ADDRESS_SPACE_GENERIC) {
3553 // Shared and SharedCluster can be converted to each other through generic
3554 // space
3555 if ((SrcAS == llvm::ADDRESS_SPACE_SHARED &&
3556 DestAS == llvm::ADDRESS_SPACE_SHARED_CLUSTER) ||
3557 (SrcAS == llvm::ADDRESS_SPACE_SHARED_CLUSTER &&
3558 DestAS == llvm::ADDRESS_SPACE_SHARED)) {
3559 SDLoc DL(Op.getNode());
3560 const MVT GenerictVT =
3561 getPointerTy(DL: DAG.getDataLayout(), AS: ADDRESS_SPACE_GENERIC);
3562 SDValue GenericConversion = DAG.getAddrSpaceCast(
3563 dl: DL, VT: GenerictVT, Ptr: Op.getOperand(i: 0), SrcAS, DestAS: ADDRESS_SPACE_GENERIC);
3564 SDValue SharedClusterConversion =
3565 DAG.getAddrSpaceCast(dl: DL, VT: Op.getValueType(), Ptr: GenericConversion,
3566 SrcAS: ADDRESS_SPACE_GENERIC, DestAS);
3567 return SharedClusterConversion;
3568 }
3569
3570 return DAG.getUNDEF(VT: Op.getValueType());
3571 }
3572
3573 return Op;
3574}
3575
3576// This function is almost a copy of SelectionDAG::expandVAArg().
3577// The only diff is that this one produces loads from local address space.
3578SDValue NVPTXTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3579 const TargetLowering *TLI = STI.getTargetLowering();
3580 SDLoc DL(Op);
3581
3582 SDNode *Node = Op.getNode();
3583 const Value *V = cast<SrcValueSDNode>(Val: Node->getOperand(Num: 2))->getValue();
3584 EVT VT = Node->getValueType(ResNo: 0);
3585 auto *Ty = VT.getTypeForEVT(Context&: *DAG.getContext());
3586 SDValue Tmp1 = Node->getOperand(Num: 0);
3587 SDValue Tmp2 = Node->getOperand(Num: 1);
3588 const MaybeAlign MA(Node->getConstantOperandVal(Num: 3));
3589
3590 SDValue VAListLoad = DAG.getLoad(VT: TLI->getPointerTy(DL: DAG.getDataLayout()), dl: DL,
3591 Chain: Tmp1, Ptr: Tmp2, PtrInfo: MachinePointerInfo(V));
3592 SDValue VAList = VAListLoad;
3593
3594 if (MA && *MA > TLI->getMinStackArgumentAlignment()) {
3595 VAList = DAG.getNode(
3596 Opcode: ISD::ADD, DL, VT: VAList.getValueType(), N1: VAList,
3597 N2: DAG.getConstant(Val: MA->value() - 1, DL, VT: VAList.getValueType()));
3598
3599 VAList = DAG.getNode(Opcode: ISD::AND, DL, VT: VAList.getValueType(), N1: VAList,
3600 N2: DAG.getSignedConstant(Val: -(int64_t)MA->value(), DL,
3601 VT: VAList.getValueType()));
3602 }
3603
3604 // Increment the pointer, VAList, to the next vaarg
3605 Tmp1 = DAG.getNode(Opcode: ISD::ADD, DL, VT: VAList.getValueType(), N1: VAList,
3606 N2: DAG.getConstant(Val: DAG.getDataLayout().getTypeAllocSize(Ty),
3607 DL, VT: VAList.getValueType()));
3608
3609 // Store the incremented VAList to the legalized pointer
3610 Tmp1 = DAG.getStore(Chain: VAListLoad.getValue(R: 1), dl: DL, Val: Tmp1, Ptr: Tmp2,
3611 PtrInfo: MachinePointerInfo(V));
3612
3613 const Value *SrcV = Constant::getNullValue(
3614 Ty: PointerType::get(C&: *DAG.getContext(), AddressSpace: ADDRESS_SPACE_LOCAL));
3615
3616 // Load the actual argument out of the pointer VAList
3617 return DAG.getLoad(VT, dl: DL, Chain: Tmp1, Ptr: VAList, PtrInfo: MachinePointerInfo(SrcV));
3618}
3619
3620SDValue NVPTXTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3621 const TargetLowering *TLI = STI.getTargetLowering();
3622 SDLoc DL(Op);
3623 EVT PtrVT = TLI->getPointerTy(DL: DAG.getDataLayout());
3624
3625 // Store the address of unsized array <function>_vararg[] in the ap object.
3626 SDValue VAReg = getParamSymbol(DAG, /* vararg */ I: -1, T: PtrVT);
3627
3628 const Value *SV = cast<SrcValueSDNode>(Val: Op.getOperand(i: 2))->getValue();
3629 return DAG.getStore(Chain: Op.getOperand(i: 0), dl: DL, Val: VAReg, Ptr: Op.getOperand(i: 1),
3630 PtrInfo: MachinePointerInfo(SV));
3631}
3632
3633static std::pair<MemSDNode *, uint32_t>
3634convertMLOADToLoadWithUsedBytesMask(MemSDNode *N, SelectionDAG &DAG,
3635 const NVPTXSubtarget &STI) {
3636 SDValue Chain = N->getOperand(Num: 0);
3637 SDValue BasePtr = N->getOperand(Num: 1);
3638 SDValue Mask = N->getOperand(Num: 3);
3639 [[maybe_unused]] SDValue Passthru = N->getOperand(Num: 4);
3640
3641 SDLoc DL(N);
3642 EVT ResVT = N->getValueType(ResNo: 0);
3643 assert(ResVT.isVector() && "Masked vector load must have vector type");
3644 // While we only expect poison passthru vectors as an input to the backend,
3645 // when the legalization framework splits a poison vector in half, it creates
3646 // two undef vectors, so we can technically expect those too.
3647 assert((Passthru.getOpcode() == ISD::POISON ||
3648 Passthru.getOpcode() == ISD::UNDEF) &&
3649 "Passthru operand expected to be poison or undef");
3650
3651 // Extract the mask and convert it to a uint32_t representing the used bytes
3652 // of the entire vector load
3653 uint32_t UsedBytesMask = 0;
3654 uint32_t ElementSizeInBits = ResVT.getVectorElementType().getSizeInBits();
3655 assert(ElementSizeInBits % 8 == 0 && "Unexpected element size");
3656 uint32_t ElementSizeInBytes = ElementSizeInBits / 8;
3657 uint32_t ElementMask = (1u << ElementSizeInBytes) - 1u;
3658
3659 for (SDValue Op : reverse(C: Mask->ops())) {
3660 // We technically only want to do this shift for every
3661 // iteration *but* the first, but in the first iteration UsedBytesMask is 0,
3662 // so this shift is a no-op.
3663 UsedBytesMask <<= ElementSizeInBytes;
3664
3665 // Mask elements must be constants.
3666 if (Op->getAsZExtVal() != 0)
3667 UsedBytesMask |= ElementMask;
3668 }
3669
3670 assert(UsedBytesMask != 0 && UsedBytesMask != UINT32_MAX &&
3671 "Unexpected masked load with elements masked all on or all off");
3672
3673 // Create a new load sd node to be handled normally by ReplaceLoadVector.
3674 MemSDNode *NewLD = cast<MemSDNode>(
3675 Val: DAG.getLoad(VT: ResVT, dl: DL, Chain, Ptr: BasePtr, MMO: N->getMemOperand()).getNode());
3676
3677 // If our subtarget does not support the used bytes mask pragma, "drop" the
3678 // mask by setting it to UINT32_MAX
3679 if (!STI.hasUsedBytesMaskPragma())
3680 UsedBytesMask = UINT32_MAX;
3681
3682 return {NewLD, UsedBytesMask};
3683}
3684
3685/// replaceLoadVector - Convert vector loads into multi-output scalar loads.
3686static std::optional<std::pair<SDValue, SDValue>>
3687replaceLoadVector(SDNode *N, SelectionDAG &DAG, const NVPTXSubtarget &STI) {
3688 MemSDNode *LD = cast<MemSDNode>(Val: N);
3689 const EVT ResVT = LD->getValueType(ResNo: 0);
3690 const EVT MemVT = LD->getMemoryVT();
3691
3692 // If we're doing sign/zero extension as part of the load, avoid lowering to
3693 // a LoadV node. TODO: consider relaxing this restriction.
3694 if (ResVT != MemVT)
3695 return std::nullopt;
3696
3697 const auto NumEltsAndEltVT =
3698 getVectorLoweringShape(VectorEVT: ResVT, STI, AddressSpace: LD->getAddressSpace());
3699 if (!NumEltsAndEltVT)
3700 return std::nullopt;
3701 const auto [NumElts, EltVT] = NumEltsAndEltVT.value();
3702
3703 Align Alignment = LD->getAlign();
3704 const auto &TD = DAG.getDataLayout();
3705 Align PrefAlign = TD.getPrefTypeAlign(Ty: MemVT.getTypeForEVT(Context&: *DAG.getContext()));
3706 if (Alignment < PrefAlign) {
3707 // This load is not sufficiently aligned, so bail out and let this vector
3708 // load be scalarized. Note that we may still be able to emit smaller
3709 // vector loads. For example, if we are loading a <4 x float> with an
3710 // alignment of 8, this check will fail but the legalizer will try again
3711 // with 2 x <2 x float>, which will succeed with an alignment of 8.
3712 return std::nullopt;
3713 }
3714
3715 // If we have a masked load, convert it to a normal load now
3716 std::optional<uint32_t> UsedBytesMask = std::nullopt;
3717 if (LD->getOpcode() == ISD::MLOAD)
3718 std::tie(args&: LD, args&: UsedBytesMask) =
3719 convertMLOADToLoadWithUsedBytesMask(N: LD, DAG, STI);
3720
3721 // Since LoadV2 is a target node, we cannot rely on DAG type legalization.
3722 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
3723 // loaded type to i16 and propagate the "real" type as the memory type.
3724 const MVT LoadEltVT = (EltVT.getSizeInBits() < 16) ? MVT::i16 : EltVT;
3725
3726 unsigned Opcode;
3727 switch (NumElts) {
3728 default:
3729 return std::nullopt;
3730 case 2:
3731 Opcode = NVPTXISD::LoadV2;
3732 break;
3733 case 4:
3734 Opcode = NVPTXISD::LoadV4;
3735 break;
3736 case 8:
3737 Opcode = NVPTXISD::LoadV8;
3738 break;
3739 }
3740 auto ListVTs = SmallVector<EVT, 9>(NumElts, LoadEltVT);
3741 ListVTs.push_back(Elt: MVT::Other);
3742 SDVTList LdResVTs = DAG.getVTList(VTs: ListVTs);
3743
3744 SDLoc DL(LD);
3745
3746 // Copy regular operands
3747 SmallVector<SDValue, 8> OtherOps(LD->ops());
3748
3749 OtherOps.push_back(
3750 Elt: DAG.getConstant(Val: UsedBytesMask.value_or(UINT32_MAX), DL, VT: MVT::i32));
3751
3752 // The select routine does not have access to the LoadSDNode instance, so
3753 // pass along the extension information
3754 OtherOps.push_back(
3755 Elt: DAG.getIntPtrConstant(Val: cast<LoadSDNode>(Val: LD)->getExtensionType(), DL));
3756
3757 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, dl: DL, VTList: LdResVTs, Ops: OtherOps, MemVT,
3758 MMO: LD->getMemOperand());
3759
3760 SmallVector<SDValue> ScalarRes;
3761 if (EltVT.isVector()) {
3762 assert(EVT(EltVT.getVectorElementType()) == ResVT.getVectorElementType());
3763 assert(NumElts * EltVT.getVectorNumElements() ==
3764 ResVT.getVectorNumElements());
3765 // Generate EXTRACT_VECTOR_ELTs to split v2[i,f,bf]16/v4i8 subvectors back
3766 // into individual elements.
3767 for (const unsigned I : llvm::seq(Size: NumElts)) {
3768 SDValue SubVector = NewLD.getValue(R: I);
3769 DAG.ExtractVectorElements(Op: SubVector, Args&: ScalarRes);
3770 }
3771 } else {
3772 for (const unsigned I : llvm::seq(Size: NumElts)) {
3773 SDValue Res = NewLD.getValue(R: I);
3774 if (LoadEltVT != EltVT)
3775 Res = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: EltVT, Operand: Res);
3776 ScalarRes.push_back(Elt: Res);
3777 }
3778 }
3779
3780 SDValue LoadChain = NewLD.getValue(R: NumElts);
3781
3782 const MVT BuildVecVT =
3783 MVT::getVectorVT(VT: EltVT.getScalarType(), NumElements: ScalarRes.size());
3784 SDValue BuildVec = DAG.getBuildVector(VT: BuildVecVT, DL, Ops: ScalarRes);
3785 SDValue LoadValue = DAG.getBitcast(VT: ResVT, V: BuildVec);
3786
3787 return {{LoadValue, LoadChain}};
3788}
3789
3790static void replaceLoadVector(SDNode *N, SelectionDAG &DAG,
3791 SmallVectorImpl<SDValue> &Results,
3792 const NVPTXSubtarget &STI) {
3793 if (auto Res = replaceLoadVector(N, DAG, STI))
3794 Results.append(IL: {Res->first, Res->second});
3795}
3796
3797static SDValue lowerLoadVector(SDNode *N, SelectionDAG &DAG,
3798 const NVPTXSubtarget &STI) {
3799 if (auto Res = replaceLoadVector(N, DAG, STI))
3800 return DAG.getMergeValues(Ops: {Res->first, Res->second}, dl: SDLoc(N));
3801 return SDValue();
3802}
3803
3804// v = ld i1* addr
3805// =>
3806// v1 = ld i8* addr (-> i16)
3807// v = trunc i16 to i1
3808static SDValue lowerLOADi1(LoadSDNode *LD, SelectionDAG &DAG) {
3809 SDLoc dl(LD);
3810 assert(LD->getExtensionType() == ISD::NON_EXTLOAD);
3811 assert(LD->getValueType(0) == MVT::i1 && "Custom lowering for i1 load only");
3812 SDValue newLD = DAG.getExtLoad(ExtType: ISD::ZEXTLOAD, dl, VT: MVT::i16, Chain: LD->getChain(),
3813 Ptr: LD->getBasePtr(), PtrInfo: LD->getPointerInfo(),
3814 MemVT: MVT::i8, Alignment: LD->getAlign(),
3815 MMOFlags: LD->getMemOperand()->getFlags());
3816 SDValue result = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i1, Operand: newLD);
3817 // The legalizer (the caller) is expecting two values from the legalized
3818 // load, so we build a MergeValues node for it. See ExpandUnalignedLoad()
3819 // in LegalizeDAG.cpp which also uses MergeValues.
3820 return DAG.getMergeValues(Ops: {result, LD->getChain()}, dl);
3821}
3822
3823SDValue NVPTXTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3824 LoadSDNode *LD = cast<LoadSDNode>(Val&: Op);
3825
3826 if (Op.getValueType() == MVT::i1)
3827 return lowerLOADi1(LD, DAG);
3828
3829 // To improve CodeGen we'll legalize any-extend loads to zext loads. This is
3830 // how they'll be lowered in ISel anyway, and by doing this a little earlier
3831 // we allow for more DAG combine opportunities.
3832 if (LD->getExtensionType() == ISD::EXTLOAD) {
3833 assert(LD->getValueType(0).isInteger() && LD->getMemoryVT().isInteger() &&
3834 "Unexpected fpext-load");
3835 return DAG.getExtLoad(ExtType: ISD::ZEXTLOAD, dl: SDLoc(Op), VT: Op.getValueType(),
3836 Chain: LD->getChain(), Ptr: LD->getBasePtr(), MemVT: LD->getMemoryVT(),
3837 MMO: LD->getMemOperand());
3838 }
3839
3840 llvm_unreachable("Unexpected custom lowering for load");
3841}
3842
3843SDValue NVPTXTargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
3844 // v2f16/v2bf16/v2i16/v4i8 are legal, so we can't rely on legalizer to handle
3845 // masked loads of these types and have to handle them here.
3846 // v2f32 also needs to be handled here if the subtarget has f32x2
3847 // instructions, making it legal.
3848 //
3849 // Note: misaligned masked loads should never reach this point
3850 // because the override of isLegalMaskedLoad in NVPTXTargetTransformInfo.cpp
3851 // will validate alignment. Therefore, we do not need to special case handle
3852 // them here.
3853 EVT VT = Op.getValueType();
3854 if (NVPTX::isPackedVectorTy(VT)) {
3855 auto Result = convertMLOADToLoadWithUsedBytesMask(
3856 N: cast<MemSDNode>(Val: Op.getNode()), DAG, STI);
3857 MemSDNode *LD = std::get<0>(in&: Result);
3858 uint32_t UsedBytesMask = std::get<1>(in&: Result);
3859
3860 SDLoc DL(LD);
3861
3862 // Copy regular operands
3863 SmallVector<SDValue, 8> OtherOps(LD->ops());
3864
3865 OtherOps.push_back(Elt: DAG.getConstant(Val: UsedBytesMask, DL, VT: MVT::i32));
3866
3867 // We currently are not lowering extending loads, but pass the extension
3868 // type anyway as later handling expects it.
3869 OtherOps.push_back(
3870 Elt: DAG.getIntPtrConstant(Val: cast<LoadSDNode>(Val: LD)->getExtensionType(), DL));
3871 SDValue NewLD =
3872 DAG.getMemIntrinsicNode(Opcode: NVPTXISD::MLoad, dl: DL, VTList: LD->getVTList(), Ops: OtherOps,
3873 MemVT: LD->getMemoryVT(), MMO: LD->getMemOperand());
3874 return NewLD;
3875 }
3876 return SDValue();
3877}
3878
3879static SDValue lowerSTOREVector(SDValue Op, SelectionDAG &DAG,
3880 const NVPTXSubtarget &STI) {
3881 MemSDNode *N = cast<MemSDNode>(Val: Op.getNode());
3882 SDValue Val = N->getOperand(Num: 1);
3883 SDLoc DL(N);
3884 const EVT ValVT = Val.getValueType();
3885 const EVT MemVT = N->getMemoryVT();
3886
3887 // If we're truncating as part of the store, avoid lowering to a StoreV node.
3888 // TODO: consider relaxing this restriction.
3889 if (ValVT != MemVT)
3890 return SDValue();
3891
3892 const auto NumEltsAndEltVT =
3893 getVectorLoweringShape(VectorEVT: ValVT, STI, AddressSpace: N->getAddressSpace());
3894 if (!NumEltsAndEltVT)
3895 return SDValue();
3896 const auto [NumElts, EltVT] = NumEltsAndEltVT.value();
3897
3898 const DataLayout &TD = DAG.getDataLayout();
3899
3900 Align Alignment = N->getAlign();
3901 Align PrefAlign = TD.getPrefTypeAlign(Ty: ValVT.getTypeForEVT(Context&: *DAG.getContext()));
3902 if (Alignment < PrefAlign) {
3903 // This store is not sufficiently aligned, so bail out and let this vector
3904 // store be scalarized. Note that we may still be able to emit smaller
3905 // vector stores. For example, if we are storing a <4 x float> with an
3906 // alignment of 8, this check will fail but the legalizer will try again
3907 // with 2 x <2 x float>, which will succeed with an alignment of 8.
3908 return SDValue();
3909 }
3910
3911 unsigned Opcode;
3912 switch (NumElts) {
3913 default:
3914 return SDValue();
3915 case 2:
3916 Opcode = NVPTXISD::StoreV2;
3917 break;
3918 case 4:
3919 Opcode = NVPTXISD::StoreV4;
3920 break;
3921 case 8:
3922 Opcode = NVPTXISD::StoreV8;
3923 break;
3924 }
3925
3926 SmallVector<SDValue, 8> Ops;
3927
3928 // First is the chain
3929 Ops.push_back(Elt: N->getOperand(Num: 0));
3930
3931 // Then the split values
3932 if (EltVT.isVector()) {
3933 assert(EVT(EltVT.getVectorElementType()) == ValVT.getVectorElementType());
3934 assert(NumElts * EltVT.getVectorNumElements() ==
3935 ValVT.getVectorNumElements());
3936 // Combine individual elements into v2[i,f,bf]16/v4i8 subvectors to be
3937 // stored as b32s
3938 const unsigned NumEltsPerSubVector = EltVT.getVectorNumElements();
3939 for (const unsigned I : llvm::seq(Size: NumElts)) {
3940 SmallVector<SDValue, 4> SubVectorElts;
3941 DAG.ExtractVectorElements(Op: Val, Args&: SubVectorElts, Start: I * NumEltsPerSubVector,
3942 Count: NumEltsPerSubVector);
3943 Ops.push_back(Elt: DAG.getBuildVector(VT: EltVT, DL, Ops: SubVectorElts));
3944 }
3945 } else {
3946 SDValue V = DAG.getBitcast(VT: MVT::getVectorVT(VT: EltVT, NumElements: NumElts), V: Val);
3947 for (const unsigned I : llvm::seq(Size: NumElts)) {
3948 SDValue ExtVal = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: V,
3949 N2: DAG.getIntPtrConstant(Val: I, DL));
3950
3951 // Since StoreV2 is a target node, we cannot rely on DAG type
3952 // legalization. Therefore, we must ensure the type is legal. For i1 and
3953 // i8, we set the stored type to i16 and propagate the "real" type as the
3954 // memory type.
3955 if (EltVT.getSizeInBits() < 16)
3956 ExtVal = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: MVT::i16, Operand: ExtVal);
3957 Ops.push_back(Elt: ExtVal);
3958 }
3959 }
3960
3961 // Then any remaining arguments
3962 Ops.append(in_start: N->op_begin() + 2, in_end: N->op_end());
3963
3964 SDValue NewSt =
3965 DAG.getMemIntrinsicNode(Opcode, dl: DL, VTList: DAG.getVTList(VT: MVT::Other), Ops,
3966 MemVT: N->getMemoryVT(), MMO: N->getMemOperand());
3967
3968 // return DCI.CombineTo(N, NewSt, true);
3969 return NewSt;
3970}
3971
3972SDValue NVPTXTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3973 StoreSDNode *Store = cast<StoreSDNode>(Val&: Op);
3974 EVT VT = Store->getMemoryVT();
3975
3976 if (VT == MVT::i1)
3977 return LowerSTOREi1(Op, DAG);
3978
3979 // Lower store of any other vector type, including v2f32 as we want to break
3980 // it apart since this is not a widely-supported type.
3981 return lowerSTOREVector(Op, DAG, STI);
3982}
3983
3984// st i1 v, addr
3985// =>
3986// v1 = zxt v to i16
3987// st.u8 i16, addr
3988SDValue NVPTXTargetLowering::LowerSTOREi1(SDValue Op, SelectionDAG &DAG) const {
3989 SDNode *Node = Op.getNode();
3990 SDLoc dl(Node);
3991 StoreSDNode *ST = cast<StoreSDNode>(Val: Node);
3992 SDValue Tmp1 = ST->getChain();
3993 SDValue Tmp2 = ST->getBasePtr();
3994 SDValue Tmp3 = ST->getValue();
3995 assert(Tmp3.getValueType() == MVT::i1 && "Custom lowering for i1 store only");
3996 Tmp3 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::i16, Operand: Tmp3);
3997 SDValue Result =
3998 DAG.getTruncStore(Chain: Tmp1, dl, Val: Tmp3, Ptr: Tmp2, PtrInfo: ST->getPointerInfo(), SVT: MVT::i8,
3999 Alignment: ST->getAlign(), MMOFlags: ST->getMemOperand()->getFlags());
4000 return Result;
4001}
4002
4003SDValue NVPTXTargetLowering::LowerCopyToReg_128(SDValue Op,
4004 SelectionDAG &DAG) const {
4005 // Change the CopyToReg to take in two 64-bit operands instead of a 128-bit
4006 // operand so that it can pass the legalization.
4007
4008 assert(Op.getOperand(1).getValueType() == MVT::i128 &&
4009 "Custom lowering for 128-bit CopyToReg only");
4010
4011 SDNode *Node = Op.getNode();
4012 SDLoc DL(Node);
4013
4014 SDValue Cast = DAG.getBitcast(VT: MVT::v2i64, V: Op->getOperand(Num: 2));
4015 SDValue Lo = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i64, N1: Cast,
4016 N2: DAG.getIntPtrConstant(Val: 0, DL));
4017 SDValue Hi = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i64, N1: Cast,
4018 N2: DAG.getIntPtrConstant(Val: 1, DL));
4019
4020 SmallVector<SDValue, 5> NewOps(Op->getNumOperands() + 1);
4021 SmallVector<EVT, 3> ResultsType(Node->values());
4022
4023 NewOps[0] = Op->getOperand(Num: 0); // Chain
4024 NewOps[1] = Op->getOperand(Num: 1); // Dst Reg
4025 NewOps[2] = Lo; // Lower 64-bit
4026 NewOps[3] = Hi; // Higher 64-bit
4027 if (Op.getNumOperands() == 4)
4028 NewOps[4] = Op->getOperand(Num: 3); // Glue if exists
4029
4030 return DAG.getNode(Opcode: ISD::CopyToReg, DL, ResultTys: ResultsType, Ops: NewOps);
4031}
4032
4033unsigned NVPTXTargetLowering::getNumRegisters(
4034 LLVMContext &Context, EVT VT,
4035 std::optional<MVT> RegisterVT = std::nullopt) const {
4036 if (VT == MVT::i128 && RegisterVT == MVT::i128)
4037 return 1;
4038 return TargetLoweringBase::getNumRegisters(Context, VT, RegisterVT);
4039}
4040
4041bool NVPTXTargetLowering::splitValueIntoRegisterParts(
4042 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4043 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4044 if (Val.getValueType() == MVT::i128 && NumParts == 1) {
4045 Parts[0] = Val;
4046 return true;
4047 }
4048 return false;
4049}
4050
4051// This creates target external symbol for a function parameter.
4052// Name of the symbol is composed from its index and the function name.
4053// Negative index corresponds to special parameter (unsized array) used for
4054// passing variable arguments.
4055SDValue NVPTXTargetLowering::getParamSymbol(SelectionDAG &DAG, int I,
4056 EVT T) const {
4057 StringRef SavedStr = nvTM->getStrPool().save(
4058 S: getParamName(F: &DAG.getMachineFunction().getFunction(), Idx: I));
4059 return DAG.getExternalSymbol(Sym: SavedStr.data(), VT: T);
4060}
4061
4062SDValue NVPTXTargetLowering::getCallParamSymbol(SelectionDAG &DAG, int I,
4063 EVT T) const {
4064 const StringRef SavedStr = nvTM->getStrPool().save(S: "param" + Twine(I));
4065 return DAG.getExternalSymbol(Sym: SavedStr.data(), VT: T);
4066}
4067
4068SDValue NVPTXTargetLowering::LowerFormalArguments(
4069 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4070 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4071 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4072 const DataLayout &DL = DAG.getDataLayout();
4073 LLVMContext &Ctx = *DAG.getContext();
4074
4075 const Function &F = DAG.getMachineFunction().getFunction();
4076 const bool IsKernel = isKernelFunction(F);
4077
4078 const MVT PtrVT = getPointerTy(DL, AS: IsKernel ? ADDRESS_SPACE_ENTRY_PARAM
4079 : ADDRESS_SPACE_LOCAL);
4080
4081 SDValue Root = DAG.getRoot();
4082 SmallVector<SDValue, 16> OutChains;
4083
4084 // argTypes.size() (or theArgs.size()) and Ins.size() need not match.
4085 // Ins.size() will be larger
4086 // * if there is an aggregate argument with multiple fields (each field
4087 // showing up separately in Ins)
4088 // * if there is a vector argument with more than typical vector-length
4089 // elements (generally if more than 4) where each vector element is
4090 // individually present in Ins.
4091 // So a different index should be used for indexing into Ins.
4092 // See similar issue in LowerCall.
4093
4094 auto AllIns = ArrayRef(Ins);
4095 const auto NonEmptyArgs = make_filter_range(
4096 Range: F.args(), Pred: [](const Argument &A) { return !A.getType()->isEmptyTy(); });
4097 for (const auto &[ParamI, Arg] : enumerate(First: NonEmptyArgs)) {
4098 const unsigned ArgNo = Arg.getArgNo();
4099 const auto ArgIns =
4100 AllIns.take_while(Pred: [&](auto I) { return I.OrigArgIndex == ArgNo; });
4101 AllIns = AllIns.drop_front(N: ArgIns.size());
4102
4103 Type *Ty = Arg.getType();
4104 assert(!ArgIns.empty() &&
4105 "Non-empty argument produced no parameter values");
4106
4107 if (Arg.use_empty()) {
4108 // argument is dead
4109 for (const auto &In : ArgIns) {
4110 assert(!In.Used && "Arg.use_empty() is true but Arg is used?");
4111 InVals.push_back(Elt: DAG.getUNDEF(VT: In.VT));
4112 }
4113 continue;
4114 }
4115
4116 SDValue ArgSymbol = getParamSymbol(DAG, I: ParamI, T: PtrVT);
4117
4118 // In the following cases, assign a node order of "i+1"
4119 // to newly created nodes. The SDNodes for params have to
4120 // appear in the same order as their order of appearance
4121 // in the original function. "i+1" holds that order.
4122 if (Arg.hasByValAttr()) {
4123 // Param has ByVal attribute
4124 // Return MoveParam(param symbol).
4125 // Ideally, the param symbol can be returned directly,
4126 // but when SDNode builder decides to use it in a CopyToReg(),
4127 // machine instruction fails because TargetExternalSymbol
4128 // (not lowered) is target dependent, and CopyToReg assumes
4129 // the source is lowered.
4130 assert(ArgIns.size() == 1 && "ByVal argument must be a pointer");
4131 const auto &ByvalIn = ArgIns[0];
4132 assert(getValueType(DL, Ty) == ByvalIn.VT &&
4133 "Ins type did not match function type");
4134
4135 SDValue P;
4136 if (IsKernel) {
4137 assert(Ty->getPointerAddressSpace() == ADDRESS_SPACE_ENTRY_PARAM &&
4138 "Kernel ByVal argument must be lowered to the param address "
4139 "space by NVPTXLowerArgs");
4140 P = ArgSymbol;
4141 P.getNode()->setIROrder(Arg.getArgNo() + 1);
4142 } else {
4143 P = DAG.getNode(Opcode: NVPTXISD::MoveParam, DL: dl, VT: ArgSymbol.getValueType(),
4144 Operand: ArgSymbol);
4145 P.getNode()->setIROrder(Arg.getArgNo() + 1);
4146 P = DAG.getAddrSpaceCast(dl, VT: ByvalIn.VT, Ptr: P, SrcAS: ADDRESS_SPACE_LOCAL,
4147 DestAS: ADDRESS_SPACE_GENERIC);
4148 }
4149 InVals.push_back(Elt: P);
4150 } else {
4151 SmallVector<EVT, 16> VTs;
4152 SmallVector<uint64_t, 16> Offsets;
4153 ComputePTXValueVTs(TLI: *this, DL, Ctx, CallConv, Ty, ValueVTs&: VTs, Offsets);
4154 assert(VTs.size() == ArgIns.size() && "Size mismatch");
4155 assert(VTs.size() == Offsets.size() && "Size mismatch");
4156
4157 const Align ArgAlign = getPTXParamAlign(
4158 F: &F, Ty, AttrIdx: Arg.getArgNo() + AttributeList::FirstArgIndex, DL);
4159
4160 unsigned I = 0;
4161 const auto VI = VectorizePTXValueVTs(ValueVTs: VTs, Offsets, ParamAlignment: ArgAlign);
4162 for (const unsigned NumElts : VI) {
4163 // i1 is loaded/stored as i8
4164 const EVT LoadVT = VTs[I] == MVT::i1 ? MVT::i8 : VTs[I];
4165 const EVT VecVT = getVectorizedVT(VT: LoadVT, N: NumElts, C&: Ctx);
4166
4167 SDValue VecAddr = DAG.getObjectPtrOffset(
4168 SL: dl, Ptr: ArgSymbol, Offset: TypeSize::getFixed(ExactSize: Offsets[I]));
4169
4170 const Align PartAlign = commonAlignment(A: ArgAlign, Offset: Offsets[I]);
4171 const unsigned AS = IsKernel ? NVPTX::AddressSpace::EntryParam
4172 : NVPTX::AddressSpace::DeviceParam;
4173 SDValue P = DAG.getLoad(VT: VecVT, dl, Chain: Root, Ptr: VecAddr,
4174 PtrInfo: MachinePointerInfo(AS), Alignment: PartAlign,
4175 MMOFlags: MachineMemOperand::MODereferenceable |
4176 MachineMemOperand::MOInvariant);
4177 P.getNode()->setIROrder(Arg.getArgNo() + 1);
4178 for (const unsigned J : llvm::seq(Size: NumElts)) {
4179 SDValue Elt = getExtractVectorizedValue(V: P, I: J, VT: LoadVT, dl, DAG);
4180
4181 Elt = correctParamType(V: Elt, ExpectedVT: ArgIns[I + J].VT, Flags: ArgIns[I + J].Flags,
4182 DAG, dl);
4183 InVals.push_back(Elt);
4184 }
4185 I += NumElts;
4186 }
4187 }
4188 }
4189
4190 if (!OutChains.empty())
4191 DAG.setRoot(DAG.getTokenFactor(DL: dl, Vals&: OutChains));
4192
4193 return Chain;
4194}
4195
4196SDValue
4197NVPTXTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4198 bool isVarArg,
4199 const SmallVectorImpl<ISD::OutputArg> &Outs,
4200 const SmallVectorImpl<SDValue> &OutVals,
4201 const SDLoc &dl, SelectionDAG &DAG) const {
4202 const Function &F = DAG.getMachineFunction().getFunction();
4203 Type *RetTy = F.getReturnType();
4204
4205 if (RetTy->isVoidTy()) {
4206 assert(OutVals.empty() && Outs.empty() && "Return value expected for void");
4207 return DAG.getNode(Opcode: NVPTXISD::RET_GLUE, DL: dl, VT: MVT::Other, Operand: Chain);
4208 }
4209
4210 const DataLayout &DL = DAG.getDataLayout();
4211 LLVMContext &Ctx = *DAG.getContext();
4212
4213 const SDValue RetSymbol = DAG.getExternalSymbol(Sym: "func_retval0", VT: MVT::i32);
4214 const auto RetAlign =
4215 getPTXParamAlign(F: &F, Ty: RetTy, AttrIdx: AttributeList::ReturnIndex, DL);
4216
4217 // PTX Interoperability Guide 3.3(A): [Integer] Values shorter than
4218 // 32-bits are sign extended or zero extended, depending on whether
4219 // they are signed or unsigned types.
4220 const bool ExtendIntegerRetVal =
4221 RetTy->isIntegerTy() && DL.getTypeAllocSizeInBits(Ty: RetTy) < 32;
4222
4223 SmallVector<EVT, 16> VTs;
4224 SmallVector<uint64_t, 16> Offsets;
4225 ComputePTXValueVTs(TLI: *this, DL, Ctx, CallConv, Ty: RetTy, ValueVTs&: VTs, Offsets);
4226 assert(VTs.size() == OutVals.size() && "Bad return value decomposition");
4227
4228 const auto GetRetVal = [&](unsigned I) -> SDValue {
4229 SDValue RetVal = OutVals[I];
4230 assert(promoteScalarIntegerPTX(RetVal.getValueType()) ==
4231 RetVal.getValueType() &&
4232 "OutVal type should always be legal");
4233
4234 const EVT VTI = promoteScalarIntegerPTX(VT: VTs[I]);
4235 const EVT StoreVT =
4236 ExtendIntegerRetVal ? MVT::i32 : (VTI == MVT::i1 ? MVT::i8 : VTI);
4237 return correctParamType(V: RetVal, ExpectedVT: StoreVT, Flags: Outs[I].Flags, DAG, dl);
4238 };
4239
4240 unsigned I = 0;
4241 const auto VI = VectorizePTXValueVTs(ValueVTs: VTs, Offsets, ParamAlignment: RetAlign);
4242 for (const unsigned NumElts : VI) {
4243 const MaybeAlign CurrentAlign = ExtendIntegerRetVal
4244 ? MaybeAlign(std::nullopt)
4245 : commonAlignment(A: RetAlign, Offset: Offsets[I]);
4246
4247 SDValue Val = getBuildVectorizedValue(
4248 N: NumElts, dl, DAG, GetElement: [&](unsigned K) { return GetRetVal(I + K); });
4249
4250 SDValue Ptr =
4251 DAG.getObjectPtrOffset(SL: dl, Ptr: RetSymbol, Offset: TypeSize::getFixed(ExactSize: Offsets[I]));
4252
4253 Chain = DAG.getStore(Chain, dl, Val, Ptr,
4254 PtrInfo: MachinePointerInfo(NVPTX::AddressSpace::DeviceParam),
4255 Alignment: CurrentAlign);
4256
4257 I += NumElts;
4258 }
4259
4260 return DAG.getNode(Opcode: NVPTXISD::RET_GLUE, DL: dl, VT: MVT::Other, Operand: Chain);
4261}
4262
4263void NVPTXTargetLowering::LowerAsmOperandForConstraint(
4264 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
4265 SelectionDAG &DAG) const {
4266 if (Constraint.size() > 1)
4267 return;
4268 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4269}
4270
4271// llvm.ptx.memcpy.const and llvm.ptx.memmove.const need to be modeled as
4272// TgtMemIntrinsic
4273// because we need the information that is only available in the "Value" type
4274// of destination
4275// pointer. In particular, the address space information.
4276void NVPTXTargetLowering::getTgtMemIntrinsic(
4277 SmallVectorImpl<IntrinsicInfo> &Infos, const CallBase &I,
4278 MachineFunction &MF, unsigned Intrinsic) const {
4279 IntrinsicInfo Info;
4280 switch (Intrinsic) {
4281 default:
4282 return;
4283 case Intrinsic::nvvm_match_all_sync_i32p:
4284 case Intrinsic::nvvm_match_all_sync_i64p:
4285 Info.opc = ISD::INTRINSIC_W_CHAIN;
4286 // memVT is bogus. These intrinsics have IntrInaccessibleMemOnly attribute
4287 // in order to model data exchange with other threads, but perform no real
4288 // memory accesses.
4289 Info.memVT = MVT::i1;
4290
4291 // Our result depends on both our and other thread's arguments.
4292 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4293 Infos.push_back(Elt: Info);
4294 return;
4295 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_col:
4296 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_row:
4297 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_col_stride:
4298 case Intrinsic::nvvm_wmma_m16n16k16_load_a_f16_row_stride:
4299 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_col:
4300 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_row:
4301 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_col_stride:
4302 case Intrinsic::nvvm_wmma_m16n16k16_load_b_f16_row_stride:
4303 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_col:
4304 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_row:
4305 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_col_stride:
4306 case Intrinsic::nvvm_wmma_m32n8k16_load_a_f16_row_stride:
4307 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_col:
4308 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_row:
4309 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_col_stride:
4310 case Intrinsic::nvvm_wmma_m32n8k16_load_b_f16_row_stride:
4311 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_col:
4312 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_row:
4313 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_col_stride:
4314 case Intrinsic::nvvm_wmma_m8n32k16_load_a_f16_row_stride:
4315 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_col:
4316 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_row:
4317 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_col_stride:
4318 case Intrinsic::nvvm_wmma_m8n32k16_load_b_f16_row_stride: {
4319 Info.opc = ISD::INTRINSIC_W_CHAIN;
4320 Info.memVT = MVT::v8f16;
4321 Info.ptrVal = I.getArgOperand(i: 0);
4322 Info.offset = 0;
4323 Info.flags = MachineMemOperand::MOLoad;
4324 Info.align = Align(16);
4325 Infos.push_back(Elt: Info);
4326 return;
4327 }
4328 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_col:
4329 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_col_stride:
4330 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_col_stride:
4331 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_col:
4332 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_row:
4333 case Intrinsic::nvvm_wmma_m16n16k16_load_a_s8_row_stride:
4334 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_row_stride:
4335 case Intrinsic::nvvm_wmma_m16n16k16_load_a_u8_row:
4336 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_col:
4337 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_col_stride:
4338 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_row:
4339 case Intrinsic::nvvm_wmma_m8n32k16_load_a_bf16_row_stride:
4340 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_col:
4341 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_col_stride:
4342 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_col_stride:
4343 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_col:
4344 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_row:
4345 case Intrinsic::nvvm_wmma_m16n16k16_load_b_s8_row_stride:
4346 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_row_stride:
4347 case Intrinsic::nvvm_wmma_m16n16k16_load_b_u8_row:
4348 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_col:
4349 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_col_stride:
4350 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_row:
4351 case Intrinsic::nvvm_wmma_m32n8k16_load_b_bf16_row_stride: {
4352 Info.opc = ISD::INTRINSIC_W_CHAIN;
4353 Info.memVT = MVT::v2i32;
4354 Info.ptrVal = I.getArgOperand(i: 0);
4355 Info.offset = 0;
4356 Info.flags = MachineMemOperand::MOLoad;
4357 Info.align = Align(8);
4358 Infos.push_back(Elt: Info);
4359 return;
4360 }
4361
4362 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_col:
4363 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_col_stride:
4364 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_col_stride:
4365 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_col:
4366 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_row:
4367 case Intrinsic::nvvm_wmma_m32n8k16_load_a_s8_row_stride:
4368 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_row_stride:
4369 case Intrinsic::nvvm_wmma_m32n8k16_load_a_u8_row:
4370 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_col:
4371 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_col_stride:
4372 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_row:
4373 case Intrinsic::nvvm_wmma_m16n16k16_load_a_bf16_row_stride:
4374 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_col:
4375 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_col_stride:
4376 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_row:
4377 case Intrinsic::nvvm_wmma_m16n16k8_load_a_tf32_row_stride:
4378
4379 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_col:
4380 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_col_stride:
4381 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_col_stride:
4382 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_col:
4383 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_row:
4384 case Intrinsic::nvvm_wmma_m8n32k16_load_b_s8_row_stride:
4385 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_row_stride:
4386 case Intrinsic::nvvm_wmma_m8n32k16_load_b_u8_row:
4387 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_col:
4388 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_col_stride:
4389 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_row:
4390 case Intrinsic::nvvm_wmma_m16n16k16_load_b_bf16_row_stride:
4391 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_col:
4392 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_col_stride:
4393 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_row:
4394 case Intrinsic::nvvm_wmma_m16n16k8_load_b_tf32_row_stride:
4395 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x4_b16:
4396 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x4_trans_b16:
4397 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8:
4398 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8x16_b4x16_p64:
4399 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x2_trans_b8x16_b6x16_p32:
4400 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x4_b8x16_b4x16_p64:
4401 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x4_b8x16_b6x16_p32: {
4402 Info.opc = ISD::INTRINSIC_W_CHAIN;
4403 Info.memVT = MVT::v4i32;
4404 Info.ptrVal = I.getArgOperand(i: 0);
4405 Info.offset = 0;
4406 Info.flags = MachineMemOperand::MOLoad;
4407 Info.align = Align(16);
4408 Infos.push_back(Elt: Info);
4409 return;
4410 }
4411
4412 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_col:
4413 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_col_stride:
4414 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_col_stride:
4415 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_col:
4416 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_row:
4417 case Intrinsic::nvvm_wmma_m32n8k16_load_b_s8_row_stride:
4418 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_row_stride:
4419 case Intrinsic::nvvm_wmma_m32n8k16_load_b_u8_row:
4420
4421 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_col:
4422 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_col_stride:
4423 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_col_stride:
4424 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_col:
4425 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_row:
4426 case Intrinsic::nvvm_wmma_m8n32k16_load_a_s8_row_stride:
4427 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_row_stride:
4428 case Intrinsic::nvvm_wmma_m8n32k16_load_a_u8_row:
4429 case Intrinsic::nvvm_wmma_m8n8k128_load_a_b1_row:
4430 case Intrinsic::nvvm_wmma_m8n8k128_load_a_b1_row_stride:
4431 case Intrinsic::nvvm_wmma_m8n8k128_load_b_b1_col:
4432 case Intrinsic::nvvm_wmma_m8n8k128_load_b_b1_col_stride:
4433 case Intrinsic::nvvm_wmma_m8n8k32_load_a_s4_row:
4434 case Intrinsic::nvvm_wmma_m8n8k32_load_a_s4_row_stride:
4435 case Intrinsic::nvvm_wmma_m8n8k32_load_a_u4_row_stride:
4436 case Intrinsic::nvvm_wmma_m8n8k32_load_a_u4_row:
4437 case Intrinsic::nvvm_wmma_m8n8k32_load_b_s4_col:
4438 case Intrinsic::nvvm_wmma_m8n8k32_load_b_s4_col_stride:
4439 case Intrinsic::nvvm_wmma_m8n8k32_load_b_u4_col_stride:
4440 case Intrinsic::nvvm_wmma_m8n8k32_load_b_u4_col:
4441 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x1_b16:
4442 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x1_trans_b16:
4443 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x1_b8x16_b4x16_p64:
4444 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x1_b8x16_b6x16_p32: {
4445 Info.opc = ISD::INTRINSIC_W_CHAIN;
4446 Info.memVT = MVT::i32;
4447 Info.ptrVal = I.getArgOperand(i: 0);
4448 Info.offset = 0;
4449 Info.flags = MachineMemOperand::MOLoad;
4450 Info.align = Align(4);
4451 Infos.push_back(Elt: Info);
4452 return;
4453 }
4454
4455 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_col:
4456 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_row:
4457 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_col_stride:
4458 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f16_row_stride:
4459 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_col:
4460 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_row:
4461 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_col_stride:
4462 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f16_row_stride:
4463 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_col:
4464 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_row:
4465 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_col_stride:
4466 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f16_row_stride: {
4467 Info.opc = ISD::INTRINSIC_W_CHAIN;
4468 Info.memVT = MVT::v4f16;
4469 Info.ptrVal = I.getArgOperand(i: 0);
4470 Info.offset = 0;
4471 Info.flags = MachineMemOperand::MOLoad;
4472 Info.align = Align(16);
4473 Infos.push_back(Elt: Info);
4474 return;
4475 }
4476
4477 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_col:
4478 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_row:
4479 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_col_stride:
4480 case Intrinsic::nvvm_wmma_m16n16k16_load_c_f32_row_stride:
4481 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_col:
4482 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_row:
4483 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_col_stride:
4484 case Intrinsic::nvvm_wmma_m32n8k16_load_c_f32_row_stride:
4485 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_col:
4486 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_row:
4487 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_col_stride:
4488 case Intrinsic::nvvm_wmma_m8n32k16_load_c_f32_row_stride:
4489 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_col:
4490 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_row:
4491 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_col_stride:
4492 case Intrinsic::nvvm_wmma_m16n16k8_load_c_f32_row_stride: {
4493 Info.opc = ISD::INTRINSIC_W_CHAIN;
4494 Info.memVT = MVT::v8f32;
4495 Info.ptrVal = I.getArgOperand(i: 0);
4496 Info.offset = 0;
4497 Info.flags = MachineMemOperand::MOLoad;
4498 Info.align = Align(16);
4499 Infos.push_back(Elt: Info);
4500 return;
4501 }
4502
4503 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_col:
4504 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_col_stride:
4505 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_row:
4506 case Intrinsic::nvvm_wmma_m32n8k16_load_a_bf16_row_stride:
4507
4508 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_col:
4509 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_col_stride:
4510 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_row:
4511 case Intrinsic::nvvm_wmma_m8n32k16_load_b_bf16_row_stride:
4512
4513 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_col:
4514 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_col_stride:
4515 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_row:
4516 case Intrinsic::nvvm_wmma_m16n16k16_load_c_s32_row_stride:
4517 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_col:
4518 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_col_stride:
4519 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_row:
4520 case Intrinsic::nvvm_wmma_m32n8k16_load_c_s32_row_stride:
4521 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_col:
4522 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_col_stride:
4523 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_row:
4524 case Intrinsic::nvvm_wmma_m8n32k16_load_c_s32_row_stride: {
4525 Info.opc = ISD::INTRINSIC_W_CHAIN;
4526 Info.memVT = MVT::v8i32;
4527 Info.ptrVal = I.getArgOperand(i: 0);
4528 Info.offset = 0;
4529 Info.flags = MachineMemOperand::MOLoad;
4530 Info.align = Align(16);
4531 Infos.push_back(Elt: Info);
4532 return;
4533 }
4534
4535 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_col:
4536 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_col_stride:
4537 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_row:
4538 case Intrinsic::nvvm_wmma_m8n8k128_load_c_s32_row_stride:
4539 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_col:
4540 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_col_stride:
4541 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_row:
4542 case Intrinsic::nvvm_wmma_m8n8k32_load_c_s32_row_stride:
4543 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x2_b16:
4544 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n8_x2_trans_b16:
4545 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8:
4546 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8x16_b4x16_p64:
4547 case Intrinsic::nvvm_ldmatrix_sync_aligned_m16n16_x1_trans_b8x16_b6x16_p32:
4548 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x2_b8x16_b4x16_p64:
4549 case Intrinsic::nvvm_ldmatrix_sync_aligned_m8n16_x2_b8x16_b6x16_p32: {
4550 Info.opc = ISD::INTRINSIC_W_CHAIN;
4551 Info.memVT = MVT::v2i32;
4552 Info.ptrVal = I.getArgOperand(i: 0);
4553 Info.offset = 0;
4554 Info.flags = MachineMemOperand::MOLoad;
4555 Info.align = Align(8);
4556 Infos.push_back(Elt: Info);
4557 return;
4558 }
4559
4560 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_col:
4561 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_col_stride:
4562 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_row:
4563 case Intrinsic::nvvm_wmma_m8n8k4_load_a_f64_row_stride:
4564
4565 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_col:
4566 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_col_stride:
4567 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_row:
4568 case Intrinsic::nvvm_wmma_m8n8k4_load_b_f64_row_stride: {
4569 Info.opc = ISD::INTRINSIC_W_CHAIN;
4570 Info.memVT = MVT::f64;
4571 Info.ptrVal = I.getArgOperand(i: 0);
4572 Info.offset = 0;
4573 Info.flags = MachineMemOperand::MOLoad;
4574 Info.align = Align(8);
4575 Infos.push_back(Elt: Info);
4576 return;
4577 }
4578
4579 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_col:
4580 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_col_stride:
4581 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_row:
4582 case Intrinsic::nvvm_wmma_m8n8k4_load_c_f64_row_stride: {
4583 Info.opc = ISD::INTRINSIC_W_CHAIN;
4584 Info.memVT = MVT::v2f64;
4585 Info.ptrVal = I.getArgOperand(i: 0);
4586 Info.offset = 0;
4587 Info.flags = MachineMemOperand::MOLoad;
4588 Info.align = Align(16);
4589 Infos.push_back(Elt: Info);
4590 return;
4591 }
4592
4593 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_col:
4594 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_row:
4595 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_col_stride:
4596 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f16_row_stride:
4597 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_col:
4598 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_row:
4599 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_col_stride:
4600 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f16_row_stride:
4601 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_col:
4602 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_row:
4603 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_col_stride:
4604 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f16_row_stride: {
4605 Info.opc = ISD::INTRINSIC_VOID;
4606 Info.memVT = MVT::v4f16;
4607 Info.ptrVal = I.getArgOperand(i: 0);
4608 Info.offset = 0;
4609 Info.flags = MachineMemOperand::MOStore;
4610 Info.align = Align(16);
4611 Infos.push_back(Elt: Info);
4612 return;
4613 }
4614
4615 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_col:
4616 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_row:
4617 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_col_stride:
4618 case Intrinsic::nvvm_wmma_m16n16k16_store_d_f32_row_stride:
4619 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_col:
4620 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_row:
4621 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_col_stride:
4622 case Intrinsic::nvvm_wmma_m32n8k16_store_d_f32_row_stride:
4623 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_col:
4624 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_row:
4625 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_col_stride:
4626 case Intrinsic::nvvm_wmma_m8n32k16_store_d_f32_row_stride:
4627 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_col:
4628 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_row:
4629 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_col_stride:
4630 case Intrinsic::nvvm_wmma_m16n16k8_store_d_f32_row_stride: {
4631 Info.opc = ISD::INTRINSIC_VOID;
4632 Info.memVT = MVT::v8f32;
4633 Info.ptrVal = I.getArgOperand(i: 0);
4634 Info.offset = 0;
4635 Info.flags = MachineMemOperand::MOStore;
4636 Info.align = Align(16);
4637 Infos.push_back(Elt: Info);
4638 return;
4639 }
4640
4641 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_col:
4642 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_col_stride:
4643 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_row:
4644 case Intrinsic::nvvm_wmma_m16n16k16_store_d_s32_row_stride:
4645 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_col:
4646 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_col_stride:
4647 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_row:
4648 case Intrinsic::nvvm_wmma_m32n8k16_store_d_s32_row_stride:
4649 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_col:
4650 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_col_stride:
4651 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_row:
4652 case Intrinsic::nvvm_wmma_m8n32k16_store_d_s32_row_stride: {
4653 Info.opc = ISD::INTRINSIC_VOID;
4654 Info.memVT = MVT::v8i32;
4655 Info.ptrVal = I.getArgOperand(i: 0);
4656 Info.offset = 0;
4657 Info.flags = MachineMemOperand::MOStore;
4658 Info.align = Align(16);
4659 Infos.push_back(Elt: Info);
4660 return;
4661 }
4662
4663 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_col:
4664 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_col_stride:
4665 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_row:
4666 case Intrinsic::nvvm_wmma_m8n8k128_store_d_s32_row_stride:
4667 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_col:
4668 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_col_stride:
4669 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_row:
4670 case Intrinsic::nvvm_wmma_m8n8k32_store_d_s32_row_stride:
4671 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x2_b16:
4672 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x2_trans_b16:
4673 case Intrinsic::nvvm_stmatrix_sync_aligned_m16n8_x2_trans_b8: {
4674 Info.opc = ISD::INTRINSIC_VOID;
4675 Info.memVT = MVT::v2i32;
4676 Info.ptrVal = I.getArgOperand(i: 0);
4677 Info.offset = 0;
4678 Info.flags = MachineMemOperand::MOStore;
4679 Info.align = Align(8);
4680 Infos.push_back(Elt: Info);
4681 return;
4682 }
4683
4684 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_col:
4685 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_col_stride:
4686 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_row:
4687 case Intrinsic::nvvm_wmma_m8n8k4_store_d_f64_row_stride: {
4688 Info.opc = ISD::INTRINSIC_VOID;
4689 Info.memVT = MVT::v2f64;
4690 Info.ptrVal = I.getArgOperand(i: 0);
4691 Info.offset = 0;
4692 Info.flags = MachineMemOperand::MOStore;
4693 Info.align = Align(16);
4694 Infos.push_back(Elt: Info);
4695 return;
4696 }
4697
4698 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x1_b16:
4699 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x1_trans_b16:
4700 case Intrinsic::nvvm_stmatrix_sync_aligned_m16n8_x1_trans_b8: {
4701 Info.opc = ISD::INTRINSIC_VOID;
4702 Info.memVT = MVT::i32;
4703 Info.ptrVal = I.getArgOperand(i: 0);
4704 Info.offset = 0;
4705 Info.flags = MachineMemOperand::MOStore;
4706 Info.align = Align(4);
4707 Infos.push_back(Elt: Info);
4708 return;
4709 }
4710
4711 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x4_b16:
4712 case Intrinsic::nvvm_stmatrix_sync_aligned_m8n8_x4_trans_b16:
4713 case Intrinsic::nvvm_stmatrix_sync_aligned_m16n8_x4_trans_b8: {
4714 Info.opc = ISD::INTRINSIC_VOID;
4715 Info.memVT = MVT::v4i32;
4716 Info.ptrVal = I.getArgOperand(i: 0);
4717 Info.offset = 0;
4718 Info.flags = MachineMemOperand::MOStore;
4719 Info.align = Align(16);
4720 Infos.push_back(Elt: Info);
4721 return;
4722 }
4723
4724 case Intrinsic::nvvm_prefetch_tensormap: {
4725 auto &DL = I.getDataLayout();
4726 Info.opc = ISD::INTRINSIC_VOID;
4727 Info.memVT = getPointerTy(DL);
4728 Info.ptrVal = I.getArgOperand(i: 0);
4729 Info.offset = 0;
4730 Info.flags =
4731 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable;
4732 Info.align.reset();
4733 Infos.push_back(Elt: Info);
4734 return;
4735 }
4736
4737 case Intrinsic::nvvm_tensormap_replace_global_address:
4738 case Intrinsic::nvvm_tensormap_replace_global_stride: {
4739 Info.opc = ISD::INTRINSIC_VOID;
4740 Info.memVT = MVT::i64;
4741 Info.ptrVal = I.getArgOperand(i: 0);
4742 Info.offset = 0;
4743 Info.flags = MachineMemOperand::MOStore;
4744 Info.align.reset();
4745 Infos.push_back(Elt: Info);
4746 return;
4747 }
4748
4749 case Intrinsic::nvvm_tensormap_replace_rank:
4750 case Intrinsic::nvvm_tensormap_replace_box_dim:
4751 case Intrinsic::nvvm_tensormap_replace_global_dim:
4752 case Intrinsic::nvvm_tensormap_replace_element_stride:
4753 case Intrinsic::nvvm_tensormap_replace_elemtype:
4754 case Intrinsic::nvvm_tensormap_replace_interleave_layout:
4755 case Intrinsic::nvvm_tensormap_replace_swizzle_mode:
4756 case Intrinsic::nvvm_tensormap_replace_swizzle_atomicity:
4757 case Intrinsic::nvvm_tensormap_replace_fill_mode: {
4758 Info.opc = ISD::INTRINSIC_VOID;
4759 Info.memVT = MVT::i32;
4760 Info.ptrVal = I.getArgOperand(i: 0);
4761 Info.offset = 0;
4762 Info.flags = MachineMemOperand::MOStore;
4763 Info.align.reset();
4764 Infos.push_back(Elt: Info);
4765 return;
4766 }
4767
4768 case Intrinsic::nvvm_ldu_global_i:
4769 case Intrinsic::nvvm_ldu_global_f:
4770 case Intrinsic::nvvm_ldu_global_p: {
4771 Info.opc = ISD::INTRINSIC_W_CHAIN;
4772 Info.memVT = getValueType(DL: I.getDataLayout(), Ty: I.getType());
4773 Info.ptrVal = I.getArgOperand(i: 0);
4774 Info.offset = 0;
4775 Info.flags = MachineMemOperand::MOLoad;
4776 Info.align = cast<ConstantInt>(Val: I.getArgOperand(i: 1))->getMaybeAlignValue();
4777
4778 Infos.push_back(Elt: Info);
4779 return;
4780 }
4781 case Intrinsic::nvvm_tex_1d_v4f32_s32:
4782 case Intrinsic::nvvm_tex_1d_v4f32_f32:
4783 case Intrinsic::nvvm_tex_1d_level_v4f32_f32:
4784 case Intrinsic::nvvm_tex_1d_grad_v4f32_f32:
4785 case Intrinsic::nvvm_tex_1d_array_v4f32_s32:
4786 case Intrinsic::nvvm_tex_1d_array_v4f32_f32:
4787 case Intrinsic::nvvm_tex_1d_array_level_v4f32_f32:
4788 case Intrinsic::nvvm_tex_1d_array_grad_v4f32_f32:
4789 case Intrinsic::nvvm_tex_2d_v4f32_s32:
4790 case Intrinsic::nvvm_tex_2d_v4f32_f32:
4791 case Intrinsic::nvvm_tex_2d_level_v4f32_f32:
4792 case Intrinsic::nvvm_tex_2d_grad_v4f32_f32:
4793 case Intrinsic::nvvm_tex_2d_array_v4f32_s32:
4794 case Intrinsic::nvvm_tex_2d_array_v4f32_f32:
4795 case Intrinsic::nvvm_tex_2d_array_level_v4f32_f32:
4796 case Intrinsic::nvvm_tex_2d_array_grad_v4f32_f32:
4797 case Intrinsic::nvvm_tex_3d_v4f32_s32:
4798 case Intrinsic::nvvm_tex_3d_v4f32_f32:
4799 case Intrinsic::nvvm_tex_3d_level_v4f32_f32:
4800 case Intrinsic::nvvm_tex_3d_grad_v4f32_f32:
4801 case Intrinsic::nvvm_tex_cube_v4f32_f32:
4802 case Intrinsic::nvvm_tex_cube_level_v4f32_f32:
4803 case Intrinsic::nvvm_tex_cube_array_v4f32_f32:
4804 case Intrinsic::nvvm_tex_cube_array_level_v4f32_f32:
4805 case Intrinsic::nvvm_tld4_r_2d_v4f32_f32:
4806 case Intrinsic::nvvm_tld4_g_2d_v4f32_f32:
4807 case Intrinsic::nvvm_tld4_b_2d_v4f32_f32:
4808 case Intrinsic::nvvm_tld4_a_2d_v4f32_f32:
4809 case Intrinsic::nvvm_tex_unified_1d_v4f32_s32:
4810 case Intrinsic::nvvm_tex_unified_1d_v4f32_f32:
4811 case Intrinsic::nvvm_tex_unified_1d_level_v4f32_f32:
4812 case Intrinsic::nvvm_tex_unified_1d_grad_v4f32_f32:
4813 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_s32:
4814 case Intrinsic::nvvm_tex_unified_1d_array_v4f32_f32:
4815 case Intrinsic::nvvm_tex_unified_1d_array_level_v4f32_f32:
4816 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4f32_f32:
4817 case Intrinsic::nvvm_tex_unified_2d_v4f32_s32:
4818 case Intrinsic::nvvm_tex_unified_2d_v4f32_f32:
4819 case Intrinsic::nvvm_tex_unified_2d_level_v4f32_f32:
4820 case Intrinsic::nvvm_tex_unified_2d_grad_v4f32_f32:
4821 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_s32:
4822 case Intrinsic::nvvm_tex_unified_2d_array_v4f32_f32:
4823 case Intrinsic::nvvm_tex_unified_2d_array_level_v4f32_f32:
4824 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4f32_f32:
4825 case Intrinsic::nvvm_tex_unified_3d_v4f32_s32:
4826 case Intrinsic::nvvm_tex_unified_3d_v4f32_f32:
4827 case Intrinsic::nvvm_tex_unified_3d_level_v4f32_f32:
4828 case Intrinsic::nvvm_tex_unified_3d_grad_v4f32_f32:
4829 case Intrinsic::nvvm_tex_unified_cube_v4f32_f32:
4830 case Intrinsic::nvvm_tex_unified_cube_level_v4f32_f32:
4831 case Intrinsic::nvvm_tex_unified_cube_array_v4f32_f32:
4832 case Intrinsic::nvvm_tex_unified_cube_array_level_v4f32_f32:
4833 case Intrinsic::nvvm_tex_unified_cube_grad_v4f32_f32:
4834 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4f32_f32:
4835 case Intrinsic::nvvm_tld4_unified_r_2d_v4f32_f32:
4836 case Intrinsic::nvvm_tld4_unified_g_2d_v4f32_f32:
4837 case Intrinsic::nvvm_tld4_unified_b_2d_v4f32_f32:
4838 case Intrinsic::nvvm_tld4_unified_a_2d_v4f32_f32:
4839 Info.opc = ISD::INTRINSIC_W_CHAIN;
4840 Info.memVT = MVT::v4f32;
4841 Info.ptrVal = nullptr;
4842 Info.offset = 0;
4843 Info.flags = MachineMemOperand::MOLoad;
4844 Info.align = Align(16);
4845 Infos.push_back(Elt: Info);
4846 return;
4847
4848 case Intrinsic::nvvm_tex_1d_v4s32_s32:
4849 case Intrinsic::nvvm_tex_1d_v4s32_f32:
4850 case Intrinsic::nvvm_tex_1d_level_v4s32_f32:
4851 case Intrinsic::nvvm_tex_1d_grad_v4s32_f32:
4852 case Intrinsic::nvvm_tex_1d_array_v4s32_s32:
4853 case Intrinsic::nvvm_tex_1d_array_v4s32_f32:
4854 case Intrinsic::nvvm_tex_1d_array_level_v4s32_f32:
4855 case Intrinsic::nvvm_tex_1d_array_grad_v4s32_f32:
4856 case Intrinsic::nvvm_tex_2d_v4s32_s32:
4857 case Intrinsic::nvvm_tex_2d_v4s32_f32:
4858 case Intrinsic::nvvm_tex_2d_level_v4s32_f32:
4859 case Intrinsic::nvvm_tex_2d_grad_v4s32_f32:
4860 case Intrinsic::nvvm_tex_2d_array_v4s32_s32:
4861 case Intrinsic::nvvm_tex_2d_array_v4s32_f32:
4862 case Intrinsic::nvvm_tex_2d_array_level_v4s32_f32:
4863 case Intrinsic::nvvm_tex_2d_array_grad_v4s32_f32:
4864 case Intrinsic::nvvm_tex_3d_v4s32_s32:
4865 case Intrinsic::nvvm_tex_3d_v4s32_f32:
4866 case Intrinsic::nvvm_tex_3d_level_v4s32_f32:
4867 case Intrinsic::nvvm_tex_3d_grad_v4s32_f32:
4868 case Intrinsic::nvvm_tex_cube_v4s32_f32:
4869 case Intrinsic::nvvm_tex_cube_level_v4s32_f32:
4870 case Intrinsic::nvvm_tex_cube_array_v4s32_f32:
4871 case Intrinsic::nvvm_tex_cube_array_level_v4s32_f32:
4872 case Intrinsic::nvvm_tex_cube_v4u32_f32:
4873 case Intrinsic::nvvm_tex_cube_level_v4u32_f32:
4874 case Intrinsic::nvvm_tex_cube_array_v4u32_f32:
4875 case Intrinsic::nvvm_tex_cube_array_level_v4u32_f32:
4876 case Intrinsic::nvvm_tex_1d_v4u32_s32:
4877 case Intrinsic::nvvm_tex_1d_v4u32_f32:
4878 case Intrinsic::nvvm_tex_1d_level_v4u32_f32:
4879 case Intrinsic::nvvm_tex_1d_grad_v4u32_f32:
4880 case Intrinsic::nvvm_tex_1d_array_v4u32_s32:
4881 case Intrinsic::nvvm_tex_1d_array_v4u32_f32:
4882 case Intrinsic::nvvm_tex_1d_array_level_v4u32_f32:
4883 case Intrinsic::nvvm_tex_1d_array_grad_v4u32_f32:
4884 case Intrinsic::nvvm_tex_2d_v4u32_s32:
4885 case Intrinsic::nvvm_tex_2d_v4u32_f32:
4886 case Intrinsic::nvvm_tex_2d_level_v4u32_f32:
4887 case Intrinsic::nvvm_tex_2d_grad_v4u32_f32:
4888 case Intrinsic::nvvm_tex_2d_array_v4u32_s32:
4889 case Intrinsic::nvvm_tex_2d_array_v4u32_f32:
4890 case Intrinsic::nvvm_tex_2d_array_level_v4u32_f32:
4891 case Intrinsic::nvvm_tex_2d_array_grad_v4u32_f32:
4892 case Intrinsic::nvvm_tex_3d_v4u32_s32:
4893 case Intrinsic::nvvm_tex_3d_v4u32_f32:
4894 case Intrinsic::nvvm_tex_3d_level_v4u32_f32:
4895 case Intrinsic::nvvm_tex_3d_grad_v4u32_f32:
4896 case Intrinsic::nvvm_tld4_r_2d_v4s32_f32:
4897 case Intrinsic::nvvm_tld4_g_2d_v4s32_f32:
4898 case Intrinsic::nvvm_tld4_b_2d_v4s32_f32:
4899 case Intrinsic::nvvm_tld4_a_2d_v4s32_f32:
4900 case Intrinsic::nvvm_tld4_r_2d_v4u32_f32:
4901 case Intrinsic::nvvm_tld4_g_2d_v4u32_f32:
4902 case Intrinsic::nvvm_tld4_b_2d_v4u32_f32:
4903 case Intrinsic::nvvm_tld4_a_2d_v4u32_f32:
4904 case Intrinsic::nvvm_tex_unified_1d_v4s32_s32:
4905 case Intrinsic::nvvm_tex_unified_1d_v4s32_f32:
4906 case Intrinsic::nvvm_tex_unified_1d_level_v4s32_f32:
4907 case Intrinsic::nvvm_tex_unified_1d_grad_v4s32_f32:
4908 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_s32:
4909 case Intrinsic::nvvm_tex_unified_1d_array_v4s32_f32:
4910 case Intrinsic::nvvm_tex_unified_1d_array_level_v4s32_f32:
4911 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4s32_f32:
4912 case Intrinsic::nvvm_tex_unified_2d_v4s32_s32:
4913 case Intrinsic::nvvm_tex_unified_2d_v4s32_f32:
4914 case Intrinsic::nvvm_tex_unified_2d_level_v4s32_f32:
4915 case Intrinsic::nvvm_tex_unified_2d_grad_v4s32_f32:
4916 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_s32:
4917 case Intrinsic::nvvm_tex_unified_2d_array_v4s32_f32:
4918 case Intrinsic::nvvm_tex_unified_2d_array_level_v4s32_f32:
4919 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4s32_f32:
4920 case Intrinsic::nvvm_tex_unified_3d_v4s32_s32:
4921 case Intrinsic::nvvm_tex_unified_3d_v4s32_f32:
4922 case Intrinsic::nvvm_tex_unified_3d_level_v4s32_f32:
4923 case Intrinsic::nvvm_tex_unified_3d_grad_v4s32_f32:
4924 case Intrinsic::nvvm_tex_unified_1d_v4u32_s32:
4925 case Intrinsic::nvvm_tex_unified_1d_v4u32_f32:
4926 case Intrinsic::nvvm_tex_unified_1d_level_v4u32_f32:
4927 case Intrinsic::nvvm_tex_unified_1d_grad_v4u32_f32:
4928 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_s32:
4929 case Intrinsic::nvvm_tex_unified_1d_array_v4u32_f32:
4930 case Intrinsic::nvvm_tex_unified_1d_array_level_v4u32_f32:
4931 case Intrinsic::nvvm_tex_unified_1d_array_grad_v4u32_f32:
4932 case Intrinsic::nvvm_tex_unified_2d_v4u32_s32:
4933 case Intrinsic::nvvm_tex_unified_2d_v4u32_f32:
4934 case Intrinsic::nvvm_tex_unified_2d_level_v4u32_f32:
4935 case Intrinsic::nvvm_tex_unified_2d_grad_v4u32_f32:
4936 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_s32:
4937 case Intrinsic::nvvm_tex_unified_2d_array_v4u32_f32:
4938 case Intrinsic::nvvm_tex_unified_2d_array_level_v4u32_f32:
4939 case Intrinsic::nvvm_tex_unified_2d_array_grad_v4u32_f32:
4940 case Intrinsic::nvvm_tex_unified_3d_v4u32_s32:
4941 case Intrinsic::nvvm_tex_unified_3d_v4u32_f32:
4942 case Intrinsic::nvvm_tex_unified_3d_level_v4u32_f32:
4943 case Intrinsic::nvvm_tex_unified_3d_grad_v4u32_f32:
4944 case Intrinsic::nvvm_tex_unified_cube_v4s32_f32:
4945 case Intrinsic::nvvm_tex_unified_cube_level_v4s32_f32:
4946 case Intrinsic::nvvm_tex_unified_cube_array_v4s32_f32:
4947 case Intrinsic::nvvm_tex_unified_cube_array_level_v4s32_f32:
4948 case Intrinsic::nvvm_tex_unified_cube_v4u32_f32:
4949 case Intrinsic::nvvm_tex_unified_cube_level_v4u32_f32:
4950 case Intrinsic::nvvm_tex_unified_cube_array_v4u32_f32:
4951 case Intrinsic::nvvm_tex_unified_cube_array_level_v4u32_f32:
4952 case Intrinsic::nvvm_tex_unified_cube_grad_v4s32_f32:
4953 case Intrinsic::nvvm_tex_unified_cube_grad_v4u32_f32:
4954 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4s32_f32:
4955 case Intrinsic::nvvm_tex_unified_cube_array_grad_v4u32_f32:
4956 case Intrinsic::nvvm_tld4_unified_r_2d_v4s32_f32:
4957 case Intrinsic::nvvm_tld4_unified_g_2d_v4s32_f32:
4958 case Intrinsic::nvvm_tld4_unified_b_2d_v4s32_f32:
4959 case Intrinsic::nvvm_tld4_unified_a_2d_v4s32_f32:
4960 case Intrinsic::nvvm_tld4_unified_r_2d_v4u32_f32:
4961 case Intrinsic::nvvm_tld4_unified_g_2d_v4u32_f32:
4962 case Intrinsic::nvvm_tld4_unified_b_2d_v4u32_f32:
4963 case Intrinsic::nvvm_tld4_unified_a_2d_v4u32_f32:
4964 Info.opc = ISD::INTRINSIC_W_CHAIN;
4965 Info.memVT = MVT::v4i32;
4966 Info.ptrVal = nullptr;
4967 Info.offset = 0;
4968 Info.flags = MachineMemOperand::MOLoad;
4969 Info.align = Align(16);
4970 Infos.push_back(Elt: Info);
4971 return;
4972
4973 case Intrinsic::nvvm_suld_1d_i8_clamp:
4974 case Intrinsic::nvvm_suld_1d_v2i8_clamp:
4975 case Intrinsic::nvvm_suld_1d_v4i8_clamp:
4976 case Intrinsic::nvvm_suld_1d_array_i8_clamp:
4977 case Intrinsic::nvvm_suld_1d_array_v2i8_clamp:
4978 case Intrinsic::nvvm_suld_1d_array_v4i8_clamp:
4979 case Intrinsic::nvvm_suld_2d_i8_clamp:
4980 case Intrinsic::nvvm_suld_2d_v2i8_clamp:
4981 case Intrinsic::nvvm_suld_2d_v4i8_clamp:
4982 case Intrinsic::nvvm_suld_2d_array_i8_clamp:
4983 case Intrinsic::nvvm_suld_2d_array_v2i8_clamp:
4984 case Intrinsic::nvvm_suld_2d_array_v4i8_clamp:
4985 case Intrinsic::nvvm_suld_3d_i8_clamp:
4986 case Intrinsic::nvvm_suld_3d_v2i8_clamp:
4987 case Intrinsic::nvvm_suld_3d_v4i8_clamp:
4988 case Intrinsic::nvvm_suld_1d_i8_trap:
4989 case Intrinsic::nvvm_suld_1d_v2i8_trap:
4990 case Intrinsic::nvvm_suld_1d_v4i8_trap:
4991 case Intrinsic::nvvm_suld_1d_array_i8_trap:
4992 case Intrinsic::nvvm_suld_1d_array_v2i8_trap:
4993 case Intrinsic::nvvm_suld_1d_array_v4i8_trap:
4994 case Intrinsic::nvvm_suld_2d_i8_trap:
4995 case Intrinsic::nvvm_suld_2d_v2i8_trap:
4996 case Intrinsic::nvvm_suld_2d_v4i8_trap:
4997 case Intrinsic::nvvm_suld_2d_array_i8_trap:
4998 case Intrinsic::nvvm_suld_2d_array_v2i8_trap:
4999 case Intrinsic::nvvm_suld_2d_array_v4i8_trap:
5000 case Intrinsic::nvvm_suld_3d_i8_trap:
5001 case Intrinsic::nvvm_suld_3d_v2i8_trap:
5002 case Intrinsic::nvvm_suld_3d_v4i8_trap:
5003 case Intrinsic::nvvm_suld_1d_i8_zero:
5004 case Intrinsic::nvvm_suld_1d_v2i8_zero:
5005 case Intrinsic::nvvm_suld_1d_v4i8_zero:
5006 case Intrinsic::nvvm_suld_1d_array_i8_zero:
5007 case Intrinsic::nvvm_suld_1d_array_v2i8_zero:
5008 case Intrinsic::nvvm_suld_1d_array_v4i8_zero:
5009 case Intrinsic::nvvm_suld_2d_i8_zero:
5010 case Intrinsic::nvvm_suld_2d_v2i8_zero:
5011 case Intrinsic::nvvm_suld_2d_v4i8_zero:
5012 case Intrinsic::nvvm_suld_2d_array_i8_zero:
5013 case Intrinsic::nvvm_suld_2d_array_v2i8_zero:
5014 case Intrinsic::nvvm_suld_2d_array_v4i8_zero:
5015 case Intrinsic::nvvm_suld_3d_i8_zero:
5016 case Intrinsic::nvvm_suld_3d_v2i8_zero:
5017 case Intrinsic::nvvm_suld_3d_v4i8_zero:
5018 Info.opc = ISD::INTRINSIC_W_CHAIN;
5019 Info.memVT = MVT::i8;
5020 Info.ptrVal = nullptr;
5021 Info.offset = 0;
5022 Info.flags = MachineMemOperand::MOLoad;
5023 Info.align = Align(16);
5024 Infos.push_back(Elt: Info);
5025 return;
5026
5027 case Intrinsic::nvvm_suld_1d_i16_clamp:
5028 case Intrinsic::nvvm_suld_1d_v2i16_clamp:
5029 case Intrinsic::nvvm_suld_1d_v4i16_clamp:
5030 case Intrinsic::nvvm_suld_1d_array_i16_clamp:
5031 case Intrinsic::nvvm_suld_1d_array_v2i16_clamp:
5032 case Intrinsic::nvvm_suld_1d_array_v4i16_clamp:
5033 case Intrinsic::nvvm_suld_2d_i16_clamp:
5034 case Intrinsic::nvvm_suld_2d_v2i16_clamp:
5035 case Intrinsic::nvvm_suld_2d_v4i16_clamp:
5036 case Intrinsic::nvvm_suld_2d_array_i16_clamp:
5037 case Intrinsic::nvvm_suld_2d_array_v2i16_clamp:
5038 case Intrinsic::nvvm_suld_2d_array_v4i16_clamp:
5039 case Intrinsic::nvvm_suld_3d_i16_clamp:
5040 case Intrinsic::nvvm_suld_3d_v2i16_clamp:
5041 case Intrinsic::nvvm_suld_3d_v4i16_clamp:
5042 case Intrinsic::nvvm_suld_1d_i16_trap:
5043 case Intrinsic::nvvm_suld_1d_v2i16_trap:
5044 case Intrinsic::nvvm_suld_1d_v4i16_trap:
5045 case Intrinsic::nvvm_suld_1d_array_i16_trap:
5046 case Intrinsic::nvvm_suld_1d_array_v2i16_trap:
5047 case Intrinsic::nvvm_suld_1d_array_v4i16_trap:
5048 case Intrinsic::nvvm_suld_2d_i16_trap:
5049 case Intrinsic::nvvm_suld_2d_v2i16_trap:
5050 case Intrinsic::nvvm_suld_2d_v4i16_trap:
5051 case Intrinsic::nvvm_suld_2d_array_i16_trap:
5052 case Intrinsic::nvvm_suld_2d_array_v2i16_trap:
5053 case Intrinsic::nvvm_suld_2d_array_v4i16_trap:
5054 case Intrinsic::nvvm_suld_3d_i16_trap:
5055 case Intrinsic::nvvm_suld_3d_v2i16_trap:
5056 case Intrinsic::nvvm_suld_3d_v4i16_trap:
5057 case Intrinsic::nvvm_suld_1d_i16_zero:
5058 case Intrinsic::nvvm_suld_1d_v2i16_zero:
5059 case Intrinsic::nvvm_suld_1d_v4i16_zero:
5060 case Intrinsic::nvvm_suld_1d_array_i16_zero:
5061 case Intrinsic::nvvm_suld_1d_array_v2i16_zero:
5062 case Intrinsic::nvvm_suld_1d_array_v4i16_zero:
5063 case Intrinsic::nvvm_suld_2d_i16_zero:
5064 case Intrinsic::nvvm_suld_2d_v2i16_zero:
5065 case Intrinsic::nvvm_suld_2d_v4i16_zero:
5066 case Intrinsic::nvvm_suld_2d_array_i16_zero:
5067 case Intrinsic::nvvm_suld_2d_array_v2i16_zero:
5068 case Intrinsic::nvvm_suld_2d_array_v4i16_zero:
5069 case Intrinsic::nvvm_suld_3d_i16_zero:
5070 case Intrinsic::nvvm_suld_3d_v2i16_zero:
5071 case Intrinsic::nvvm_suld_3d_v4i16_zero:
5072 Info.opc = ISD::INTRINSIC_W_CHAIN;
5073 Info.memVT = MVT::i16;
5074 Info.ptrVal = nullptr;
5075 Info.offset = 0;
5076 Info.flags = MachineMemOperand::MOLoad;
5077 Info.align = Align(16);
5078 Infos.push_back(Elt: Info);
5079 return;
5080
5081 case Intrinsic::nvvm_suld_1d_i32_clamp:
5082 case Intrinsic::nvvm_suld_1d_v2i32_clamp:
5083 case Intrinsic::nvvm_suld_1d_v4i32_clamp:
5084 case Intrinsic::nvvm_suld_1d_array_i32_clamp:
5085 case Intrinsic::nvvm_suld_1d_array_v2i32_clamp:
5086 case Intrinsic::nvvm_suld_1d_array_v4i32_clamp:
5087 case Intrinsic::nvvm_suld_2d_i32_clamp:
5088 case Intrinsic::nvvm_suld_2d_v2i32_clamp:
5089 case Intrinsic::nvvm_suld_2d_v4i32_clamp:
5090 case Intrinsic::nvvm_suld_2d_array_i32_clamp:
5091 case Intrinsic::nvvm_suld_2d_array_v2i32_clamp:
5092 case Intrinsic::nvvm_suld_2d_array_v4i32_clamp:
5093 case Intrinsic::nvvm_suld_3d_i32_clamp:
5094 case Intrinsic::nvvm_suld_3d_v2i32_clamp:
5095 case Intrinsic::nvvm_suld_3d_v4i32_clamp:
5096 case Intrinsic::nvvm_suld_1d_i32_trap:
5097 case Intrinsic::nvvm_suld_1d_v2i32_trap:
5098 case Intrinsic::nvvm_suld_1d_v4i32_trap:
5099 case Intrinsic::nvvm_suld_1d_array_i32_trap:
5100 case Intrinsic::nvvm_suld_1d_array_v2i32_trap:
5101 case Intrinsic::nvvm_suld_1d_array_v4i32_trap:
5102 case Intrinsic::nvvm_suld_2d_i32_trap:
5103 case Intrinsic::nvvm_suld_2d_v2i32_trap:
5104 case Intrinsic::nvvm_suld_2d_v4i32_trap:
5105 case Intrinsic::nvvm_suld_2d_array_i32_trap:
5106 case Intrinsic::nvvm_suld_2d_array_v2i32_trap:
5107 case Intrinsic::nvvm_suld_2d_array_v4i32_trap:
5108 case Intrinsic::nvvm_suld_3d_i32_trap:
5109 case Intrinsic::nvvm_suld_3d_v2i32_trap:
5110 case Intrinsic::nvvm_suld_3d_v4i32_trap:
5111 case Intrinsic::nvvm_suld_1d_i32_zero:
5112 case Intrinsic::nvvm_suld_1d_v2i32_zero:
5113 case Intrinsic::nvvm_suld_1d_v4i32_zero:
5114 case Intrinsic::nvvm_suld_1d_array_i32_zero:
5115 case Intrinsic::nvvm_suld_1d_array_v2i32_zero:
5116 case Intrinsic::nvvm_suld_1d_array_v4i32_zero:
5117 case Intrinsic::nvvm_suld_2d_i32_zero:
5118 case Intrinsic::nvvm_suld_2d_v2i32_zero:
5119 case Intrinsic::nvvm_suld_2d_v4i32_zero:
5120 case Intrinsic::nvvm_suld_2d_array_i32_zero:
5121 case Intrinsic::nvvm_suld_2d_array_v2i32_zero:
5122 case Intrinsic::nvvm_suld_2d_array_v4i32_zero:
5123 case Intrinsic::nvvm_suld_3d_i32_zero:
5124 case Intrinsic::nvvm_suld_3d_v2i32_zero:
5125 case Intrinsic::nvvm_suld_3d_v4i32_zero:
5126 Info.opc = ISD::INTRINSIC_W_CHAIN;
5127 Info.memVT = MVT::i32;
5128 Info.ptrVal = nullptr;
5129 Info.offset = 0;
5130 Info.flags = MachineMemOperand::MOLoad;
5131 Info.align = Align(16);
5132 Infos.push_back(Elt: Info);
5133 return;
5134
5135 case Intrinsic::nvvm_suld_1d_i64_clamp:
5136 case Intrinsic::nvvm_suld_1d_v2i64_clamp:
5137 case Intrinsic::nvvm_suld_1d_array_i64_clamp:
5138 case Intrinsic::nvvm_suld_1d_array_v2i64_clamp:
5139 case Intrinsic::nvvm_suld_2d_i64_clamp:
5140 case Intrinsic::nvvm_suld_2d_v2i64_clamp:
5141 case Intrinsic::nvvm_suld_2d_array_i64_clamp:
5142 case Intrinsic::nvvm_suld_2d_array_v2i64_clamp:
5143 case Intrinsic::nvvm_suld_3d_i64_clamp:
5144 case Intrinsic::nvvm_suld_3d_v2i64_clamp:
5145 case Intrinsic::nvvm_suld_1d_i64_trap:
5146 case Intrinsic::nvvm_suld_1d_v2i64_trap:
5147 case Intrinsic::nvvm_suld_1d_array_i64_trap:
5148 case Intrinsic::nvvm_suld_1d_array_v2i64_trap:
5149 case Intrinsic::nvvm_suld_2d_i64_trap:
5150 case Intrinsic::nvvm_suld_2d_v2i64_trap:
5151 case Intrinsic::nvvm_suld_2d_array_i64_trap:
5152 case Intrinsic::nvvm_suld_2d_array_v2i64_trap:
5153 case Intrinsic::nvvm_suld_3d_i64_trap:
5154 case Intrinsic::nvvm_suld_3d_v2i64_trap:
5155 case Intrinsic::nvvm_suld_1d_i64_zero:
5156 case Intrinsic::nvvm_suld_1d_v2i64_zero:
5157 case Intrinsic::nvvm_suld_1d_array_i64_zero:
5158 case Intrinsic::nvvm_suld_1d_array_v2i64_zero:
5159 case Intrinsic::nvvm_suld_2d_i64_zero:
5160 case Intrinsic::nvvm_suld_2d_v2i64_zero:
5161 case Intrinsic::nvvm_suld_2d_array_i64_zero:
5162 case Intrinsic::nvvm_suld_2d_array_v2i64_zero:
5163 case Intrinsic::nvvm_suld_3d_i64_zero:
5164 case Intrinsic::nvvm_suld_3d_v2i64_zero:
5165 Info.opc = ISD::INTRINSIC_W_CHAIN;
5166 Info.memVT = MVT::i64;
5167 Info.ptrVal = nullptr;
5168 Info.offset = 0;
5169 Info.flags = MachineMemOperand::MOLoad;
5170 Info.align = Align(16);
5171 Infos.push_back(Elt: Info);
5172 return;
5173
5174 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
5175 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
5176 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1: {
5177 Info.opc = ISD::INTRINSIC_W_CHAIN;
5178 Info.memVT = MVT::v1i32;
5179 Info.ptrVal = I.getArgOperand(i: 0);
5180 Info.offset = 0;
5181 Info.flags = MachineMemOperand::MOLoad;
5182 Info.align.reset();
5183 Infos.push_back(Elt: Info);
5184 return;
5185 }
5186
5187 case Intrinsic::nvvm_tcgen05_ld_16x64b_x2:
5188 case Intrinsic::nvvm_tcgen05_ld_16x128b_x1:
5189 case Intrinsic::nvvm_tcgen05_ld_32x32b_x2:
5190 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x2:
5191 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_i32:
5192 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_i32: {
5193 Info.opc = ISD::INTRINSIC_W_CHAIN;
5194 Info.memVT = MVT::v2i32;
5195 Info.ptrVal = I.getArgOperand(i: 0);
5196 Info.offset = 0;
5197 Info.flags = MachineMemOperand::MOLoad;
5198 Info.align.reset();
5199 Infos.push_back(Elt: Info);
5200 return;
5201 }
5202
5203 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x2_f32:
5204 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x2_f32: {
5205 Info.opc = ISD::INTRINSIC_W_CHAIN;
5206 Info.memVT = MVT::v2f32;
5207 Info.ptrVal = I.getArgOperand(i: 0);
5208 Info.offset = 0;
5209 Info.flags = MachineMemOperand::MOLoad;
5210 Info.align.reset();
5211 Infos.push_back(Elt: Info);
5212 return;
5213 }
5214
5215 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
5216 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
5217 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
5218 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
5219 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
5220 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_i32:
5221 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_i32: {
5222 Info.opc = ISD::INTRINSIC_W_CHAIN;
5223 Info.memVT = MVT::v4i32;
5224 Info.ptrVal = I.getArgOperand(i: 0);
5225 Info.offset = 0;
5226 Info.flags = MachineMemOperand::MOLoad;
5227 Info.align.reset();
5228 Infos.push_back(Elt: Info);
5229 return;
5230 }
5231
5232 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_f32:
5233 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_f32: {
5234 Info.opc = ISD::INTRINSIC_W_CHAIN;
5235 Info.memVT = MVT::v4f32;
5236 Info.ptrVal = I.getArgOperand(i: 0);
5237 Info.offset = 0;
5238 Info.flags = MachineMemOperand::MOLoad;
5239 Info.align.reset();
5240 Infos.push_back(Elt: Info);
5241 return;
5242 }
5243
5244 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
5245 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
5246 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
5247 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
5248 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
5249 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_i32:
5250 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_i32: {
5251 Info.opc = ISD::INTRINSIC_W_CHAIN;
5252 Info.memVT = MVT::v8i32;
5253 Info.ptrVal = I.getArgOperand(i: 0);
5254 Info.offset = 0;
5255 Info.flags = MachineMemOperand::MOLoad;
5256 Info.align.reset();
5257 Infos.push_back(Elt: Info);
5258 return;
5259 }
5260
5261 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_f32:
5262 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_f32: {
5263 Info.opc = ISD::INTRINSIC_W_CHAIN;
5264 Info.memVT = MVT::v8f32;
5265 Info.ptrVal = I.getArgOperand(i: 0);
5266 Info.offset = 0;
5267 Info.flags = MachineMemOperand::MOLoad;
5268 Info.align.reset();
5269 Infos.push_back(Elt: Info);
5270 return;
5271 }
5272
5273 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
5274 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
5275 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
5276 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
5277 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
5278 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_i32:
5279 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_i32: {
5280 Info.opc = ISD::INTRINSIC_W_CHAIN;
5281 Info.memVT = MVT::v16i32;
5282 Info.ptrVal = I.getArgOperand(i: 0);
5283 Info.offset = 0;
5284 Info.flags = MachineMemOperand::MOLoad;
5285 Info.align.reset();
5286 Infos.push_back(Elt: Info);
5287 return;
5288 }
5289
5290 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_f32:
5291 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_f32: {
5292 Info.opc = ISD::INTRINSIC_W_CHAIN;
5293 Info.memVT = MVT::v16f32;
5294 Info.ptrVal = I.getArgOperand(i: 0);
5295 Info.offset = 0;
5296 Info.flags = MachineMemOperand::MOLoad;
5297 Info.align.reset();
5298 Infos.push_back(Elt: Info);
5299 return;
5300 }
5301
5302 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
5303 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
5304 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
5305 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
5306 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
5307 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_i32:
5308 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_i32: {
5309 Info.opc = ISD::INTRINSIC_W_CHAIN;
5310 Info.memVT = MVT::v32i32;
5311 Info.ptrVal = I.getArgOperand(i: 0);
5312 Info.offset = 0;
5313 Info.flags = MachineMemOperand::MOLoad;
5314 Info.align.reset();
5315 Infos.push_back(Elt: Info);
5316 return;
5317 }
5318
5319 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_f32:
5320 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_f32: {
5321 Info.opc = ISD::INTRINSIC_W_CHAIN;
5322 Info.memVT = MVT::v32f32;
5323 Info.ptrVal = I.getArgOperand(i: 0);
5324 Info.offset = 0;
5325 Info.flags = MachineMemOperand::MOLoad;
5326 Info.align.reset();
5327 Infos.push_back(Elt: Info);
5328 return;
5329 }
5330
5331 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
5332 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
5333 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
5334 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
5335 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
5336 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_i32:
5337 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_i32: {
5338 Info.opc = ISD::INTRINSIC_W_CHAIN;
5339 Info.memVT = MVT::v64i32;
5340 Info.ptrVal = I.getArgOperand(i: 0);
5341 Info.offset = 0;
5342 Info.flags = MachineMemOperand::MOLoad;
5343 Info.align.reset();
5344 Infos.push_back(Elt: Info);
5345 return;
5346 }
5347
5348 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_f32:
5349 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_f32: {
5350 Info.opc = ISD::INTRINSIC_W_CHAIN;
5351 Info.memVT = MVT::v64f32;
5352 Info.ptrVal = I.getArgOperand(i: 0);
5353 Info.offset = 0;
5354 Info.flags = MachineMemOperand::MOLoad;
5355 Info.align.reset();
5356 Infos.push_back(Elt: Info);
5357 return;
5358 }
5359
5360 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
5361 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
5362 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
5363 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
5364 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
5365 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_i32:
5366 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_i32: {
5367 Info.opc = ISD::INTRINSIC_W_CHAIN;
5368 Info.memVT = MVT::v128i32;
5369 Info.ptrVal = I.getArgOperand(i: 0);
5370 Info.offset = 0;
5371 Info.flags = MachineMemOperand::MOLoad;
5372 Info.align.reset();
5373 Infos.push_back(Elt: Info);
5374 return;
5375 }
5376
5377 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_f32:
5378 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_f32: {
5379 Info.opc = ISD::INTRINSIC_W_CHAIN;
5380 Info.memVT = MVT::v128f32;
5381 Info.ptrVal = I.getArgOperand(i: 0);
5382 Info.offset = 0;
5383 Info.flags = MachineMemOperand::MOLoad;
5384 Info.align.reset();
5385 Infos.push_back(Elt: Info);
5386 return;
5387 }
5388
5389 case Intrinsic::nvvm_tcgen05_st_16x64b_x1:
5390 case Intrinsic::nvvm_tcgen05_st_32x32b_x1:
5391 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x1: {
5392 Info.opc = ISD::INTRINSIC_VOID;
5393 Info.memVT = MVT::v1i32;
5394 Info.ptrVal = I.getArgOperand(i: 0);
5395 Info.offset = 0;
5396 Info.flags = MachineMemOperand::MOStore;
5397 Info.align.reset();
5398 Infos.push_back(Elt: Info);
5399 return;
5400 }
5401
5402 case Intrinsic::nvvm_tcgen05_st_16x64b_x2:
5403 case Intrinsic::nvvm_tcgen05_st_16x128b_x1:
5404 case Intrinsic::nvvm_tcgen05_st_32x32b_x2:
5405 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x2: {
5406 Info.opc = ISD::INTRINSIC_VOID;
5407 Info.memVT = MVT::v2i32;
5408 Info.ptrVal = I.getArgOperand(i: 0);
5409 Info.offset = 0;
5410 Info.flags = MachineMemOperand::MOStore;
5411 Info.align.reset();
5412 Infos.push_back(Elt: Info);
5413 return;
5414 }
5415
5416 case Intrinsic::nvvm_tcgen05_st_16x64b_x4:
5417 case Intrinsic::nvvm_tcgen05_st_16x128b_x2:
5418 case Intrinsic::nvvm_tcgen05_st_16x256b_x1:
5419 case Intrinsic::nvvm_tcgen05_st_32x32b_x4:
5420 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x4: {
5421 Info.opc = ISD::INTRINSIC_VOID;
5422 Info.memVT = MVT::v4i32;
5423 Info.ptrVal = I.getArgOperand(i: 0);
5424 Info.offset = 0;
5425 Info.flags = MachineMemOperand::MOStore;
5426 Info.align.reset();
5427 Infos.push_back(Elt: Info);
5428 return;
5429 }
5430
5431 case Intrinsic::nvvm_tcgen05_st_16x64b_x8:
5432 case Intrinsic::nvvm_tcgen05_st_16x128b_x4:
5433 case Intrinsic::nvvm_tcgen05_st_16x256b_x2:
5434 case Intrinsic::nvvm_tcgen05_st_32x32b_x8:
5435 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x8: {
5436 Info.opc = ISD::INTRINSIC_VOID;
5437 Info.memVT = MVT::v8i32;
5438 Info.ptrVal = I.getArgOperand(i: 0);
5439 Info.offset = 0;
5440 Info.flags = MachineMemOperand::MOStore;
5441 Info.align.reset();
5442 Infos.push_back(Elt: Info);
5443 return;
5444 }
5445
5446 case Intrinsic::nvvm_tcgen05_st_16x64b_x16:
5447 case Intrinsic::nvvm_tcgen05_st_16x128b_x8:
5448 case Intrinsic::nvvm_tcgen05_st_16x256b_x4:
5449 case Intrinsic::nvvm_tcgen05_st_32x32b_x16:
5450 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x16: {
5451 Info.opc = ISD::INTRINSIC_VOID;
5452 Info.memVT = MVT::v16i32;
5453 Info.ptrVal = I.getArgOperand(i: 0);
5454 Info.offset = 0;
5455 Info.flags = MachineMemOperand::MOStore;
5456 Info.align.reset();
5457 Infos.push_back(Elt: Info);
5458 return;
5459 }
5460
5461 case Intrinsic::nvvm_tcgen05_st_16x64b_x32:
5462 case Intrinsic::nvvm_tcgen05_st_16x128b_x16:
5463 case Intrinsic::nvvm_tcgen05_st_16x256b_x8:
5464 case Intrinsic::nvvm_tcgen05_st_32x32b_x32:
5465 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x32: {
5466 Info.opc = ISD::INTRINSIC_VOID;
5467 Info.memVT = MVT::v32i32;
5468 Info.ptrVal = I.getArgOperand(i: 0);
5469 Info.offset = 0;
5470 Info.flags = MachineMemOperand::MOStore;
5471 Info.align.reset();
5472 Infos.push_back(Elt: Info);
5473 return;
5474 }
5475
5476 case Intrinsic::nvvm_tcgen05_st_16x64b_x64:
5477 case Intrinsic::nvvm_tcgen05_st_16x128b_x32:
5478 case Intrinsic::nvvm_tcgen05_st_16x256b_x16:
5479 case Intrinsic::nvvm_tcgen05_st_32x32b_x64:
5480 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x64: {
5481 Info.opc = ISD::INTRINSIC_VOID;
5482 Info.memVT = MVT::v64i32;
5483 Info.ptrVal = I.getArgOperand(i: 0);
5484 Info.offset = 0;
5485 Info.flags = MachineMemOperand::MOStore;
5486 Info.align.reset();
5487 Infos.push_back(Elt: Info);
5488 return;
5489 }
5490
5491 case Intrinsic::nvvm_tcgen05_st_16x64b_x128:
5492 case Intrinsic::nvvm_tcgen05_st_16x128b_x64:
5493 case Intrinsic::nvvm_tcgen05_st_16x256b_x32:
5494 case Intrinsic::nvvm_tcgen05_st_32x32b_x128:
5495 case Intrinsic::nvvm_tcgen05_st_16x32bx2_x128: {
5496 Info.opc = ISD::INTRINSIC_VOID;
5497 Info.memVT = MVT::v128i32;
5498 Info.ptrVal = I.getArgOperand(i: 0);
5499 Info.offset = 0;
5500 Info.flags = MachineMemOperand::MOStore;
5501 Info.align.reset();
5502 Infos.push_back(Elt: Info);
5503 return;
5504 }
5505 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg1:
5506 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg1:
5507 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg1:
5508 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg1:
5509 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1:
5510 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1:
5511 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg1_ashift:
5512 case Intrinsic::
5513 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg1_ashift:
5514 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1:
5515 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1:
5516 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg1_ashift:
5517 case Intrinsic::
5518 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg1_ashift: {
5519 // We are reading and writing back to TMem
5520 Info.opc = ISD::INTRINSIC_VOID;
5521 Info.memVT = MVT::v4i32;
5522 Info.ptrVal = I.getArgOperand(i: 0);
5523 Info.offset = 0;
5524 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
5525 Info.align = Align(16);
5526 Infos.push_back(Elt: Info);
5527 return;
5528 }
5529
5530 case Intrinsic::nvvm_tcgen05_mma_shared_disable_output_lane_cg2:
5531 case Intrinsic::nvvm_tcgen05_mma_shared_scale_d_disable_output_lane_cg2:
5532 case Intrinsic::nvvm_tcgen05_mma_sp_shared_disable_output_lane_cg2:
5533 case Intrinsic::nvvm_tcgen05_mma_sp_shared_scale_d_disable_output_lane_cg2:
5534 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2:
5535 case Intrinsic::nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2:
5536 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2:
5537 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2:
5538 case Intrinsic::nvvm_tcgen05_mma_tensor_disable_output_lane_cg2_ashift:
5539 case Intrinsic::
5540 nvvm_tcgen05_mma_tensor_scale_d_disable_output_lane_cg2_ashift:
5541 case Intrinsic::nvvm_tcgen05_mma_sp_tensor_disable_output_lane_cg2_ashift:
5542 case Intrinsic::
5543 nvvm_tcgen05_mma_sp_tensor_scale_d_disable_output_lane_cg2_ashift: {
5544 // We are reading and writing back to TMem
5545 Info.opc = ISD::INTRINSIC_VOID;
5546 Info.memVT = MVT::v8i32;
5547 Info.ptrVal = I.getArgOperand(i: 0);
5548 Info.offset = 0;
5549 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
5550 Info.align = Align(16);
5551 Infos.push_back(Elt: Info);
5552 return;
5553 }
5554 }
5555}
5556
5557// Helper for getting a function parameter name. Name is composed from
5558// its index and the function name. Negative index corresponds to special
5559// parameter (unsized array) used for passing variable arguments.
5560std::string NVPTXTargetLowering::getParamName(const Function *F,
5561 int Idx) const {
5562 std::string ParamName;
5563 raw_string_ostream ParamStr(ParamName);
5564
5565 ParamStr << getTargetMachine().getSymbol(GV: F)->getName();
5566 if (Idx < 0)
5567 ParamStr << "_vararg";
5568 else
5569 ParamStr << "_param_" << Idx;
5570
5571 return ParamName;
5572}
5573
5574/// isLegalAddressingMode - Return true if the addressing mode represented
5575/// by AM is legal for this target, for a load/store of the specified type.
5576/// Used to guide target specific optimizations, like loop strength reduction
5577/// (LoopStrengthReduce.cpp) and memory optimization for address mode
5578/// (CodeGenPrepare.cpp)
5579bool NVPTXTargetLowering::isLegalAddressingMode(const DataLayout &DL,
5580 const AddrMode &AM, Type *Ty,
5581 unsigned AS, Instruction *I) const {
5582 // AddrMode - This represents an addressing mode of:
5583 // BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
5584 //
5585 // The legal address modes are
5586 // - [avar]
5587 // - [areg]
5588 // - [areg+immoff]
5589 // - [immAddr]
5590
5591 // immoff must fit in a signed 32-bit int
5592 if (!APInt(64, AM.BaseOffs).isSignedIntN(N: 32))
5593 return false;
5594
5595 if (AM.BaseGV)
5596 return !AM.BaseOffs && !AM.HasBaseReg && !AM.Scale;
5597
5598 switch (AM.Scale) {
5599 case 0: // "r", "r+i" or "i" is allowed
5600 break;
5601 case 1:
5602 if (AM.HasBaseReg) // "r+r+i" or "r+r" is not allowed.
5603 return false;
5604 // Otherwise we have r+i.
5605 break;
5606 default:
5607 // No scale > 1 is allowed
5608 return false;
5609 }
5610 return true;
5611}
5612
5613//===----------------------------------------------------------------------===//
5614// NVPTX Inline Assembly Support
5615//===----------------------------------------------------------------------===//
5616
5617/// getConstraintType - Given a constraint letter, return the type of
5618/// constraint it is for this target.
5619NVPTXTargetLowering::ConstraintType
5620NVPTXTargetLowering::getConstraintType(StringRef Constraint) const {
5621 if (Constraint.size() == 1) {
5622 switch (Constraint[0]) {
5623 default:
5624 break;
5625 case 'b':
5626 case 'r':
5627 case 'h':
5628 case 'c':
5629 case 'l':
5630 case 'f':
5631 case 'd':
5632 case 'q':
5633 case '0':
5634 case 'N':
5635 return C_RegisterClass;
5636 }
5637 }
5638 return TargetLowering::getConstraintType(Constraint);
5639}
5640
5641std::pair<unsigned, const TargetRegisterClass *>
5642NVPTXTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5643 StringRef Constraint,
5644 MVT VT) const {
5645 if (Constraint.size() == 1) {
5646 switch (Constraint[0]) {
5647 case 'b':
5648 return std::make_pair(x: 0U, y: &NVPTX::B1RegClass);
5649 case 'c':
5650 case 'h':
5651 return std::make_pair(x: 0U, y: &NVPTX::B16RegClass);
5652 case 'r':
5653 case 'f':
5654 return std::make_pair(x: 0U, y: &NVPTX::B32RegClass);
5655 case 'l':
5656 case 'N':
5657 case 'd':
5658 return std::make_pair(x: 0U, y: &NVPTX::B64RegClass);
5659 case 'q': {
5660 if (STI.getSmVersion() < 70)
5661 report_fatal_error(reason: "Inline asm with 128 bit operands is only "
5662 "supported for sm_70 and higher!");
5663 return std::make_pair(x: 0U, y: &NVPTX::B128RegClass);
5664 }
5665 }
5666 }
5667 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5668}
5669
5670//===----------------------------------------------------------------------===//
5671// NVPTX DAG Combining
5672//===----------------------------------------------------------------------===//
5673
5674bool NVPTXTargetLowering::allowFMA(MachineFunction &MF,
5675 CodeGenOptLevel OptLevel) const {
5676 // Always honor command-line argument
5677 if (FMAContractLevelOpt.getNumOccurrences() > 0)
5678 return FMAContractLevelOpt > 0;
5679
5680 // Do not contract if we're not optimizing the code.
5681 if (OptLevel == CodeGenOptLevel::None)
5682 return false;
5683
5684 // Honor TargetOptions flags that explicitly say fusion is okay.
5685 if (MF.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast)
5686 return true;
5687
5688 return false;
5689}
5690
5691static bool isConstZero(const SDValue &Operand) {
5692 const auto *Const = dyn_cast<ConstantSDNode>(Val: Operand);
5693 return Const && Const->getZExtValue() == 0;
5694}
5695
5696/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
5697/// operands N0 and N1. This is a helper for PerformADDCombine that is
5698/// called with the default operands, and if that fails, with commuted
5699/// operands.
5700static SDValue
5701PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
5702 TargetLowering::DAGCombinerInfo &DCI) {
5703 EVT VT = N0.getValueType();
5704
5705 // Since integer multiply-add costs the same as integer multiply
5706 // but is more costly than integer add, do the fusion only when
5707 // the mul is only used in the add.
5708 // TODO: this may not be true for later architectures, consider relaxing this
5709 if (!N0.getNode()->hasOneUse())
5710 return SDValue();
5711
5712 // fold (add (select cond, 0, (mul a, b)), c)
5713 // -> (select cond, c, (add (mul a, b), c))
5714 //
5715 if (N0.getOpcode() == ISD::SELECT) {
5716 unsigned ZeroOpNum;
5717 if (isConstZero(Operand: N0->getOperand(Num: 1)))
5718 ZeroOpNum = 1;
5719 else if (isConstZero(Operand: N0->getOperand(Num: 2)))
5720 ZeroOpNum = 2;
5721 else
5722 return SDValue();
5723
5724 SDValue M = N0->getOperand(Num: (ZeroOpNum == 1) ? 2 : 1);
5725 if (M->getOpcode() != ISD::MUL || !M.getNode()->hasOneUse())
5726 return SDValue();
5727
5728 SDLoc DL(N);
5729 SDValue Mul =
5730 DCI.DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: M->getOperand(Num: 0), N2: M->getOperand(Num: 1));
5731 SDValue MAD = DCI.DAG.getNode(Opcode: ISD::ADD, DL, VT, N1: Mul, N2: N1);
5732 return DCI.DAG.getSelect(DL: SDLoc(N), VT, Cond: N0->getOperand(Num: 0),
5733 LHS: ((ZeroOpNum == 1) ? N1 : MAD),
5734 RHS: ((ZeroOpNum == 1) ? MAD : N1));
5735 }
5736
5737 return SDValue();
5738}
5739
5740SDValue NVPTXTargetLowering::performFADDCombineWithOperands(
5741 SDNode *N, SDValue N0, SDValue N1, TargetLowering::DAGCombinerInfo &DCI,
5742 CodeGenOptLevel OptLevel) const {
5743 EVT VT = N0.getValueType();
5744 if (N0.getOpcode() == ISD::FMUL) {
5745 if (!(allowFMA(MF&: DCI.DAG.getMachineFunction(), OptLevel) ||
5746 (N->getFlags().hasAllowContract() &&
5747 N0->getFlags().hasAllowContract())))
5748 return SDValue();
5749
5750 // For floating point:
5751 // Do the fusion only when the mul has less than 5 uses and all
5752 // are add.
5753 // The heuristic is that if a use is not an add, then that use
5754 // cannot be fused into fma, therefore mul is still needed anyway.
5755 // If there are more than 4 uses, even if they are all add, fusing
5756 // them will increase register pressue.
5757 //
5758 int numUses = 0;
5759 int nonAddCount = 0;
5760 for (const SDNode *User : N0.getNode()->users()) {
5761 numUses++;
5762 if (User->getOpcode() != ISD::FADD)
5763 ++nonAddCount;
5764 if (numUses >= 5)
5765 return SDValue();
5766 }
5767 if (nonAddCount) {
5768 int orderNo = N->getIROrder();
5769 int orderNo2 = N0.getNode()->getIROrder();
5770 // simple heuristics here for considering potential register
5771 // pressure, the logics here is that the differnce are used
5772 // to measure the distance between def and use, the longer distance
5773 // more likely cause register pressure.
5774 if (orderNo - orderNo2 < 500)
5775 return SDValue();
5776
5777 // Now, check if at least one of the FMUL's operands is live beyond the
5778 // node N, which guarantees that the FMA will not increase register
5779 // pressure at node N.
5780 bool opIsLive = false;
5781 const SDNode *left = N0.getOperand(i: 0).getNode();
5782 const SDNode *right = N0.getOperand(i: 1).getNode();
5783
5784 if (isa<ConstantSDNode>(Val: left) || isa<ConstantSDNode>(Val: right))
5785 opIsLive = true;
5786
5787 if (!opIsLive)
5788 for (const SDNode *User : left->users()) {
5789 int orderNo3 = User->getIROrder();
5790 if (orderNo3 > orderNo) {
5791 opIsLive = true;
5792 break;
5793 }
5794 }
5795
5796 if (!opIsLive)
5797 for (const SDNode *User : right->users()) {
5798 int orderNo3 = User->getIROrder();
5799 if (orderNo3 > orderNo) {
5800 opIsLive = true;
5801 break;
5802 }
5803 }
5804
5805 if (!opIsLive)
5806 return SDValue();
5807 }
5808
5809 return DCI.DAG.getNode(Opcode: ISD::FMA, DL: SDLoc(N), VT, N1: N0.getOperand(i: 0),
5810 N2: N0.getOperand(i: 1), N3: N1);
5811 }
5812
5813 return SDValue();
5814}
5815
5816/// Fold unpacking movs into a load by increasing the number of return values.
5817///
5818/// ex:
5819/// L: v2f16,ch = load <p>
5820/// a: f16 = extractelt L:0, 0
5821/// b: f16 = extractelt L:0, 1
5822/// use(a, b)
5823///
5824/// ...is turned into...
5825///
5826/// L: f16,f16,ch = LoadV2 <p>
5827/// use(L:0, L:1)
5828static SDValue
5829combineUnpackingMovIntoLoad(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
5830 // Don't run this optimization before the legalizer
5831 if (!DCI.isAfterLegalizeDAG())
5832 return SDValue();
5833
5834 EVT ElementVT = N->getValueType(ResNo: 0);
5835 // Avoid non-packed types and v4i8
5836 if (!NVPTX::isPackedVectorTy(VT: ElementVT) || ElementVT == MVT::v4i8)
5837 return SDValue();
5838
5839 // Check whether all outputs are either used by an extractelt or are
5840 // glue/chain nodes
5841 if (!all_of(Range: N->uses(), P: [&](SDUse &U) {
5842 // Skip glue, chain nodes
5843 if (U.getValueType() == MVT::Glue || U.getValueType() == MVT::Other)
5844 return true;
5845 if (U.getUser()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
5846 if (N->getOpcode() != ISD::LOAD)
5847 return true;
5848 // Since this is an ISD::LOAD, check all extractelts are used. If
5849 // any are not used, we don't want to defeat another optimization that
5850 // will narrow the load.
5851 //
5852 // For example:
5853 //
5854 // L: v2f16,ch = load <p>
5855 // e0: f16 = extractelt L:0, 0
5856 // e1: f16 = extractelt L:0, 1 <-- unused
5857 // store e0
5858 //
5859 // Can be optimized by DAGCombiner to:
5860 //
5861 // L: f16,ch = load <p>
5862 // store L:0
5863 return !U.getUser()->use_empty();
5864 }
5865
5866 // Otherwise, this use prevents us from splitting a value.
5867 return false;
5868 }))
5869 return SDValue();
5870
5871 auto *LD = cast<MemSDNode>(Val: N);
5872 SDLoc DL(LD);
5873
5874 // the new opcode after we double the number of operands
5875 unsigned Opcode;
5876 SmallVector<SDValue> Operands(LD->ops());
5877 unsigned OldNumOutputs; // non-glue, non-chain outputs
5878 switch (LD->getOpcode()) {
5879 case ISD::LOAD:
5880 OldNumOutputs = 1;
5881 // Any packed type is legal, so the legalizer will not have lowered
5882 // ISD::LOAD -> NVPTXISD::Load (unless it's under-aligned). We have to do it
5883 // here.
5884 Opcode = NVPTXISD::LoadV2;
5885 // append a "full" used bytes mask operand right before the extension type
5886 // operand, signifying that all bytes are used.
5887 Operands.push_back(Elt: DCI.DAG.getConstant(UINT32_MAX, DL, VT: MVT::i32));
5888 Operands.push_back(Elt: DCI.DAG.getIntPtrConstant(
5889 Val: cast<LoadSDNode>(Val: LD)->getExtensionType(), DL));
5890 break;
5891 case NVPTXISD::LoadV2:
5892 OldNumOutputs = 2;
5893 Opcode = NVPTXISD::LoadV4;
5894 break;
5895 case NVPTXISD::LoadV4:
5896 // V8 is only supported for f32/i32. Don't forget, we're not changing the
5897 // load size here. This is already a 256-bit load.
5898 if (ElementVT != MVT::v2f32 && ElementVT != MVT::v2i32)
5899 return SDValue();
5900 OldNumOutputs = 4;
5901 Opcode = NVPTXISD::LoadV8;
5902 break;
5903 case NVPTXISD::LoadV8:
5904 // PTX doesn't support the next doubling of outputs
5905 return SDValue();
5906 }
5907
5908 // the non-glue, non-chain outputs in the new load
5909 const unsigned NewNumOutputs = OldNumOutputs * 2;
5910 SmallVector<EVT> NewVTs(NewNumOutputs, ElementVT.getVectorElementType());
5911 // add remaining chain and glue values
5912 NewVTs.append(in_start: LD->value_begin() + OldNumOutputs, in_end: LD->value_end());
5913
5914 // Create the new load
5915 SDValue NewLoad = DCI.DAG.getMemIntrinsicNode(
5916 Opcode, dl: DL, VTList: DCI.DAG.getVTList(VTs: NewVTs), Ops: Operands, MemVT: LD->getMemoryVT(),
5917 MMO: LD->getMemOperand());
5918
5919 // Now we use a combination of BUILD_VECTORs and a MERGE_VALUES node to keep
5920 // the outputs the same. These nodes will be optimized away in later
5921 // DAGCombiner iterations.
5922 SmallVector<SDValue> Results;
5923 for (unsigned I : seq(Size: OldNumOutputs))
5924 Results.push_back(Elt: DCI.DAG.getBuildVector(
5925 VT: ElementVT, DL, Ops: {NewLoad.getValue(R: I * 2), NewLoad.getValue(R: I * 2 + 1)}));
5926 // Add remaining chain and glue nodes
5927 for (unsigned I : seq(Size: NewLoad->getNumValues() - NewNumOutputs))
5928 Results.push_back(Elt: NewLoad.getValue(R: NewNumOutputs + I));
5929
5930 return DCI.DAG.getMergeValues(Ops: Results, dl: DL);
5931}
5932
5933/// Fold packing movs into a store.
5934///
5935/// ex:
5936/// v1: v2f16 = BUILD_VECTOR a:f16, b:f16
5937/// v2: v2f16 = BUILD_VECTOR c:f16, d:f16
5938/// StoreV2 v1, v2
5939///
5940/// ...is turned into...
5941///
5942/// StoreV4 a, b, c, d
5943static SDValue combinePackingMovIntoStore(SDNode *N,
5944 TargetLowering::DAGCombinerInfo &DCI,
5945 unsigned Front, unsigned Back) {
5946 // We want to run this as late as possible since other optimizations may
5947 // eliminate the BUILD_VECTORs.
5948 if (!DCI.isAfterLegalizeDAG())
5949 return SDValue();
5950
5951 // Get the type of the operands being stored.
5952 EVT ElementVT = N->getOperand(Num: Front).getValueType();
5953
5954 // Avoid non-packed types and v4i8
5955 if (!NVPTX::isPackedVectorTy(VT: ElementVT) || ElementVT == MVT::v4i8)
5956 return SDValue();
5957
5958 auto *ST = cast<MemSDNode>(Val: N);
5959
5960 // The new opcode after we double the number of operands.
5961 unsigned Opcode;
5962 switch (N->getOpcode()) {
5963 case ISD::STORE:
5964 // Any packed type is legal, so the legalizer will not have lowered
5965 // ISD::STORE -> NVPTXISD::Store (unless it's under-aligned). We have to do
5966 // it here.
5967 Opcode = NVPTXISD::StoreV2;
5968 break;
5969 case NVPTXISD::StoreV2:
5970 Opcode = NVPTXISD::StoreV4;
5971 break;
5972 case NVPTXISD::StoreV4:
5973 // V8 is only supported for f32/i32. Don't forget, we're not changing the
5974 // store size here. This is already a 256-bit store.
5975 if (ElementVT != MVT::v2f32 && ElementVT != MVT::v2i32)
5976 return SDValue();
5977 Opcode = NVPTXISD::StoreV8;
5978 break;
5979 case NVPTXISD::StoreV8:
5980 // PTX doesn't support the next doubling of operands
5981 return SDValue();
5982 default:
5983 llvm_unreachable("Unhandled store opcode");
5984 }
5985
5986 // Scan the operands and if they're all BUILD_VECTORs, we'll have gathered
5987 // their elements.
5988 SmallVector<SDValue, 4> Operands(N->ops().take_front(N: Front));
5989 for (SDValue BV : N->ops().drop_front(N: Front).drop_back(N: Back)) {
5990 if (BV.getOpcode() != ISD::BUILD_VECTOR)
5991 return SDValue();
5992
5993 // If the operand has multiple uses, this optimization can increase register
5994 // pressure.
5995 if (!BV.hasOneUse())
5996 return SDValue();
5997
5998 // DAGCombiner visits nodes bottom-up. Check the BUILD_VECTOR operands for
5999 // any signs they may be folded by some other pattern or rule.
6000 for (SDValue Op : BV->ops()) {
6001 // Peek through bitcasts
6002 if (Op.getOpcode() == ISD::BITCAST)
6003 Op = Op.getOperand(i: 0);
6004
6005 // This may be folded into a PRMT.
6006 if (Op.getValueType() == MVT::i16 && Op.getOpcode() == ISD::TRUNCATE &&
6007 Op->getOperand(Num: 0).getValueType() == MVT::i32)
6008 return SDValue();
6009
6010 // This may be folded into cvt.bf16x2
6011 if (Op.getOpcode() == ISD::FP_ROUND)
6012 return SDValue();
6013 }
6014 Operands.append(IL: {BV.getOperand(i: 0), BV.getOperand(i: 1)});
6015 }
6016 Operands.append(in_start: N->op_end() - Back, in_end: N->op_end());
6017
6018 // Now we replace the store
6019 return DCI.DAG.getMemIntrinsicNode(Opcode, dl: SDLoc(N), VTList: N->getVTList(), Ops: Operands,
6020 MemVT: ST->getMemoryVT(), MMO: ST->getMemOperand());
6021}
6022
6023static SDValue combineSTORE(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6024 const NVPTXSubtarget &STI) {
6025
6026 if (DCI.isBeforeLegalize() && N->getOpcode() == ISD::STORE) {
6027 // Here is our chance to custom lower a store with a non-simple type.
6028 // Unfortunately, we can't do this in the legalizer because there is no
6029 // way to setOperationAction for an non-simple type.
6030 StoreSDNode *ST = cast<StoreSDNode>(Val: N);
6031 if (!ST->getValue().getValueType().isSimple())
6032 return lowerSTOREVector(Op: SDValue(ST, 0), DAG&: DCI.DAG, STI);
6033 }
6034
6035 return combinePackingMovIntoStore(N, DCI, Front: 1, Back: 2);
6036}
6037
6038static SDValue combineLOAD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6039 const NVPTXSubtarget &STI) {
6040 if (DCI.isBeforeLegalize() && N->getOpcode() == ISD::LOAD) {
6041 // Here is our chance to custom lower a load with a non-simple type.
6042 // Unfortunately, we can't do this in the legalizer because there is no
6043 // way to setOperationAction for an non-simple type.
6044 if (!N->getValueType(ResNo: 0).isSimple())
6045 return lowerLoadVector(N, DAG&: DCI.DAG, STI);
6046 }
6047
6048 return combineUnpackingMovIntoLoad(N, DCI);
6049}
6050
6051/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6052///
6053static SDValue PerformADDCombine(SDNode *N,
6054 TargetLowering::DAGCombinerInfo &DCI,
6055 CodeGenOptLevel OptLevel) {
6056 if (OptLevel == CodeGenOptLevel::None)
6057 return SDValue();
6058
6059 SDValue N0 = N->getOperand(Num: 0);
6060 SDValue N1 = N->getOperand(Num: 1);
6061
6062 // Skip non-integer, non-scalar case
6063 EVT VT = N0.getValueType();
6064 if (VT.isVector() || VT != MVT::i32)
6065 return SDValue();
6066
6067 // First try with the default operand order.
6068 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI))
6069 return Result;
6070
6071 // If that didn't work, try again with the operands commuted.
6072 return PerformADDCombineWithOperands(N, N0: N1, N1: N0, DCI);
6073}
6074
6075/// Check if a v2f32 BUILD_VECTOR provably packs values from non-adjacent
6076/// register pairs (non-coalescable).
6077static bool isNonCoalescableBuildVector(const SDValue &BV) {
6078 if (BV.getOpcode() != ISD::BUILD_VECTOR || BV.getValueType() != MVT::v2f32)
6079 return false;
6080
6081 SDValue Elt0 = BV.getOperand(i: 0);
6082 SDValue Elt1 = BV.getOperand(i: 1);
6083
6084 bool IsExt0 = Elt0.getOpcode() == ISD::EXTRACT_VECTOR_ELT;
6085 bool IsExt1 = Elt1.getOpcode() == ISD::EXTRACT_VECTOR_ELT;
6086
6087 // If neither element is an EXTRACT_VECTOR_ELT they are free-standing
6088 // scalars and the register allocator can still place them side-by-side.
6089 if (!IsExt0 && !IsExt1)
6090 return false;
6091
6092 // If exactly one element is an EXTRACT_VECTOR_ELT, the other is a scalar
6093 // that cannot generally occupy the adjacent register slot.
6094 if (IsExt0 != IsExt1)
6095 return true;
6096
6097 // At this point both sources are extracting from vectors. If they are from
6098 // different vectors, then the BUILD_VECTOR is non-coalescable.
6099 SDValue Src0 = Elt0.getOperand(i: 0);
6100 SDValue Src1 = Elt1.getOperand(i: 0);
6101 if (Src0 != Src1)
6102 return true;
6103
6104 auto *Idx0 = dyn_cast<ConstantSDNode>(Val: Elt0.getOperand(i: 1));
6105 auto *Idx1 = dyn_cast<ConstantSDNode>(Val: Elt1.getOperand(i: 1));
6106 // If both indices are dynamic they will be lowered to
6107 // loads and the vector will be spilled to local memory. The register
6108 // allocator can easily place the results in adjacent registers.
6109 if (!Idx0 && !Idx1)
6110 return false;
6111
6112 // If one index is dynamic and the other is constant, the value from the
6113 // constant load will result in an additional register to pair with the result
6114 // from the dynamic load. We consider this non-coalescable.
6115 if ((Idx0 && !Idx1) || (!Idx0 && Idx1))
6116 return true;
6117
6118 // Both are constant, adjacent pairs are coalescable
6119 return std::abs(i: Idx0->getSExtValue() - Idx1->getSExtValue()) != 1;
6120}
6121
6122/// Return true if FMUL v2f32 node \p N may be scalarized to fold each lane's
6123/// product into a scalar FMA.
6124bool NVPTXTargetLowering::mayFoldFMULIntoFMA(SDNode *N, MachineFunction &MF,
6125 CodeGenOptLevel OptLevel) const {
6126 if (N->getOpcode() != ISD::FMUL || N->getValueType(ResNo: 0) != MVT::v2f32)
6127 return false;
6128 const bool GlobalFMA = allowFMA(MF, OptLevel);
6129 if (!N->getFlags().hasAllowContract() && !GlobalFMA)
6130 return false;
6131
6132 const SDNode *FirstFAdd = nullptr;
6133 unsigned NumScalarFAdd = 0;
6134
6135 // Both lanes must feed unique FADDs
6136 for (SDNode *EE : N->users()) {
6137 if (NumScalarFAdd == 2)
6138 return false;
6139
6140 if (EE->getOpcode() != ISD::EXTRACT_VECTOR_ELT || !EE->hasOneUse() ||
6141 !isa<ConstantSDNode>(Val: EE->getOperand(Num: 1)))
6142 return false;
6143
6144 const SDNode *const FAdd = *EE->users().begin();
6145 if (FAdd->getOpcode() != ISD::FADD ||
6146 (!GlobalFMA && !FAdd->getFlags().hasAllowContract()))
6147 return false;
6148
6149 if (!FirstFAdd)
6150 FirstFAdd = FAdd;
6151 else if (FAdd == FirstFAdd)
6152 return false;
6153
6154 NumScalarFAdd++;
6155 }
6156
6157 return NumScalarFAdd == 2;
6158}
6159
6160/// Scalarize a v2f32 arithmetic node (FADD, FMUL, FSUB, FMA) when at least
6161/// one operand is a BUILD_VECTOR that repacks values from non-adjacent register
6162/// pairs. Without this combine the BUILD_VECTOR forces allocation of a
6163/// temporary 64-bit register, increasing register pressure.
6164///
6165/// Example - before:
6166/// t0: v2f32,v2f32,ch = LoadV2 ...
6167/// t1: f32 = extract_vector_elt t0, 0
6168/// t2: f32 = extract_vector_elt t0:1, 0
6169/// t3: v2f32 = BUILD_VECTOR t1, t2 ;; non-coalescable repack
6170/// t4: v2f32 = fma t_a, t3, t_c
6171///
6172/// After:
6173/// t0: v2f32,v2f32,ch = LoadV2 ...
6174/// t1: f32 = extract_vector_elt t0, 0
6175/// t2: f32 = extract_vector_elt t0:1, 0
6176/// a0: f32 = extract_vector_elt t_a, 0
6177/// a1: f32 = extract_vector_elt t_a, 1
6178/// c0: f32 = extract_vector_elt t_c, 0
6179/// c1: f32 = extract_vector_elt t_c, 1
6180/// r0: f32 = fma a0, t1, c0
6181/// r1: f32 = fma a1, t2, c1
6182/// t4: v2f32 = BUILD_VECTOR r0, r1
6183///
6184/// Also scalarizes an FMUL when all output lanes feed into scalar FADDs
6185/// to enable scalar FMA combining.
6186SDValue NVPTXTargetLowering::performScalarizeV2F32Op(
6187 SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6188 CodeGenOptLevel OptLevel) const {
6189 EVT VT = N->getValueType(ResNo: 0);
6190 if (VT != MVT::v2f32)
6191 return SDValue();
6192
6193 if (none_of(Range: N->ops(), P: isNonCoalescableBuildVector) &&
6194 !mayFoldFMULIntoFMA(N, MF&: DCI.DAG.getMachineFunction(), OptLevel))
6195 return SDValue();
6196
6197 SelectionDAG &DAG = DCI.DAG;
6198 SDLoc DL(N);
6199 EVT EltVT = VT.getVectorElementType();
6200 unsigned Opc = N->getOpcode();
6201
6202 // For each operand, get the scalar element at the given index: if the operand
6203 // is a BUILD_VECTOR, grab the element directly; otherwise, emit an
6204 // EXTRACT_VECTOR_ELT.
6205 auto GetElement = [&](SDValue Op, unsigned Index) -> SDValue {
6206 if (Op.getOpcode() == ISD::BUILD_VECTOR)
6207 return Op.getOperand(i: Index);
6208 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: EltVT, N1: Op,
6209 N2: DAG.getVectorIdxConstant(Val: Index, DL));
6210 };
6211
6212 // Build scalar operand lists for element 0 and element 1.
6213 SmallVector<SDValue, 3> Ops0, Ops1;
6214 for (const SDValue &Op : N->ops()) {
6215 Ops0.push_back(Elt: GetElement(Op, 0));
6216 Ops1.push_back(Elt: GetElement(Op, 1));
6217 }
6218
6219 SDValue Res0 = DAG.getNode(Opcode: Opc, DL, VT: EltVT, Ops: Ops0, Flags: N->getFlags());
6220 SDValue Res1 = DAG.getNode(Opcode: Opc, DL, VT: EltVT, Ops: Ops1, Flags: N->getFlags());
6221
6222 return DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT, N1: Res0, N2: Res1);
6223}
6224
6225/// Target-specific dag combine xforms for ISD::FADD.
6226SDValue
6227NVPTXTargetLowering::performFADDCombine(SDNode *N,
6228 TargetLowering::DAGCombinerInfo &DCI,
6229 CodeGenOptLevel OptLevel) const {
6230 if (SDValue Result = performScalarizeV2F32Op(N, DCI, OptLevel))
6231 return Result;
6232
6233 SDValue N0 = N->getOperand(Num: 0);
6234 SDValue N1 = N->getOperand(Num: 1);
6235
6236 EVT VT = N0.getValueType();
6237 if (VT.isVector() || !(VT == MVT::f32 || VT == MVT::f64))
6238 return SDValue();
6239
6240 // First try with the default operand order.
6241 if (SDValue Result = performFADDCombineWithOperands(N, N0, N1, DCI, OptLevel))
6242 return Result;
6243
6244 // If that didn't work, try again with the operands commuted.
6245 return performFADDCombineWithOperands(N, N0: N1, N1: N0, DCI, OptLevel);
6246}
6247
6248/// Get 3-input version of a 2-input min/max opcode
6249static unsigned getMinMax3Opcode(unsigned MinMax2Opcode) {
6250 switch (MinMax2Opcode) {
6251 case ISD::FMAXNUM:
6252 case ISD::FMAXIMUMNUM:
6253 return NVPTXISD::FMAXNUM3;
6254 case ISD::FMINNUM:
6255 case ISD::FMINIMUMNUM:
6256 return NVPTXISD::FMINNUM3;
6257 case ISD::FMAXIMUM:
6258 return NVPTXISD::FMAXIMUM3;
6259 case ISD::FMINIMUM:
6260 return NVPTXISD::FMINIMUM3;
6261 default:
6262 llvm_unreachable("Invalid 2-input min/max opcode");
6263 }
6264}
6265
6266/// PerformFMinMaxCombine - Combine (fmaxnum (fmaxnum a, b), c) into
6267/// (fmaxnum3 a, b, c). Also covers other llvm min/max intrinsics.
6268static SDValue PerformFMinMaxCombine(SDNode *N,
6269 TargetLowering::DAGCombinerInfo &DCI,
6270 unsigned PTXVersion, unsigned SmVersion) {
6271
6272 // 3-input min/max requires PTX 8.8+ and SM_100+, and only supports f32s
6273 EVT VT = N->getValueType(ResNo: 0);
6274 if (VT != MVT::f32 || PTXVersion < 88 || SmVersion < 100)
6275 return SDValue();
6276
6277 SDValue Op0 = N->getOperand(Num: 0);
6278 SDValue Op1 = N->getOperand(Num: 1);
6279 unsigned MinMaxOp2 = N->getOpcode();
6280 unsigned MinMaxOp3 = getMinMax3Opcode(MinMax2Opcode: MinMaxOp2);
6281
6282 if (Op0.getOpcode() == MinMaxOp2 && Op0.hasOneUse()) {
6283 // (maxnum (maxnum a, b), c) -> (maxnum3 a, b, c)
6284 SDValue A = Op0.getOperand(i: 0);
6285 SDValue B = Op0.getOperand(i: 1);
6286 SDValue C = Op1;
6287 return DCI.DAG.getNode(Opcode: MinMaxOp3, DL: SDLoc(N), VT, N1: A, N2: B, N3: C, Flags: N->getFlags());
6288 } else if (Op1.getOpcode() == MinMaxOp2 && Op1.hasOneUse()) {
6289 // (maxnum a, (maxnum b, c)) -> (maxnum3 a, b, c)
6290 SDValue A = Op0;
6291 SDValue B = Op1.getOperand(i: 0);
6292 SDValue C = Op1.getOperand(i: 1);
6293 return DCI.DAG.getNode(Opcode: MinMaxOp3, DL: SDLoc(N), VT, N1: A, N2: B, N3: C, Flags: N->getFlags());
6294 }
6295 return SDValue();
6296}
6297
6298static SDValue PerformREMCombine(SDNode *N,
6299 TargetLowering::DAGCombinerInfo &DCI,
6300 CodeGenOptLevel OptLevel) {
6301 assert(N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM);
6302
6303 // Don't do anything at less than -O2.
6304 if (OptLevel < CodeGenOptLevel::Default)
6305 return SDValue();
6306
6307 SelectionDAG &DAG = DCI.DAG;
6308 SDLoc DL(N);
6309 EVT VT = N->getValueType(ResNo: 0);
6310 bool IsSigned = N->getOpcode() == ISD::SREM;
6311 unsigned DivOpc = IsSigned ? ISD::SDIV : ISD::UDIV;
6312
6313 const SDValue &Num = N->getOperand(Num: 0);
6314 const SDValue &Den = N->getOperand(Num: 1);
6315
6316 for (const SDNode *U : Num->users()) {
6317 if (U->getOpcode() == DivOpc && U->getOperand(Num: 0) == Num &&
6318 U->getOperand(Num: 1) == Den) {
6319 // Num % Den -> Num - (Num / Den) * Den
6320 return DAG.getNode(Opcode: ISD::SUB, DL, VT, N1: Num,
6321 N2: DAG.getNode(Opcode: ISD::MUL, DL, VT,
6322 N1: DAG.getNode(Opcode: DivOpc, DL, VT, N1: Num, N2: Den),
6323 N2: Den));
6324 }
6325 }
6326 return SDValue();
6327}
6328
6329// sext (mul.iN nsw x, y) => mul.wide.sN x, y
6330// zext (mul.iN nuw x, y) => mul.wide.uN x, y
6331// sext (shl.iN nsw x, const) => mul.wide.sN x, (1 << const)
6332// zext (shl.iN nuw x, const) => mul.wide.uN x, (1 << const)
6333static SDValue combineSZExtToMulWide(SDNode *N,
6334 TargetLowering::DAGCombinerInfo &DCI,
6335 CodeGenOptLevel OptLevel) {
6336 assert(N->getOpcode() == ISD::SIGN_EXTEND ||
6337 N->getOpcode() == ISD::ZERO_EXTEND);
6338
6339 if (OptLevel == CodeGenOptLevel::None)
6340 return SDValue();
6341
6342 SDValue Op = N->getOperand(Num: 0);
6343 if (!Op.hasOneUse())
6344 return SDValue();
6345
6346 EVT ToVT = N->getValueType(ResNo: 0);
6347 EVT FromVT = Op.getValueType();
6348 if (!((ToVT == MVT::i32 && FromVT == MVT::i16) ||
6349 (ToVT == MVT::i64 && FromVT == MVT::i32)))
6350 return SDValue();
6351
6352 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
6353 if ((IsSigned && !Op->getFlags().hasNoSignedWrap()) ||
6354 (!IsSigned && !Op->getFlags().hasNoUnsignedWrap()))
6355 return SDValue();
6356
6357 SDLoc DL(N);
6358 SDValue LHS = Op.getOperand(i: 0);
6359 SDValue RHS = Op.getOperand(i: 1);
6360 unsigned MulWideOpcode =
6361 IsSigned ? NVPTXISD::MUL_WIDE_SIGNED : NVPTXISD::MUL_WIDE_UNSIGNED;
6362 if (Op.getOpcode() == ISD::MUL) {
6363 return DCI.DAG.getNode(Opcode: MulWideOpcode, DL, VT: ToVT, N1: LHS, N2: RHS);
6364 } else if (Op.getOpcode() == ISD::SHL && isa<ConstantSDNode>(Val: RHS)) {
6365 const auto ShiftAmt = Op.getConstantOperandVal(i: 1);
6366 const auto MulVal = APInt(FromVT.getSizeInBits(), 1) << ShiftAmt;
6367
6368 // Note that the sext (shl nsw ...) case doesn't work if 1 << const
6369 // overflows to a negative value! The only valid input values in this
6370 // case are 0 and -1 (all other values yield poison because of the nsw),
6371 // and mul.wide.sN would give us the wrong sign for -1. We could use
6372 // mul.wide.uN, but since this is a weird case anyway, we might as well not
6373 // apply this transformation at all.
6374 if (IsSigned && MulVal.isNegative())
6375 return SDValue();
6376
6377 RHS = DCI.DAG.getConstant(Val: MulVal, DL, VT: FromVT);
6378 return DCI.DAG.getNode(Opcode: MulWideOpcode, DL, VT: ToVT, N1: LHS, N2: RHS);
6379 }
6380
6381 return SDValue();
6382}
6383
6384enum OperandSignedness {
6385 Signed = 0,
6386 Unsigned,
6387 Unknown
6388};
6389
6390/// IsMulWideOperandDemotable - Checks if the provided DAG node is an operand
6391/// that can be demoted to \p OptSize bits without loss of information. The
6392/// signedness of the operand, if determinable, is placed in \p S.
6393static bool IsMulWideOperandDemotable(SDValue Op,
6394 unsigned OptSize,
6395 OperandSignedness &S) {
6396 S = Unknown;
6397
6398 if (Op.getOpcode() == ISD::SIGN_EXTEND ||
6399 Op.getOpcode() == ISD::SIGN_EXTEND_INREG) {
6400 EVT OrigVT = Op.getOperand(i: 0).getValueType();
6401 if (OrigVT.getFixedSizeInBits() <= OptSize) {
6402 S = Signed;
6403 return true;
6404 }
6405 } else if (Op.getOpcode() == ISD::ZERO_EXTEND) {
6406 EVT OrigVT = Op.getOperand(i: 0).getValueType();
6407 if (OrigVT.getFixedSizeInBits() <= OptSize) {
6408 S = Unsigned;
6409 return true;
6410 }
6411 }
6412
6413 return false;
6414}
6415
6416/// AreMulWideOperandsDemotable - Checks if the given LHS and RHS operands can
6417/// be demoted to \p OptSize bits without loss of information. If the operands
6418/// contain a constant, it should appear as the RHS operand. The signedness of
6419/// the operands is placed in \p IsSigned.
6420static bool AreMulWideOperandsDemotable(SDValue LHS, SDValue RHS,
6421 unsigned OptSize,
6422 bool &IsSigned) {
6423 OperandSignedness LHSSign;
6424
6425 // The LHS operand must be a demotable op
6426 if (!IsMulWideOperandDemotable(Op: LHS, OptSize, S&: LHSSign))
6427 return false;
6428
6429 // We should have been able to determine the signedness from the LHS
6430 if (LHSSign == Unknown)
6431 return false;
6432
6433 IsSigned = (LHSSign == Signed);
6434
6435 // The RHS can be a demotable op or a constant
6436 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Val&: RHS)) {
6437 const APInt &Val = CI->getAPIntValue();
6438 if (LHSSign == Unsigned) {
6439 return Val.isIntN(N: OptSize);
6440 } else {
6441 return Val.isSignedIntN(N: OptSize);
6442 }
6443 } else {
6444 OperandSignedness RHSSign;
6445 if (!IsMulWideOperandDemotable(Op: RHS, OptSize, S&: RHSSign))
6446 return false;
6447
6448 return LHSSign == RHSSign;
6449 }
6450}
6451
6452/// TryMULWIDECombine - Attempt to replace a multiply of M bits with a multiply
6453/// of M/2 bits that produces an M-bit result (i.e. mul.wide). This transform
6454/// works on both multiply DAG nodes and SHL DAG nodes with a constant shift
6455/// amount.
6456static SDValue TryMULWIDECombine(SDNode *N,
6457 TargetLowering::DAGCombinerInfo &DCI) {
6458 EVT MulType = N->getValueType(ResNo: 0);
6459 if (MulType != MVT::i32 && MulType != MVT::i64) {
6460 return SDValue();
6461 }
6462
6463 SDLoc DL(N);
6464 unsigned OptSize = MulType.getSizeInBits() >> 1;
6465 SDValue LHS = N->getOperand(Num: 0);
6466 SDValue RHS = N->getOperand(Num: 1);
6467
6468 // Canonicalize the multiply so the constant (if any) is on the right
6469 if (N->getOpcode() == ISD::MUL) {
6470 if (isa<ConstantSDNode>(Val: LHS)) {
6471 std::swap(a&: LHS, b&: RHS);
6472 }
6473 }
6474
6475 // If we have a SHL, determine the actual multiply amount
6476 if (N->getOpcode() == ISD::SHL) {
6477 ConstantSDNode *ShlRHS = dyn_cast<ConstantSDNode>(Val&: RHS);
6478 if (!ShlRHS) {
6479 return SDValue();
6480 }
6481
6482 APInt ShiftAmt = ShlRHS->getAPIntValue();
6483 unsigned BitWidth = MulType.getSizeInBits();
6484 if (ShiftAmt.sge(RHS: 0) && ShiftAmt.slt(RHS: BitWidth)) {
6485 APInt MulVal = APInt(BitWidth, 1) << ShiftAmt;
6486 RHS = DCI.DAG.getConstant(Val: MulVal, DL, VT: MulType);
6487 } else {
6488 return SDValue();
6489 }
6490 }
6491
6492 bool Signed;
6493 // Verify that our operands are demotable
6494 if (!AreMulWideOperandsDemotable(LHS, RHS, OptSize, IsSigned&: Signed)) {
6495 return SDValue();
6496 }
6497
6498 EVT DemotedVT;
6499 if (MulType == MVT::i32) {
6500 DemotedVT = MVT::i16;
6501 } else {
6502 DemotedVT = MVT::i32;
6503 }
6504
6505 // Truncate the operands to the correct size. Note that these are just for
6506 // type consistency and will (likely) be eliminated in later phases.
6507 SDValue TruncLHS =
6508 DCI.DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: DemotedVT, Operand: LHS);
6509 SDValue TruncRHS =
6510 DCI.DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: DemotedVT, Operand: RHS);
6511
6512 unsigned Opc;
6513 if (Signed) {
6514 Opc = NVPTXISD::MUL_WIDE_SIGNED;
6515 } else {
6516 Opc = NVPTXISD::MUL_WIDE_UNSIGNED;
6517 }
6518
6519 return DCI.DAG.getNode(Opcode: Opc, DL, VT: MulType, N1: TruncLHS, N2: TruncRHS);
6520}
6521
6522static bool isConstOne(const SDValue &Operand) {
6523 const auto *Const = dyn_cast<ConstantSDNode>(Val: Operand);
6524 return Const && Const->getZExtValue() == 1;
6525}
6526
6527static SDValue matchMADConstOnePattern(SDValue Add) {
6528 if (Add->getOpcode() != ISD::ADD)
6529 return SDValue();
6530
6531 if (isConstOne(Operand: Add->getOperand(Num: 0)))
6532 return Add->getOperand(Num: 1);
6533
6534 if (isConstOne(Operand: Add->getOperand(Num: 1)))
6535 return Add->getOperand(Num: 0);
6536
6537 return SDValue();
6538}
6539
6540static SDValue combineMADConstOne(SDValue X, SDValue Add, EVT VT, SDLoc DL,
6541 TargetLowering::DAGCombinerInfo &DCI) {
6542
6543 if (SDValue Y = matchMADConstOnePattern(Add)) {
6544 SDValue Mul = DCI.DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: X, N2: Y);
6545 return DCI.DAG.getNode(Opcode: ISD::ADD, DL, VT, N1: Mul, N2: X);
6546 }
6547
6548 return SDValue();
6549}
6550
6551static SDValue combineMulSelectConstOne(SDValue X, SDValue Select, EVT VT,
6552 SDLoc DL,
6553 TargetLowering::DAGCombinerInfo &DCI) {
6554 if (Select->getOpcode() != ISD::SELECT)
6555 return SDValue();
6556
6557 SDValue Cond = Select->getOperand(Num: 0);
6558
6559 unsigned ConstOpNo;
6560 if (isConstOne(Operand: Select->getOperand(Num: 1)))
6561 ConstOpNo = 1;
6562 else if (isConstOne(Operand: Select->getOperand(Num: 2)))
6563 ConstOpNo = 2;
6564 else
6565 return SDValue();
6566
6567 SDValue Y = Select->getOperand(Num: (ConstOpNo == 1) ? 2 : 1);
6568
6569 // Do not combine if the resulting sequence is not obviously profitable.
6570 if (!matchMADConstOnePattern(Add: Y))
6571 return SDValue();
6572
6573 SDValue NewMul = DCI.DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: X, N2: Y);
6574
6575 return DCI.DAG.getNode(Opcode: ISD::SELECT, DL, VT, N1: Cond,
6576 N2: (ConstOpNo == 1) ? X : NewMul,
6577 N3: (ConstOpNo == 1) ? NewMul : X);
6578}
6579
6580static SDValue
6581PerformMULCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6582 TargetLowering::DAGCombinerInfo &DCI) {
6583
6584 EVT VT = N0.getValueType();
6585 if (VT.isVector())
6586 return SDValue();
6587
6588 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6589 return SDValue();
6590
6591 SDLoc DL(N);
6592
6593 // (mul x, (add y, 1)) -> (add (mul x, y), x)
6594 if (SDValue Res = combineMADConstOne(X: N0, Add: N1, VT, DL, DCI))
6595 return Res;
6596 if (SDValue Res = combineMADConstOne(X: N1, Add: N0, VT, DL, DCI))
6597 return Res;
6598
6599 // (mul x, (select y, 1)) -> (select (mul x, y), x)
6600 if (SDValue Res = combineMulSelectConstOne(X: N0, Select: N1, VT, DL, DCI))
6601 return Res;
6602 if (SDValue Res = combineMulSelectConstOne(X: N1, Select: N0, VT, DL, DCI))
6603 return Res;
6604
6605 return SDValue();
6606}
6607
6608/// PerformMULCombine - Runs PTX-specific DAG combine patterns on MUL nodes.
6609static SDValue PerformMULCombine(SDNode *N,
6610 TargetLowering::DAGCombinerInfo &DCI,
6611 CodeGenOptLevel OptLevel) {
6612 if (OptLevel == CodeGenOptLevel::None)
6613 return SDValue();
6614
6615 if (SDValue Ret = TryMULWIDECombine(N, DCI))
6616 return Ret;
6617
6618 SDValue N0 = N->getOperand(Num: 0);
6619 SDValue N1 = N->getOperand(Num: 1);
6620 return PerformMULCombineWithOperands(N, N0, N1, DCI);
6621}
6622
6623/// PerformSHLCombine - Runs PTX-specific DAG combine patterns on SHL nodes.
6624static SDValue PerformSHLCombine(SDNode *N,
6625 TargetLowering::DAGCombinerInfo &DCI,
6626 CodeGenOptLevel OptLevel) {
6627 if (OptLevel > CodeGenOptLevel::None) {
6628 // Try mul.wide combining at OptLevel > 0
6629 if (SDValue Ret = TryMULWIDECombine(N, DCI))
6630 return Ret;
6631 }
6632
6633 return SDValue();
6634}
6635
6636static SDValue PerformSETCCCombine(SDNode *N,
6637 TargetLowering::DAGCombinerInfo &DCI,
6638 unsigned int SmVersion) {
6639 EVT CCType = N->getValueType(ResNo: 0);
6640 SDValue A = N->getOperand(Num: 0);
6641 SDValue B = N->getOperand(Num: 1);
6642
6643 EVT AType = A.getValueType();
6644 if (!(CCType == MVT::v2i1 && (AType == MVT::v2f16 || AType == MVT::v2bf16)))
6645 return SDValue();
6646
6647 if (A.getValueType() == MVT::v2bf16 && SmVersion < 90)
6648 return SDValue();
6649
6650 SDLoc DL(N);
6651 // setp.f16x2 returns two scalar predicates, which we need to
6652 // convert back to v2i1. The returned result will be scalarized by
6653 // the legalizer, but the comparison will remain a single vector
6654 // instruction.
6655 SDValue CCNode = DCI.DAG.getNode(
6656 Opcode: A.getValueType() == MVT::v2f16 ? NVPTXISD::SETP_F16X2
6657 : NVPTXISD::SETP_BF16X2,
6658 DL, VTList: DCI.DAG.getVTList(VT1: MVT::i1, VT2: MVT::i1), Ops: {A, B, N->getOperand(Num: 2)});
6659 return DCI.DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT: CCType, N1: CCNode.getValue(R: 0),
6660 N2: CCNode.getValue(R: 1));
6661}
6662
6663static SDValue PerformEXTRACTCombine(SDNode *N,
6664 TargetLowering::DAGCombinerInfo &DCI) {
6665 SDValue Vector = peekThroughFreeze(V: N->getOperand(Num: 0));
6666 SDLoc DL(N);
6667 EVT VectorVT = Vector.getValueType();
6668 if (Vector->getOpcode() == ISD::LOAD && VectorVT.isSimple() &&
6669 IsPTXVectorType(VT: VectorVT.getSimpleVT()))
6670 return SDValue(); // Native vector loads already combine nicely w/
6671 // extract_vector_elt.
6672 // Don't mess with singletons or packed types (v2*32, v2*16, v4i8 and v8i8),
6673 // we already handle them OK.
6674 if (VectorVT.getVectorNumElements() == 1 ||
6675 NVPTX::isPackedVectorTy(VT: VectorVT) || VectorVT == MVT::v8i8)
6676 return SDValue();
6677
6678 // Don't mess with undef values as sra may be simplified to 0, not undef.
6679 if (Vector->isUndef() || ISD::allOperandsUndef(N: Vector.getNode()))
6680 return SDValue();
6681
6682 uint64_t VectorBits = VectorVT.getSizeInBits();
6683 // We only handle the types we can extract in-register.
6684 if (!(VectorBits == 16 || VectorBits == 32 || VectorBits == 64))
6685 return SDValue();
6686
6687 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
6688 // Index == 0 is handled by generic DAG combiner.
6689 if (!Index || Index->getZExtValue() == 0)
6690 return SDValue();
6691
6692 MVT IVT = MVT::getIntegerVT(BitWidth: VectorBits);
6693 EVT EltVT = VectorVT.getVectorElementType();
6694 EVT EltIVT = EltVT.changeTypeToInteger();
6695 uint64_t EltBits = EltVT.getScalarSizeInBits();
6696
6697 SDValue Result = DCI.DAG.getNode(
6698 Opcode: ISD::TRUNCATE, DL, VT: EltIVT,
6699 Operand: DCI.DAG.getNode(
6700 Opcode: ISD::SRA, DL, VT: IVT, N1: DCI.DAG.getNode(Opcode: ISD::BITCAST, DL, VT: IVT, Operand: Vector),
6701 N2: DCI.DAG.getConstant(Val: Index->getZExtValue() * EltBits, DL, VT: IVT)));
6702
6703 // If element has non-integer type, bitcast it back to the expected type.
6704 if (EltVT != EltIVT)
6705 Result = DCI.DAG.getNode(Opcode: ISD::BITCAST, DL, VT: EltVT, Operand: Result);
6706 // Past legalizer, we may need to extent i8 -> i16 to match the register type.
6707 if (EltVT != N->getValueType(ResNo: 0))
6708 Result = DCI.DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: N->getValueType(ResNo: 0), Operand: Result);
6709
6710 return Result;
6711}
6712
6713/// Transform patterns like:
6714/// (select (ugt shift_amt, BitWidth-1), 0, (srl/shl x, shift_amt))
6715/// (select (ult shift_amt, BitWidth), (srl/shl x, shift_amt), 0)
6716/// Into:
6717/// (NVPTXISD::SRL_CLAMP x, shift_amt) or (NVPTXISD::SHL_CLAMP x, shift_amt)
6718///
6719/// These patterns arise from code like `s >= 32 ? 0 : x >> s`. In LLVM,
6720/// over-shifting a value results in poison, but PTX shr/shl instructions clamp
6721/// the shift amount to BitWidth, making the guard redundant.
6722///
6723/// Note: We only handle SRL and SHL, not SRA, because arithmetic right shifts
6724/// can produce 0 or -1 when shift >= BitWidth.
6725/// Note: We don't handle uge or ule. These don't appear because of
6726/// canonicalization.
6727static SDValue PerformSELECTShiftCombine(SDNode *N,
6728 TargetLowering::DAGCombinerInfo &DCI) {
6729 if (!DCI.isAfterLegalizeDAG())
6730 return SDValue();
6731
6732 using namespace SDPatternMatch;
6733 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
6734 SDValue ShiftAmt, ShiftOp;
6735
6736 // Match logical shifts where the shift amount in the guard matches the shift
6737 // amount in the operation.
6738 auto LogicalShift =
6739 m_AllOf(preds: m_Value(N&: ShiftOp),
6740 preds: m_AnyOf(preds: m_Srl(L: m_Value(), R: m_TruncOrSelf(Op: m_Deferred(V&: ShiftAmt))),
6741 preds: m_Shl(L: m_Value(), R: m_TruncOrSelf(Op: m_Deferred(V&: ShiftAmt)))));
6742
6743 // shift_amt > BitWidth-1 ? 0 : shift_op
6744 bool MatchedUGT =
6745 sd_match(N, P: m_Select(Cond: m_SetCC(LHS: m_Value(N&: ShiftAmt),
6746 RHS: m_SpecificInt(V: APInt(BitWidth, BitWidth - 1)),
6747 CC: m_SpecificCondCode(CC: ISD::SETUGT)),
6748 T: m_Zero(), F: LogicalShift));
6749 // shift_amt < BitWidth ? shift_op : 0
6750 bool MatchedULT =
6751 !MatchedUGT &&
6752 sd_match(N, P: m_Select(Cond: m_SetCC(LHS: m_Value(N&: ShiftAmt),
6753 RHS: m_SpecificInt(V: APInt(BitWidth, BitWidth)),
6754 CC: m_SpecificCondCode(CC: ISD::SETULT)),
6755 T: LogicalShift, F: m_Zero()));
6756
6757 if (!MatchedUGT && !MatchedULT)
6758 return SDValue();
6759
6760 // In LLVM IR, the shift amount and the value-to-be-shifted are the same
6761 // type, whereas in PTX the shift amount is always i32. Therefore when
6762 // shifting types larger than i32, we can only do this transformation if we
6763 // know that the upper bits of the shift amount are known zero.
6764 SDValue ClampAmt = ShiftOp.getOperand(i: 1);
6765 unsigned ClampAmtBits = ClampAmt.getValueSizeInBits();
6766 if (ShiftAmt.getValueSizeInBits() > ClampAmtBits &&
6767 DCI.DAG.computeKnownBits(Op: ShiftAmt).countMaxActiveBits() > ClampAmtBits)
6768 return SDValue();
6769
6770 // Return a clamp shift operation, which has the same semantics as PTX shift.
6771 unsigned ClampOpc = ShiftOp.getOpcode() == ISD::SRL ? NVPTXISD::SRL_CLAMP
6772 : NVPTXISD::SHL_CLAMP;
6773 return DCI.DAG.getNode(Opcode: ClampOpc, DL: SDLoc(N), VT: ShiftOp.getValueType(),
6774 N1: ShiftOp.getOperand(i: 0), N2: ClampAmt);
6775}
6776
6777static SDValue PerformVSELECTCombine(SDNode *N,
6778 TargetLowering::DAGCombinerInfo &DCI) {
6779 SDValue VA = N->getOperand(Num: 1);
6780 EVT VectorVT = VA.getValueType();
6781 if (VectorVT != MVT::v4i8)
6782 return SDValue();
6783
6784 // We need to split vselect into individual per-element operations Because we
6785 // use BFE/BFI instruction for byte extraction/insertion, we do end up with
6786 // 32-bit values, so we may as well do comparison as i32 to avoid conversions
6787 // to/from i16 normally used for i8 values.
6788 SmallVector<SDValue, 4> E;
6789 SDLoc DL(N);
6790 SDValue VCond = N->getOperand(Num: 0);
6791 SDValue VB = N->getOperand(Num: 2);
6792 for (int I = 0; I < 4; ++I) {
6793 SDValue C = DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i1, N1: VCond,
6794 N2: DCI.DAG.getConstant(Val: I, DL, VT: MVT::i32));
6795 SDValue EA = DCI.DAG.getAnyExtOrTrunc(
6796 Op: DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i8, N1: VA,
6797 N2: DCI.DAG.getConstant(Val: I, DL, VT: MVT::i32)),
6798 DL, VT: MVT::i32);
6799 SDValue EB = DCI.DAG.getAnyExtOrTrunc(
6800 Op: DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i8, N1: VB,
6801 N2: DCI.DAG.getConstant(Val: I, DL, VT: MVT::i32)),
6802 DL, VT: MVT::i32);
6803 E.push_back(Elt: DCI.DAG.getAnyExtOrTrunc(
6804 Op: DCI.DAG.getNode(Opcode: ISD::SELECT, DL, VT: MVT::i32, N1: C, N2: EA, N3: EB), DL, VT: MVT::i8));
6805 }
6806 return DCI.DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT: MVT::v4i8, Ops: E);
6807}
6808
6809static SDValue
6810PerformBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
6811 auto VT = N->getValueType(ResNo: 0);
6812 if (!DCI.isAfterLegalizeDAG() ||
6813 // only process v2*16 types
6814 !(NVPTX::isPackedVectorTy(VT) && VT.is32BitVector() &&
6815 VT.getVectorNumElements() == 2))
6816 return SDValue();
6817
6818 auto Op0 = N->getOperand(Num: 0);
6819 auto Op1 = N->getOperand(Num: 1);
6820
6821 // Start out by assuming we want to take the lower 2 bytes of each i32
6822 // operand.
6823 uint64_t Op0Bytes = 0x10;
6824 uint64_t Op1Bytes = 0x54;
6825
6826 std::pair<SDValue *, uint64_t *> OpData[2] = {{&Op0, &Op0Bytes},
6827 {&Op1, &Op1Bytes}};
6828
6829 // Check that each operand is an i16, truncated from an i32 operand. We'll
6830 // select individual bytes from those original operands. Optionally, fold in a
6831 // shift right of that original operand.
6832 for (auto &[Op, OpBytes] : OpData) {
6833 // Eat up any bitcast
6834 if (Op->getOpcode() == ISD::BITCAST)
6835 *Op = Op->getOperand(i: 0);
6836
6837 if (!(Op->getValueType() == MVT::i16 && Op->getOpcode() == ISD::TRUNCATE &&
6838 Op->getOperand(i: 0).getValueType() == MVT::i32))
6839 return SDValue();
6840
6841 // If the truncate has multiple uses, this optimization can increase
6842 // register pressure
6843 if (!Op->hasOneUse())
6844 return SDValue();
6845
6846 *Op = Op->getOperand(i: 0);
6847
6848 // Optionally, fold in a shift-right of the original operand and let permute
6849 // pick the two higher bytes of the original value directly.
6850 if (Op->getOpcode() == ISD::SRL && isa<ConstantSDNode>(Val: Op->getOperand(i: 1))) {
6851 if (cast<ConstantSDNode>(Val: Op->getOperand(i: 1))->getZExtValue() == 16) {
6852 // Shift the PRMT byte selector to pick upper bytes from each respective
6853 // value, instead of the lower ones: 0x10 -> 0x32, 0x54 -> 0x76
6854 assert((*OpBytes == 0x10 || *OpBytes == 0x54) &&
6855 "PRMT selector values out of range");
6856 *OpBytes += 0x22;
6857 *Op = Op->getOperand(i: 0);
6858 }
6859 }
6860 }
6861
6862 SDLoc DL(N);
6863 auto &DAG = DCI.DAG;
6864
6865 auto PRMT =
6866 getPRMT(A: DAG.getBitcast(VT: MVT::i32, V: Op0), B: DAG.getBitcast(VT: MVT::i32, V: Op1),
6867 Selector: (Op1Bytes << 8) | Op0Bytes, DL, DAG);
6868 return DAG.getBitcast(VT, V: PRMT);
6869}
6870
6871static SDValue combineADDRSPACECAST(SDNode *N,
6872 TargetLowering::DAGCombinerInfo &DCI) {
6873 auto *ASCN1 = cast<AddrSpaceCastSDNode>(Val: N);
6874
6875 if (auto *ASCN2 = dyn_cast<AddrSpaceCastSDNode>(Val: ASCN1->getOperand(Num: 0))) {
6876 assert(ASCN2->getDestAddressSpace() == ASCN1->getSrcAddressSpace());
6877
6878 // Fold asc[B -> A](asc[A -> B](x)) -> x
6879 if (ASCN1->getDestAddressSpace() == ASCN2->getSrcAddressSpace())
6880 return ASCN2->getOperand(Num: 0);
6881 }
6882
6883 return SDValue();
6884}
6885
6886// Given a constant selector value and a prmt mode, return the selector value
6887// normalized to the generic prmt mode. See the PTX ISA documentation for more
6888// details:
6889// https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#data-movement-and-conversion-instructions-prmt
6890static APInt getPRMTSelector(const APInt &Selector, unsigned Mode) {
6891 assert(Selector.getBitWidth() == 32 && "PRMT must have i32 operands");
6892
6893 if (Mode == NVPTX::PTXPrmtMode::NONE)
6894 return Selector;
6895
6896 const unsigned V = Selector.trunc(width: 2).getZExtValue();
6897
6898 const auto GetSelector = [](unsigned S0, unsigned S1, unsigned S2,
6899 unsigned S3) {
6900 return APInt(32, S0 | (S1 << 4) | (S2 << 8) | (S3 << 12));
6901 };
6902
6903 switch (Mode) {
6904 case NVPTX::PTXPrmtMode::F4E:
6905 return GetSelector(V, V + 1, V + 2, V + 3);
6906 case NVPTX::PTXPrmtMode::B4E:
6907 return GetSelector(V, (V - 1) & 7, (V - 2) & 7, (V - 3) & 7);
6908 case NVPTX::PTXPrmtMode::RC8:
6909 return GetSelector(V, V, V, V);
6910 case NVPTX::PTXPrmtMode::ECL:
6911 return GetSelector(V, std::max(a: V, b: 1U), std::max(a: V, b: 2U), 3U);
6912 case NVPTX::PTXPrmtMode::ECR:
6913 return GetSelector(0, std::min(a: V, b: 1U), std::min(a: V, b: 2U), V);
6914 case NVPTX::PTXPrmtMode::RC16: {
6915 unsigned V1 = (V & 1) << 1;
6916 return GetSelector(V1, V1 + 1, V1, V1 + 1);
6917 }
6918 default:
6919 llvm_unreachable("Invalid PRMT mode");
6920 }
6921}
6922
6923static APInt computePRMT(APInt A, APInt B, APInt Selector, unsigned Mode) {
6924 assert(A.getBitWidth() == 32 && B.getBitWidth() == 32 &&
6925 Selector.getBitWidth() == 32 && "PRMT must have i32 operands");
6926 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
6927 APInt BitField = B.concat(NewLSB: A);
6928 APInt SelectorVal = getPRMTSelector(Selector, Mode);
6929 APInt Result(32, 0);
6930 for (unsigned I : llvm::seq(Size: 4U)) {
6931 APInt Sel = SelectorVal.extractBits(numBits: 4, bitPosition: I * 4);
6932 unsigned Idx = Sel.getLoBits(numBits: 3).getZExtValue();
6933 unsigned Sign = Sel.getHiBits(numBits: 1).getZExtValue();
6934 APInt Byte = BitField.extractBits(numBits: 8, bitPosition: Idx * 8);
6935 if (Sign)
6936 Byte = Byte.ashr(ShiftAmt: 8);
6937 Result.insertBits(SubBits: Byte, bitPosition: I * 8);
6938 }
6939 return Result;
6940}
6941
6942static SDValue combinePRMT(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6943 CodeGenOptLevel OptLevel) {
6944 if (OptLevel == CodeGenOptLevel::None)
6945 return SDValue();
6946
6947 // Constant fold PRMT
6948 if (isa<ConstantSDNode>(Val: N->getOperand(Num: 0)) &&
6949 isa<ConstantSDNode>(Val: N->getOperand(Num: 1)) &&
6950 isa<ConstantSDNode>(Val: N->getOperand(Num: 2)))
6951 return DCI.DAG.getConstant(Val: computePRMT(A: N->getConstantOperandAPInt(Num: 0),
6952 B: N->getConstantOperandAPInt(Num: 1),
6953 Selector: N->getConstantOperandAPInt(Num: 2),
6954 Mode: N->getConstantOperandVal(Num: 3)),
6955 DL: SDLoc(N), VT: N->getValueType(ResNo: 0));
6956 return SDValue();
6957}
6958
6959// During call lowering we wrap the return values in a ProxyReg node which
6960// depend on the chain value produced by the completed call. This ensures that
6961// the full call is emitted in cases where libcalls are used to legalize
6962// operations. To improve the functioning of other DAG combines we pull all
6963// operations we can through one of these nodes, ensuring that the ProxyReg
6964// directly wraps a load. That is:
6965//
6966// (ProxyReg (zext (load retval0))) => (zext (ProxyReg (load retval0)))
6967//
6968static SDValue sinkProxyReg(SDValue R, SDValue Chain,
6969 TargetLowering::DAGCombinerInfo &DCI) {
6970 switch (R.getOpcode()) {
6971 case ISD::TRUNCATE:
6972 case ISD::ANY_EXTEND:
6973 case ISD::SIGN_EXTEND:
6974 case ISD::ZERO_EXTEND:
6975 case ISD::BITCAST: {
6976 if (SDValue V = sinkProxyReg(R: R.getOperand(i: 0), Chain, DCI))
6977 return DCI.DAG.getNode(Opcode: R.getOpcode(), DL: SDLoc(R), VT: R.getValueType(), Operand: V);
6978 return SDValue();
6979 }
6980 case ISD::SHL:
6981 case ISD::SRL:
6982 case ISD::SRA:
6983 case ISD::OR: {
6984 if (SDValue A = sinkProxyReg(R: R.getOperand(i: 0), Chain, DCI))
6985 if (SDValue B = sinkProxyReg(R: R.getOperand(i: 1), Chain, DCI))
6986 return DCI.DAG.getNode(Opcode: R.getOpcode(), DL: SDLoc(R), VT: R.getValueType(), N1: A, N2: B);
6987 return SDValue();
6988 }
6989 case ISD::Constant:
6990 return R;
6991 case ISD::LOAD:
6992 case NVPTXISD::LoadV2:
6993 case NVPTXISD::LoadV4: {
6994 return DCI.DAG.getNode(Opcode: NVPTXISD::ProxyReg, DL: SDLoc(R), VT: R.getValueType(),
6995 Ops: {Chain, R});
6996 }
6997 case ISD::BUILD_VECTOR: {
6998 if (DCI.isBeforeLegalize())
6999 return SDValue();
7000
7001 SmallVector<SDValue, 16> Ops;
7002 for (auto &Op : R->ops()) {
7003 SDValue V = sinkProxyReg(R: Op, Chain, DCI);
7004 if (!V)
7005 return SDValue();
7006 Ops.push_back(Elt: V);
7007 }
7008 return DCI.DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL: SDLoc(R), VT: R.getValueType(), Ops);
7009 }
7010 case ISD::EXTRACT_VECTOR_ELT: {
7011 if (DCI.isBeforeLegalize())
7012 return SDValue();
7013
7014 if (SDValue V = sinkProxyReg(R: R.getOperand(i: 0), Chain, DCI))
7015 return DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: SDLoc(R),
7016 VT: R.getValueType(), N1: V, N2: R.getOperand(i: 1));
7017 return SDValue();
7018 }
7019 default:
7020 return SDValue();
7021 }
7022}
7023
7024static unsigned getF16SubOpc(Intrinsic::ID AddIntrinsicID) {
7025 switch (AddIntrinsicID) {
7026 default:
7027 break;
7028 case Intrinsic::nvvm_add_rn_sat_f16:
7029 case Intrinsic::nvvm_add_rn_sat_v2f16:
7030 return NVPTXISD::SUB_RN_SAT;
7031 case Intrinsic::nvvm_add_rn_ftz_sat_f16:
7032 case Intrinsic::nvvm_add_rn_ftz_sat_v2f16:
7033 return NVPTXISD::SUB_RN_FTZ_SAT;
7034 }
7035 llvm_unreachable("Invalid F16 add intrinsic");
7036}
7037
7038static SDValue combineF16AddWithNeg(SDNode *N, SelectionDAG &DAG,
7039 Intrinsic::ID AddIntrinsicID) {
7040 SDValue Op1 = N->getOperand(Num: 1);
7041 SDValue Op2 = N->getOperand(Num: 2);
7042
7043 SDValue SubOp1, SubOp2;
7044
7045 if (Op1.getOpcode() == ISD::FNEG) {
7046 SubOp1 = Op2;
7047 SubOp2 = Op1.getOperand(i: 0);
7048 } else if (Op2.getOpcode() == ISD::FNEG) {
7049 SubOp1 = Op1;
7050 SubOp2 = Op2.getOperand(i: 0);
7051 } else {
7052 return SDValue();
7053 }
7054
7055 SDLoc DL(N);
7056 return DAG.getNode(Opcode: getF16SubOpc(AddIntrinsicID), DL, VT: N->getValueType(ResNo: 0),
7057 N1: SubOp1, N2: SubOp2);
7058}
7059
7060static SDValue combineIntrinsicWOChain(SDNode *N,
7061 TargetLowering::DAGCombinerInfo &DCI,
7062 const NVPTXSubtarget &STI) {
7063 unsigned IID = N->getConstantOperandVal(Num: 0);
7064
7065 switch (IID) {
7066 default:
7067 break;
7068 case Intrinsic::nvvm_add_rn_sat_f16:
7069 case Intrinsic::nvvm_add_rn_ftz_sat_f16:
7070 case Intrinsic::nvvm_add_rn_sat_v2f16:
7071 case Intrinsic::nvvm_add_rn_ftz_sat_v2f16:
7072 return combineF16AddWithNeg(N, DAG&: DCI.DAG, AddIntrinsicID: IID);
7073 }
7074 return SDValue();
7075}
7076
7077static SDValue combineProxyReg(SDNode *N,
7078 TargetLowering::DAGCombinerInfo &DCI) {
7079
7080 SDValue Chain = N->getOperand(Num: 0);
7081 SDValue Reg = N->getOperand(Num: 1);
7082
7083 // If the ProxyReg is not wrapping a load, try to pull the operations through
7084 // the ProxyReg.
7085 if (Reg.getOpcode() != ISD::LOAD) {
7086 if (SDValue V = sinkProxyReg(R: Reg, Chain, DCI))
7087 return V;
7088 }
7089
7090 return SDValue();
7091}
7092
7093SDValue NVPTXTargetLowering::PerformDAGCombine(SDNode *N,
7094 DAGCombinerInfo &DCI) const {
7095 CodeGenOptLevel OptLevel = getTargetMachine().getOptLevel();
7096 switch (N->getOpcode()) {
7097 default:
7098 break;
7099 case ISD::ADD:
7100 return PerformADDCombine(N, DCI, OptLevel);
7101 case ISD::ADDRSPACECAST:
7102 return combineADDRSPACECAST(N, DCI);
7103 case ISD::SIGN_EXTEND:
7104 case ISD::ZERO_EXTEND:
7105 return combineSZExtToMulWide(N, DCI, OptLevel);
7106 case ISD::BUILD_VECTOR:
7107 return PerformBUILD_VECTORCombine(N, DCI);
7108 case ISD::EXTRACT_VECTOR_ELT:
7109 return PerformEXTRACTCombine(N, DCI);
7110 case ISD::FADD:
7111 return performFADDCombine(N, DCI, OptLevel);
7112 case ISD::FMA:
7113 case ISD::FMUL:
7114 case ISD::FSUB:
7115 return performScalarizeV2F32Op(N, DCI, OptLevel);
7116 case ISD::FMAXNUM:
7117 case ISD::FMINNUM:
7118 case ISD::FMAXIMUM:
7119 case ISD::FMINIMUM:
7120 case ISD::FMAXIMUMNUM:
7121 case ISD::FMINIMUMNUM:
7122 return PerformFMinMaxCombine(N, DCI, PTXVersion: STI.getPTXVersion(),
7123 SmVersion: STI.getSmVersion());
7124 case ISD::LOAD:
7125 case NVPTXISD::LoadV2:
7126 case NVPTXISD::LoadV4:
7127 return combineLOAD(N, DCI, STI);
7128 case ISD::MUL:
7129 return PerformMULCombine(N, DCI, OptLevel);
7130 case NVPTXISD::PRMT:
7131 return combinePRMT(N, DCI, OptLevel);
7132 case NVPTXISD::ProxyReg:
7133 return combineProxyReg(N, DCI);
7134 case ISD::SETCC:
7135 return PerformSETCCCombine(N, DCI, SmVersion: STI.getSmVersion());
7136 case ISD::SHL:
7137 return PerformSHLCombine(N, DCI, OptLevel);
7138 case ISD::SREM:
7139 case ISD::UREM:
7140 return PerformREMCombine(N, DCI, OptLevel);
7141 case ISD::STORE:
7142 case NVPTXISD::StoreV2:
7143 case NVPTXISD::StoreV4:
7144 return combineSTORE(N, DCI, STI);
7145 case ISD::SELECT:
7146 return PerformSELECTShiftCombine(N, DCI);
7147 case ISD::VSELECT:
7148 return PerformVSELECTCombine(N, DCI);
7149 case ISD::INTRINSIC_WO_CHAIN:
7150 return combineIntrinsicWOChain(N, DCI, STI);
7151 }
7152 return SDValue();
7153}
7154
7155static void ReplaceBITCAST(SDNode *Node, SelectionDAG &DAG,
7156 SmallVectorImpl<SDValue> &Results) {
7157 // Handle bitcasting to v2i8 without hitting the default promotion
7158 // strategy which goes through stack memory.
7159 SDValue Op(Node, 0);
7160 EVT ToVT = Op->getValueType(ResNo: 0);
7161 if (ToVT != MVT::v2i8) {
7162 return;
7163 }
7164
7165 // Bitcast to i16 and unpack elements into a vector
7166 SDLoc DL(Node);
7167 SDValue AsInt = DAG.getBitcast(VT: MVT::i16, V: Op->getOperand(Num: 0));
7168 SDValue Vec0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::i8, Operand: AsInt);
7169 SDValue Const8 = DAG.getConstant(Val: 8, DL, VT: MVT::i16);
7170 SDValue Vec1 =
7171 DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::i8,
7172 Operand: DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i16, Ops: {AsInt, Const8}));
7173 Results.push_back(
7174 Elt: DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL, VT: MVT::v2i8, Ops: {Vec0, Vec1}));
7175}
7176
7177static void ReplaceINTRINSIC_W_CHAIN(SDNode *N, SelectionDAG &DAG,
7178 SmallVectorImpl<SDValue> &Results) {
7179 SDValue Chain = N->getOperand(Num: 0);
7180 SDValue Intrin = N->getOperand(Num: 1);
7181 SDLoc DL(N);
7182
7183 // Get the intrinsic ID
7184 unsigned IntrinNo = Intrin.getNode()->getAsZExtVal();
7185 switch (IntrinNo) {
7186 default:
7187 return;
7188 case Intrinsic::nvvm_ldu_global_i:
7189 case Intrinsic::nvvm_ldu_global_f:
7190 case Intrinsic::nvvm_ldu_global_p: {
7191 EVT ResVT = N->getValueType(ResNo: 0);
7192
7193 if (ResVT.isVector()) {
7194 // Vector LDG/LDU
7195
7196 unsigned NumElts = ResVT.getVectorNumElements();
7197 EVT EltVT = ResVT.getVectorElementType();
7198
7199 // Since LDU/LDG are target nodes, we cannot rely on DAG type
7200 // legalization.
7201 // Therefore, we must ensure the type is legal. For i1 and i8, we set the
7202 // loaded type to i16 and propagate the "real" type as the memory type.
7203 bool NeedTrunc = false;
7204 if (EltVT.getSizeInBits() < 16) {
7205 EltVT = MVT::i16;
7206 NeedTrunc = true;
7207 }
7208
7209 unsigned Opcode = 0;
7210 SDVTList LdResVTs;
7211
7212 switch (NumElts) {
7213 default:
7214 return;
7215 case 2:
7216 Opcode = NVPTXISD::LDUV2;
7217 LdResVTs = DAG.getVTList(VT1: EltVT, VT2: EltVT, VT3: MVT::Other);
7218 break;
7219 case 4: {
7220 Opcode = NVPTXISD::LDUV4;
7221 EVT ListVTs[] = { EltVT, EltVT, EltVT, EltVT, MVT::Other };
7222 LdResVTs = DAG.getVTList(VTs: ListVTs);
7223 break;
7224 }
7225 }
7226
7227 SmallVector<SDValue, 8> OtherOps;
7228
7229 // Copy regular operands
7230
7231 OtherOps.push_back(Elt: Chain); // Chain
7232 // Skip operand 1 (intrinsic ID)
7233 // Others
7234 OtherOps.append(in_start: N->op_begin() + 2, in_end: N->op_end());
7235
7236 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(Val: N);
7237
7238 SDValue NewLD = DAG.getMemIntrinsicNode(Opcode, dl: DL, VTList: LdResVTs, Ops: OtherOps,
7239 MemVT: MemSD->getMemoryVT(),
7240 MMO: MemSD->getMemOperand());
7241
7242 SmallVector<SDValue, 4> ScalarRes;
7243
7244 for (unsigned i = 0; i < NumElts; ++i) {
7245 SDValue Res = NewLD.getValue(R: i);
7246 if (NeedTrunc)
7247 Res =
7248 DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: ResVT.getVectorElementType(), Operand: Res);
7249 ScalarRes.push_back(Elt: Res);
7250 }
7251
7252 SDValue LoadChain = NewLD.getValue(R: NumElts);
7253
7254 SDValue BuildVec =
7255 DAG.getBuildVector(VT: ResVT, DL, Ops: ScalarRes);
7256
7257 Results.push_back(Elt: BuildVec);
7258 Results.push_back(Elt: LoadChain);
7259 } else {
7260 // i8 LDG/LDU
7261 assert(ResVT.isSimple() && ResVT.getSimpleVT().SimpleTy == MVT::i8 &&
7262 "Custom handling of non-i8 ldu/ldg?");
7263
7264 // Just copy all operands as-is
7265 SmallVector<SDValue, 4> Ops(N->ops());
7266
7267 // Force output to i16
7268 SDVTList LdResVTs = DAG.getVTList(VT1: MVT::i16, VT2: MVT::Other);
7269
7270 MemIntrinsicSDNode *MemSD = cast<MemIntrinsicSDNode>(Val: N);
7271
7272 // We make sure the memory type is i8, which will be used during isel
7273 // to select the proper instruction.
7274 SDValue NewLD =
7275 DAG.getMemIntrinsicNode(Opcode: ISD::INTRINSIC_W_CHAIN, dl: DL, VTList: LdResVTs, Ops,
7276 MemVT: MVT::i8, MMO: MemSD->getMemOperand());
7277
7278 Results.push_back(Elt: DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::i8,
7279 Operand: NewLD.getValue(R: 0)));
7280 Results.push_back(Elt: NewLD.getValue(R: 1));
7281 }
7282 return;
7283 }
7284
7285 case Intrinsic::nvvm_tcgen05_ld_16x64b_x1:
7286 case Intrinsic::nvvm_tcgen05_ld_16x64b_x4:
7287 case Intrinsic::nvvm_tcgen05_ld_16x64b_x8:
7288 case Intrinsic::nvvm_tcgen05_ld_16x64b_x16:
7289 case Intrinsic::nvvm_tcgen05_ld_16x64b_x32:
7290 case Intrinsic::nvvm_tcgen05_ld_16x64b_x64:
7291 case Intrinsic::nvvm_tcgen05_ld_16x64b_x128:
7292 case Intrinsic::nvvm_tcgen05_ld_32x32b_x1:
7293 case Intrinsic::nvvm_tcgen05_ld_32x32b_x4:
7294 case Intrinsic::nvvm_tcgen05_ld_32x32b_x8:
7295 case Intrinsic::nvvm_tcgen05_ld_32x32b_x16:
7296 case Intrinsic::nvvm_tcgen05_ld_32x32b_x32:
7297 case Intrinsic::nvvm_tcgen05_ld_32x32b_x64:
7298 case Intrinsic::nvvm_tcgen05_ld_32x32b_x128:
7299 case Intrinsic::nvvm_tcgen05_ld_16x128b_x2:
7300 case Intrinsic::nvvm_tcgen05_ld_16x128b_x4:
7301 case Intrinsic::nvvm_tcgen05_ld_16x128b_x8:
7302 case Intrinsic::nvvm_tcgen05_ld_16x128b_x16:
7303 case Intrinsic::nvvm_tcgen05_ld_16x128b_x32:
7304 case Intrinsic::nvvm_tcgen05_ld_16x128b_x64:
7305 case Intrinsic::nvvm_tcgen05_ld_16x256b_x1:
7306 case Intrinsic::nvvm_tcgen05_ld_16x256b_x2:
7307 case Intrinsic::nvvm_tcgen05_ld_16x256b_x4:
7308 case Intrinsic::nvvm_tcgen05_ld_16x256b_x8:
7309 case Intrinsic::nvvm_tcgen05_ld_16x256b_x16:
7310 case Intrinsic::nvvm_tcgen05_ld_16x256b_x32:
7311 if (auto Res = lowerTcgen05Ld(N, DAG)) {
7312 Results.push_back(Elt: Res->first);
7313 Results.push_back(Elt: Res->second);
7314 }
7315 return;
7316
7317 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x1:
7318 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x4:
7319 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x8:
7320 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x16:
7321 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x32:
7322 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x64:
7323 case Intrinsic::nvvm_tcgen05_ld_16x32bx2_x128:
7324 if (auto Res = lowerTcgen05Ld(N, DAG, /*HasOffset=*/true)) {
7325 Results.push_back(Elt: Res->first);
7326 Results.push_back(Elt: Res->second);
7327 }
7328 return;
7329
7330 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_i32:
7331 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x8_f32:
7332 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_i32:
7333 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x64_f32:
7334 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_i32:
7335 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x4_f32:
7336 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_i32:
7337 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x32_f32:
7338 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_i32:
7339 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x16_f32:
7340 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_i32:
7341 case Intrinsic::nvvm_tcgen05_ld_red_32x32b_x128_f32:
7342 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_i32:
7343 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x8_f32:
7344 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_i32:
7345 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x64_f32:
7346 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_i32:
7347 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x4_f32:
7348 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_i32:
7349 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x32_f32:
7350 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_i32:
7351 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x16_f32:
7352 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_i32:
7353 case Intrinsic::nvvm_tcgen05_ld_red_16x32bx2_x128_f32:
7354 if (auto Res = lowerTcgen05LdRed(N, DAG)) {
7355 Results.push_back(Elt: std::get<0>(t&: *Res));
7356 Results.push_back(Elt: std::get<1>(t&: *Res));
7357 Results.push_back(Elt: std::get<2>(t&: *Res));
7358 }
7359 return;
7360 }
7361}
7362
7363static void ReplaceCopyFromReg_128(SDNode *N, SelectionDAG &DAG,
7364 SmallVectorImpl<SDValue> &Results) {
7365 // Change the CopyFromReg to output 2 64-bit results instead of a 128-bit
7366 // result so that it can pass the legalization
7367 SDLoc DL(N);
7368 SDValue Chain = N->getOperand(Num: 0);
7369 SDValue Reg = N->getOperand(Num: 1);
7370 SDValue Glue = N->getOperand(Num: 2);
7371
7372 assert(Reg.getValueType() == MVT::i128 &&
7373 "Custom lowering for CopyFromReg with 128-bit reg only");
7374 SmallVector<EVT, 4> ResultsType = {MVT::i64, MVT::i64, N->getValueType(ResNo: 1),
7375 N->getValueType(ResNo: 2)};
7376 SmallVector<SDValue, 3> NewOps = {Chain, Reg, Glue};
7377
7378 SDValue NewValue = DAG.getNode(Opcode: ISD::CopyFromReg, DL, ResultTys: ResultsType, Ops: NewOps);
7379 SDValue Pair = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: MVT::i128,
7380 Ops: {NewValue.getValue(R: 0), NewValue.getValue(R: 1)});
7381
7382 Results.push_back(Elt: Pair);
7383 Results.push_back(Elt: NewValue.getValue(R: 2));
7384 Results.push_back(Elt: NewValue.getValue(R: 3));
7385}
7386
7387static void replaceProxyReg(SDNode *N, SelectionDAG &DAG,
7388 const TargetLowering &TLI,
7389 SmallVectorImpl<SDValue> &Results) {
7390 SDValue Chain = N->getOperand(Num: 0);
7391 SDValue Reg = N->getOperand(Num: 1);
7392
7393 MVT VT = TLI.getRegisterType(Context&: *DAG.getContext(), VT: Reg.getValueType());
7394
7395 SDValue NewReg = DAG.getAnyExtOrTrunc(Op: Reg, DL: SDLoc(N), VT);
7396 SDValue NewProxy =
7397 DAG.getNode(Opcode: NVPTXISD::ProxyReg, DL: SDLoc(N), VT, Ops: {Chain, NewReg});
7398 SDValue Res = DAG.getAnyExtOrTrunc(Op: NewProxy, DL: SDLoc(N), VT: N->getValueType(ResNo: 0));
7399
7400 Results.push_back(Elt: Res);
7401}
7402
7403static void replaceAtomicSwap128(SDNode *N, SelectionDAG &DAG,
7404 const NVPTXSubtarget &STI,
7405 SmallVectorImpl<SDValue> &Results) {
7406 assert(N->getValueType(0) == MVT::i128 &&
7407 "Custom lowering for atomic128 only supports i128");
7408
7409 AtomicSDNode *AN = cast<AtomicSDNode>(Val: N);
7410 SDLoc dl(N);
7411
7412 if (!STI.hasAtomSwap128()) {
7413 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
7414 DAG.getMachineFunction().getFunction(),
7415 "Support for b128 atomics introduced in PTX ISA version 8.3 and "
7416 "requires target sm_90.",
7417 dl.getDebugLoc()));
7418
7419 Results.push_back(Elt: DAG.getUNDEF(VT: MVT::i128));
7420 Results.push_back(Elt: AN->getOperand(Num: 0)); // Chain
7421 return;
7422 }
7423
7424 SmallVector<SDValue, 6> Ops;
7425 Ops.push_back(Elt: AN->getOperand(Num: 0)); // Chain
7426 Ops.push_back(Elt: AN->getOperand(Num: 1)); // Ptr
7427 for (const auto &Op : AN->ops().drop_front(N: 2)) {
7428 // Low part
7429 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i64, N1: Op,
7430 N2: DAG.getIntPtrConstant(Val: 0, DL: dl)));
7431 // High part
7432 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i64, N1: Op,
7433 N2: DAG.getIntPtrConstant(Val: 1, DL: dl)));
7434 }
7435 unsigned Opcode = N->getOpcode() == ISD::ATOMIC_SWAP
7436 ? NVPTXISD::ATOMIC_SWAP_B128
7437 : NVPTXISD::ATOMIC_CMP_SWAP_B128;
7438 SDVTList Tys = DAG.getVTList(VT1: MVT::i64, VT2: MVT::i64, VT3: MVT::Other);
7439 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, VTList: Tys, Ops, MemVT: MVT::i128,
7440 MMO: AN->getMemOperand());
7441 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i128,
7442 Ops: {Result.getValue(R: 0), Result.getValue(R: 1)}));
7443 Results.push_back(Elt: Result.getValue(R: 2));
7444}
7445
7446void NVPTXTargetLowering::ReplaceNodeResults(
7447 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
7448 switch (N->getOpcode()) {
7449 default:
7450 report_fatal_error(reason: "Unhandled custom legalization");
7451 case ISD::BITCAST:
7452 ReplaceBITCAST(Node: N, DAG, Results);
7453 return;
7454 case ISD::LOAD:
7455 case ISD::MLOAD:
7456 replaceLoadVector(N, DAG, Results, STI);
7457 return;
7458 case ISD::INTRINSIC_W_CHAIN:
7459 ReplaceINTRINSIC_W_CHAIN(N, DAG, Results);
7460 return;
7461 case ISD::CopyFromReg:
7462 ReplaceCopyFromReg_128(N, DAG, Results);
7463 return;
7464 case NVPTXISD::ProxyReg:
7465 replaceProxyReg(N, DAG, TLI: *this, Results);
7466 return;
7467 case ISD::ATOMIC_CMP_SWAP:
7468 case ISD::ATOMIC_SWAP:
7469 replaceAtomicSwap128(N, DAG, STI, Results);
7470 return;
7471 }
7472}
7473
7474NVPTXTargetLowering::AtomicExpansionKind
7475NVPTXTargetLowering::shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const {
7476 Type *Ty = AI->getValOperand()->getType();
7477
7478 // Try to lower LLVM atomicrmw fadd to PTX atomic.add. This is complicated
7479 // by the weird FTZ behavior PTX atom.add has:
7480 // - atom.add.f32 on global memory flushes denormals
7481 // - atom.add.f32 on shared memory does not flush denormals
7482 // - atom.add.f16 and atomic.add.bf16 never flush denormals
7483 //
7484 // We lower to atom.add only if the function's FTZ behavior matches that of
7485 // atom.add; otherwise, we lower to a CAS loop. But we always allow
7486 // atomic.add.bf16; even though it never flushes denormals, we never flush
7487 // bf16 denormals when doing regular arithmetic, even when FTZ is enabled.
7488 if (AI->isFloatingPointOperation() &&
7489 AI->getOperation() == AtomicRMWInst::BinOp::FAdd) {
7490 const bool FTZ =
7491 AI->getFunction()->getDenormalMode(FPType: APFloat::IEEEsingle()).Output ==
7492 DenormalMode::PreserveSign;
7493
7494 // AllowFTZAtomics forces atom.add regardless of the FTZ mismatch.
7495 if (Ty->isFloatTy()) {
7496 bool UseNative = AllowFTZAtomics;
7497 switch (AI->getPointerAddressSpace()) {
7498 case llvm::ADDRESS_SPACE_GLOBAL:
7499 UseNative |= FTZ;
7500 break;
7501 case llvm::ADDRESS_SPACE_SHARED:
7502 case llvm::ADDRESS_SPACE_SHARED_CLUSTER:
7503 UseNative |= !FTZ;
7504 break;
7505 }
7506 if (UseNative)
7507 return AtomicExpansionKind::None;
7508 }
7509
7510 if (Ty->isHalfTy() && (!FTZ || AllowFTZAtomics) &&
7511 STI.getSmVersion() >= 70 && STI.getPTXVersion() >= 63)
7512 return AtomicExpansionKind::None;
7513
7514 if (Ty->isBFloatTy() && STI.getSmVersion() >= 90 &&
7515 STI.getPTXVersion() >= 78)
7516 return AtomicExpansionKind::None;
7517
7518 if (Ty->isDoubleTy() && STI.hasAtomAddF64())
7519 return AtomicExpansionKind::None;
7520 }
7521
7522 // PTX's only atomic fp op is `add`; all other ops expand to a CAS loop.
7523 if (AI->isFloatingPointOperation())
7524 return AtomicExpansionKind::CmpXChg;
7525
7526 assert(Ty->isIntegerTy() && "Ty should be integer at this point");
7527 const unsigned BitWidth = cast<IntegerType>(Val: Ty)->getBitWidth();
7528
7529 switch (AI->getOperation()) {
7530 default:
7531 return AtomicExpansionKind::CmpXChg;
7532 case AtomicRMWInst::BinOp::Xchg:
7533 if (BitWidth == 128)
7534 return AtomicExpansionKind::None;
7535 [[fallthrough]];
7536 case AtomicRMWInst::BinOp::And:
7537 case AtomicRMWInst::BinOp::Or:
7538 case AtomicRMWInst::BinOp::Xor:
7539 switch (BitWidth) {
7540 case 8:
7541 case 16:
7542 return AtomicExpansionKind::CmpXChg;
7543 case 32:
7544 return AtomicExpansionKind::None;
7545 case 64:
7546 if (STI.hasAtomBitwise64())
7547 return AtomicExpansionKind::None;
7548 return AtomicExpansionKind::CmpXChg;
7549 case 128:
7550 return AtomicExpansionKind::CmpXChg;
7551 default:
7552 llvm_unreachable("unsupported width encountered");
7553 }
7554 case AtomicRMWInst::BinOp::Add:
7555 case AtomicRMWInst::BinOp::Sub:
7556 case AtomicRMWInst::BinOp::Max:
7557 case AtomicRMWInst::BinOp::Min:
7558 case AtomicRMWInst::BinOp::UMax:
7559 case AtomicRMWInst::BinOp::UMin:
7560 switch (BitWidth) {
7561 case 8:
7562 case 16:
7563 return AtomicExpansionKind::CmpXChg;
7564 case 32:
7565 return AtomicExpansionKind::None;
7566 case 64:
7567 if (STI.hasAtomMinMax64())
7568 return AtomicExpansionKind::None;
7569 return AtomicExpansionKind::CmpXChg;
7570 case 128:
7571 return AtomicExpansionKind::CmpXChg;
7572 default:
7573 llvm_unreachable("unsupported width encountered");
7574 }
7575 case AtomicRMWInst::BinOp::UIncWrap:
7576 case AtomicRMWInst::BinOp::UDecWrap:
7577 switch (BitWidth) {
7578 case 32:
7579 return AtomicExpansionKind::None;
7580 case 8:
7581 case 16:
7582 case 64:
7583 case 128:
7584 return AtomicExpansionKind::CmpXChg;
7585 default:
7586 llvm_unreachable("unsupported width encountered");
7587 }
7588 }
7589
7590 return AtomicExpansionKind::CmpXChg;
7591}
7592
7593bool NVPTXTargetLowering::shouldInsertFencesForAtomic(
7594 const Instruction *I) const {
7595 // This function returns true iff the operation is emulated using a CAS-loop,
7596 // or if it has the memory order seq_cst (which is not natively supported in
7597 // the PTX `atom` instruction).
7598 //
7599 // atomicrmw and cmpxchg instructions not efficiently supported by PTX
7600 // are lowered to CAS emulation loops that preserve their memory order,
7601 // syncscope, and volatile semantics. For PTX, it is more efficient to use
7602 // atom.cas.relaxed.sco instructions within the loop, and fences before and
7603 // after the loop to restore order.
7604 //
7605 // Atomic instructions efficiently supported by PTX are lowered to
7606 // `atom.<op>.<sem>.<scope` instruction with their corresponding memory order
7607 // and scope. Since PTX does not support seq_cst, we emulate it by lowering to
7608 // a fence.sc followed by an atom according to the PTX atomics ABI
7609 // https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/atomic-abi.html
7610 if (auto *CI = dyn_cast<AtomicCmpXchgInst>(Val: I))
7611 return (cast<IntegerType>(Val: CI->getCompareOperand()->getType())
7612 ->getBitWidth() < STI.getMinCmpXchgSizeInBits()) ||
7613 CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent;
7614 if (auto *RI = dyn_cast<AtomicRMWInst>(Val: I))
7615 return shouldExpandAtomicRMWInIR(AI: RI) == AtomicExpansionKind::CmpXChg ||
7616 RI->getOrdering() == AtomicOrdering::SequentiallyConsistent;
7617 return false;
7618}
7619
7620AtomicOrdering NVPTXTargetLowering::atomicOperationOrderAfterFenceSplit(
7621 const Instruction *I) const {
7622 // If the operation is emulated by a CAS-loop, we lower the instruction to
7623 // atom.<op>.relaxed, since AtomicExpandPass will insert fences for enforcing
7624 // the correct memory ordering around the CAS loop.
7625 //
7626 // When the operation is not emulated, but the memory order is seq_cst,
7627 // we must lower to "fence.sc.<scope>; atom.<op>.acquire.<scope>;" to conform
7628 // to the PTX atomics ABI.
7629 // https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/atomic-abi.html
7630 // For such cases, emitLeadingFence() will separately insert the leading
7631 // "fence.sc.<scope>;". Here, we only set the memory order to acquire.
7632 //
7633 // Otherwise, the operation is not emulated, and the memory order is not
7634 // seq_cst. In this case, the LLVM memory order is natively supported by the
7635 // PTX `atom` instruction, and we just lower to the corresponding
7636 // `atom.<op>.relaxed|acquire|release|acq_rel". For such cases, this function
7637 // will NOT be called.
7638 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7639 // I before its memory order was modified.
7640 if (auto *CI = dyn_cast<AtomicCmpXchgInst>(Val: I);
7641 CI && CI->getMergedOrdering() == AtomicOrdering::SequentiallyConsistent &&
7642 cast<IntegerType>(Val: CI->getCompareOperand()->getType())->getBitWidth() >=
7643 STI.getMinCmpXchgSizeInBits())
7644 return AtomicOrdering::Acquire;
7645 else if (auto *RI = dyn_cast<AtomicRMWInst>(Val: I);
7646 RI && RI->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
7647 shouldExpandAtomicRMWInIR(AI: RI) == AtomicExpansionKind::None)
7648 return AtomicOrdering::Acquire;
7649
7650 return AtomicOrdering::Monotonic;
7651}
7652
7653Instruction *NVPTXTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
7654 Instruction *Inst,
7655 AtomicOrdering Ord) const {
7656 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7657 // `Inst` before its memory order was modified. We cannot enforce this with an
7658 // assert, because AtomicExpandPass will have modified the memory order
7659 // between the initial call to shouldInsertFencesForAtomic() and the call to
7660 // this function.
7661 if (!isa<AtomicCmpXchgInst>(Val: Inst) && !isa<AtomicRMWInst>(Val: Inst))
7662 return TargetLoweringBase::emitLeadingFence(Builder, Inst, Ord);
7663
7664 // Specialize for cmpxchg and atomicrmw
7665 auto SSID = getAtomicSyncScopeID(I: Inst);
7666 assert(SSID.has_value() && "Expected an atomic operation");
7667
7668 if (isReleaseOrStronger(AO: Ord))
7669 return Builder.CreateFence(Ordering: Ord == AtomicOrdering::SequentiallyConsistent
7670 ? AtomicOrdering::SequentiallyConsistent
7671 : AtomicOrdering::Release,
7672 SSID: SSID.value());
7673
7674 return nullptr;
7675}
7676
7677Instruction *NVPTXTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
7678 Instruction *Inst,
7679 AtomicOrdering Ord) const {
7680 // prerequisite: shouldInsertFencesForAtomic() should have returned `true` for
7681 // `Inst` before its memory order was modified. See `emitLeadingFence` for why
7682 // this cannot be enforced with an assert. Specialize for cmpxchg and
7683 // atomicrmw
7684 auto *CI = dyn_cast<AtomicCmpXchgInst>(Val: Inst);
7685 auto *RI = dyn_cast<AtomicRMWInst>(Val: Inst);
7686 if (!CI && !RI)
7687 return TargetLoweringBase::emitTrailingFence(Builder, Inst, Ord);
7688
7689 auto SSID = getAtomicSyncScopeID(I: Inst);
7690 assert(SSID.has_value() && "Expected an atomic operation");
7691
7692 bool IsEmulated =
7693 CI ? cast<IntegerType>(Val: CI->getCompareOperand()->getType())
7694 ->getBitWidth() < STI.getMinCmpXchgSizeInBits()
7695 : shouldExpandAtomicRMWInIR(AI: RI) == AtomicExpansionKind::CmpXChg;
7696
7697 if (isAcquireOrStronger(AO: Ord) && IsEmulated)
7698 return Builder.CreateFence(Ordering: AtomicOrdering::Acquire, SSID: SSID.value());
7699
7700 return nullptr;
7701}
7702
7703// Rather than default to SINT when both UINT and SINT are custom, we only
7704// change the opcode when UINT is not legal and SINT is. UINT is preferred when
7705// both are custom since unsigned CVT instructions can lead to slightly better
7706// SASS code with fewer instructions.
7707unsigned NVPTXTargetLowering::getPreferredFPToIntOpcode(unsigned Op, EVT FromVT,
7708 EVT ToVT) const {
7709 if (isOperationLegal(Op, VT: ToVT))
7710 return Op;
7711 switch (Op) {
7712 case ISD::FP_TO_UINT:
7713 if (isOperationLegal(Op: ISD::FP_TO_SINT, VT: ToVT))
7714 return ISD::FP_TO_SINT;
7715 break;
7716 case ISD::STRICT_FP_TO_UINT:
7717 if (isOperationLegal(Op: ISD::STRICT_FP_TO_SINT, VT: ToVT))
7718 return ISD::STRICT_FP_TO_SINT;
7719 break;
7720 case ISD::VP_FP_TO_UINT:
7721 if (isOperationLegal(Op: ISD::VP_FP_TO_SINT, VT: ToVT))
7722 return ISD::VP_FP_TO_SINT;
7723 break;
7724 default:
7725 break;
7726 }
7727 return Op;
7728}
7729
7730// Pin NVPTXTargetObjectFile's vtables to this file.
7731NVPTXTargetObjectFile::~NVPTXTargetObjectFile() = default;
7732
7733MCSection *NVPTXTargetObjectFile::SelectSectionForGlobal(
7734 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
7735 return getDataSection();
7736}
7737
7738static void computeKnownBitsForPRMT(const SDValue Op, KnownBits &Known,
7739 const SelectionDAG &DAG, unsigned Depth) {
7740 SDValue A = Op.getOperand(i: 0);
7741 SDValue B = Op.getOperand(i: 1);
7742 ConstantSDNode *Selector = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 2));
7743 unsigned Mode = Op.getConstantOperandVal(i: 3);
7744
7745 if (!Selector)
7746 return;
7747
7748 KnownBits AKnown = DAG.computeKnownBits(Op: A, Depth);
7749 KnownBits BKnown = DAG.computeKnownBits(Op: B, Depth);
7750
7751 // {b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}
7752 assert(AKnown.getBitWidth() == 32 && BKnown.getBitWidth() == 32 &&
7753 "PRMT must have i32 operands");
7754 assert(Known.getBitWidth() == 32 && "PRMT must have i32 result");
7755 KnownBits BitField = BKnown.concat(Lo: AKnown);
7756
7757 APInt SelectorVal = getPRMTSelector(Selector: Selector->getAPIntValue(), Mode);
7758 for (unsigned I : llvm::seq(Size: 4)) {
7759 APInt Sel = SelectorVal.extractBits(numBits: 4, bitPosition: I * 4);
7760 unsigned Idx = Sel.getLoBits(numBits: 3).getZExtValue();
7761 unsigned Sign = Sel.getHiBits(numBits: 1).getZExtValue();
7762 KnownBits Byte = BitField.extractBits(NumBits: 8, BitPosition: Idx * 8);
7763 if (Sign)
7764 Byte = KnownBits::ashr(LHS: Byte, RHS: KnownBits::makeConstant(C: APInt(8, 7)));
7765 Known.insertBits(SubBits: Byte, BitPosition: I * 8);
7766 }
7767}
7768
7769static void computeKnownBitsForLoadV(const SDValue Op, KnownBits &Known) {
7770 MemSDNode *LD = cast<MemSDNode>(Val: Op);
7771
7772 // We can't do anything without knowing the sign bit.
7773 auto ExtType = LD->getConstantOperandVal(Num: LD->getNumOperands() - 1);
7774 if (ExtType == ISD::SEXTLOAD)
7775 return;
7776
7777 // ExtLoading to vector types is weird and may not work well with known bits.
7778 auto DestVT = LD->getValueType(ResNo: 0);
7779 if (DestVT.isVector())
7780 return;
7781
7782 assert(Known.getBitWidth() == DestVT.getSizeInBits());
7783 auto ElementBitWidth = NVPTXDAGToDAGISel::getFromTypeWidthForLoad(Mem: LD);
7784 Known.Zero.setHighBits(Known.getBitWidth() - ElementBitWidth);
7785}
7786
7787void NVPTXTargetLowering::computeKnownBitsForTargetNode(
7788 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
7789 const SelectionDAG &DAG, unsigned Depth) const {
7790 Known.resetAll();
7791
7792 switch (Op.getOpcode()) {
7793 case NVPTXISD::PRMT:
7794 computeKnownBitsForPRMT(Op, Known, DAG, Depth);
7795 break;
7796 case NVPTXISD::LoadV2:
7797 case NVPTXISD::LoadV4:
7798 case NVPTXISD::LoadV8:
7799 computeKnownBitsForLoadV(Op, Known);
7800 break;
7801 default:
7802 break;
7803 }
7804}
7805
7806static std::pair<APInt, APInt> getPRMTDemandedBits(const APInt &SelectorVal,
7807 const APInt &DemandedBits) {
7808 APInt DemandedLHS = APInt(32, 0);
7809 APInt DemandedRHS = APInt(32, 0);
7810
7811 for (unsigned I : llvm::seq(Size: 4)) {
7812 if (DemandedBits.extractBits(numBits: 8, bitPosition: I * 8).isZero())
7813 continue;
7814
7815 APInt Sel = SelectorVal.extractBits(numBits: 4, bitPosition: I * 4);
7816 unsigned Idx = Sel.getLoBits(numBits: 3).getZExtValue();
7817 unsigned Sign = Sel.getHiBits(numBits: 1).getZExtValue();
7818
7819 APInt &Src = Idx < 4 ? DemandedLHS : DemandedRHS;
7820 unsigned ByteStart = (Idx % 4) * 8;
7821 if (Sign)
7822 Src.setBit(ByteStart + 7);
7823 else
7824 Src.setBits(loBit: ByteStart, hiBit: ByteStart + 8);
7825 }
7826
7827 return {DemandedLHS, DemandedRHS};
7828}
7829
7830// Replace undef with 0 as this is easier for other optimizations such as
7831// known bits.
7832static SDValue canonicalizePRMTInput(SDValue Op, SelectionDAG &DAG) {
7833 if (!Op)
7834 return SDValue();
7835 if (Op.isUndef())
7836 return DAG.getConstant(Val: 0, DL: SDLoc(), VT: MVT::i32);
7837 return Op;
7838}
7839
7840static SDValue simplifyDemandedBitsForPRMT(SDValue PRMT,
7841 const APInt &DemandedBits,
7842 SelectionDAG &DAG,
7843 const TargetLowering &TLI,
7844 unsigned Depth) {
7845 assert(PRMT.getOpcode() == NVPTXISD::PRMT);
7846 SDValue Op0 = PRMT.getOperand(i: 0);
7847 SDValue Op1 = PRMT.getOperand(i: 1);
7848 auto *SelectorConst = dyn_cast<ConstantSDNode>(Val: PRMT.getOperand(i: 2));
7849 if (!SelectorConst)
7850 return SDValue();
7851
7852 unsigned Mode = PRMT.getConstantOperandVal(i: 3);
7853 const APInt Selector = getPRMTSelector(Selector: SelectorConst->getAPIntValue(), Mode);
7854
7855 // Try to simplify the PRMT to one of the inputs if the used bytes are all
7856 // from the same input in the correct order.
7857 const unsigned LeadingBytes = DemandedBits.countLeadingZeros() / 8;
7858 const unsigned SelBits = (4 - LeadingBytes) * 4;
7859 if (Selector.getLoBits(numBits: SelBits) == APInt(32, 0x3210).getLoBits(numBits: SelBits))
7860 return Op0;
7861 if (Selector.getLoBits(numBits: SelBits) == APInt(32, 0x7654).getLoBits(numBits: SelBits))
7862 return Op1;
7863
7864 auto [DemandedLHS, DemandedRHS] = getPRMTDemandedBits(SelectorVal: Selector, DemandedBits);
7865
7866 // Attempt to avoid multi-use ops if we don't need anything from them.
7867 SDValue DemandedOp0 =
7868 TLI.SimplifyMultipleUseDemandedBits(Op: Op0, DemandedBits: DemandedLHS, DAG, Depth: Depth + 1);
7869 SDValue DemandedOp1 =
7870 TLI.SimplifyMultipleUseDemandedBits(Op: Op1, DemandedBits: DemandedRHS, DAG, Depth: Depth + 1);
7871
7872 DemandedOp0 = canonicalizePRMTInput(Op: DemandedOp0, DAG);
7873 DemandedOp1 = canonicalizePRMTInput(Op: DemandedOp1, DAG);
7874 if ((DemandedOp0 && DemandedOp0 != Op0) ||
7875 (DemandedOp1 && DemandedOp1 != Op1)) {
7876 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
7877 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
7878 return getPRMT(A: Op0, B: Op1, Selector: Selector.getZExtValue(), DL: SDLoc(PRMT), DAG);
7879 }
7880
7881 return SDValue();
7882}
7883
7884bool NVPTXTargetLowering::SimplifyDemandedBitsForTargetNode(
7885 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7886 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
7887 Known.resetAll();
7888
7889 switch (Op.getOpcode()) {
7890 case NVPTXISD::PRMT:
7891 if (SDValue Result = simplifyDemandedBitsForPRMT(PRMT: Op, DemandedBits, DAG&: TLO.DAG,
7892 TLI: *this, Depth)) {
7893 TLO.CombineTo(O: Op, N: Result);
7894 return true;
7895 }
7896 break;
7897 default:
7898 break;
7899 }
7900
7901 computeKnownBitsForTargetNode(Op, Known, DemandedElts, DAG: TLO.DAG, Depth);
7902 return false;
7903}
7904