LLVM 24.0.0git
SIISelLowering.cpp
Go to the documentation of this file.
1//===-- SIISelLowering.cpp - SI 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/// \file
10/// Custom DAG lowering for SI
11//
12//===----------------------------------------------------------------------===//
13
14#include "SIISelLowering.h"
15#include "AMDGPU.h"
16#include "AMDGPUIGroupLP.h"
17#include "AMDGPUInstrInfo.h"
18#include "AMDGPULaneMaskUtils.h"
19#include "AMDGPUMachineInstrs.h"
20#include "AMDGPUMemoryUtils.h"
22#include "AMDGPUTargetMachine.h"
23#include "GCNSubtarget.h"
26#include "SIRegisterInfo.h"
27#include "llvm/ADT/APFloat.h"
28#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/Statistic.h"
46#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/IntrinsicsAMDGPU.h"
49#include "llvm/IR/IntrinsicsR600.h"
50#include "llvm/IR/MDBuilder.h"
54#include "llvm/Support/ModRef.h"
57#include <cmath>
58#include <optional>
59
60using namespace llvm;
61using namespace llvm::SDPatternMatch;
62
63#define DEBUG_TYPE "si-lower"
64
65STATISTIC(NumTailCalls, "Number of tail calls");
66
68 return MF.getInfo<SIMachineFunctionInfo>()->getMode().getDenormalFPEnv();
69}
70
75
80
81static unsigned findFirstFreeSGPR(CCState &CCInfo) {
82 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
83 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
84 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
85 return AMDGPU::SGPR0 + Reg;
86 }
87 }
88 llvm_unreachable("Cannot allocate sgpr");
89}
90
92 const GCNSubtarget &STI)
93 : AMDGPUTargetLowering(TM, STI, STI), Subtarget(&STI) {
94 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
95 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
96
97 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
98
99 const SIRegisterInfo *TRI = STI.getRegisterInfo();
100 const TargetRegisterClass *V32RegClass =
101 TRI->getDefaultVectorSuperClassForBitWidth(32);
102 addRegisterClass(MVT::f32, V32RegClass);
103
104 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
105
106 const TargetRegisterClass *V64RegClass =
107 TRI->getDefaultVectorSuperClassForBitWidth(64);
108
109 addRegisterClass(MVT::f64, V64RegClass);
110 addRegisterClass(MVT::v2f32, V64RegClass);
111 addRegisterClass(MVT::Untyped, V64RegClass);
112
113 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
114 addRegisterClass(MVT::v3f32, TRI->getDefaultVectorSuperClassForBitWidth(96));
115
116 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
117 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
118
119 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
120 addRegisterClass(MVT::v4f32, TRI->getDefaultVectorSuperClassForBitWidth(128));
121
122 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
123 addRegisterClass(MVT::v5f32, TRI->getDefaultVectorSuperClassForBitWidth(160));
124
125 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
126 addRegisterClass(MVT::v6f32, TRI->getDefaultVectorSuperClassForBitWidth(192));
127
128 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
129 addRegisterClass(MVT::v3f64, TRI->getDefaultVectorSuperClassForBitWidth(192));
130
131 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
132 addRegisterClass(MVT::v7f32, TRI->getDefaultVectorSuperClassForBitWidth(224));
133
134 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
135 addRegisterClass(MVT::v8f32, TRI->getDefaultVectorSuperClassForBitWidth(256));
136
137 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
138 addRegisterClass(MVT::v4f64, TRI->getDefaultVectorSuperClassForBitWidth(256));
139
140 addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
141 addRegisterClass(MVT::v9f32, TRI->getDefaultVectorSuperClassForBitWidth(288));
142
143 addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
144 addRegisterClass(MVT::v10f32,
145 TRI->getDefaultVectorSuperClassForBitWidth(320));
146
147 addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
148 addRegisterClass(MVT::v11f32,
149 TRI->getDefaultVectorSuperClassForBitWidth(352));
150
151 addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
152 addRegisterClass(MVT::v12f32,
153 TRI->getDefaultVectorSuperClassForBitWidth(384));
154
155 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
156 addRegisterClass(MVT::v16f32,
157 TRI->getDefaultVectorSuperClassForBitWidth(512));
158
159 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
160 addRegisterClass(MVT::v8f64, TRI->getDefaultVectorSuperClassForBitWidth(512));
161
162 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
163 addRegisterClass(MVT::v16f64,
164 TRI->getDefaultVectorSuperClassForBitWidth(1024));
165
166 if (Subtarget->has16BitInsts()) {
167 if (Subtarget->useRealTrue16Insts()) {
168 addRegisterClass(MVT::i16, &AMDGPU::VGPR_16RegClass);
169 addRegisterClass(MVT::f16, &AMDGPU::VGPR_16RegClass);
170 addRegisterClass(MVT::bf16, &AMDGPU::VGPR_16RegClass);
171 } else {
172 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
173 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
174 addRegisterClass(MVT::bf16, &AMDGPU::SReg_32RegClass);
175 }
176
177 // Unless there are also VOP3P operations, not operations are really legal.
178 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
179 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
180 addRegisterClass(MVT::v2bf16, &AMDGPU::SReg_32RegClass);
181 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
182 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
183 addRegisterClass(MVT::v4bf16, &AMDGPU::SReg_64RegClass);
184 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
185 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
186 addRegisterClass(MVT::v8bf16, &AMDGPU::SGPR_128RegClass);
187 addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
188 addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
189 addRegisterClass(MVT::v16bf16, &AMDGPU::SGPR_256RegClass);
190 addRegisterClass(MVT::v32i16, &AMDGPU::SGPR_512RegClass);
191 addRegisterClass(MVT::v32f16, &AMDGPU::SGPR_512RegClass);
192 addRegisterClass(MVT::v32bf16, &AMDGPU::SGPR_512RegClass);
193 }
194
195 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
196 addRegisterClass(MVT::v32f32,
197 TRI->getDefaultVectorSuperClassForBitWidth(1024));
198
199 computeRegisterProperties(Subtarget->getRegisterInfo());
200
203
204 // The boolean content concept here is too inflexible. Compares only ever
205 // really produce a 1-bit result. Any copy/extend from these will turn into a
206 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
207 // it's what most targets use.
210
211 // We need to custom lower vector stores from local memory
213 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
214 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
215 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
216 MVT::i1, MVT::v32i32},
217 Custom);
218
220 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
221 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
222 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
223 MVT::i1, MVT::v32i32},
224 Custom);
225
226 if (isTypeLegal(MVT::bf16)) {
227 for (unsigned Opc :
236 ISD::SETCC}) {
237 setOperationAction(Opc, MVT::bf16, Promote);
238 }
239
240 // Only targets with packed bf16 instructions, e.g. gfx13.
241 if (Subtarget->hasBF16PackedInsts()) {
242 // Don't use Expand for fsub - the DAG combiner will undo fadd+fneg back
243 // to fsub, causing a libcall (which doesn't exist for bf16). Instead,
244 // directly expand to widened v2bf16 operations.
247 Promote);
248 // Promote scalar operations to a v2bf16 operation with an unused high
249 // lane.
250 for (unsigned Opc :
253 AddPromotedToType(Opc, MVT::bf16, MVT::v2bf16);
254 }
255
257
259 AddPromotedToType(ISD::SELECT, MVT::bf16, MVT::i16);
260
264
265 // We only need to custom lower because we can't specify an action for bf16
266 // sources.
269 }
270
271 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
272 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
273 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
274 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
275 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
276 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
277 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
278 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
279 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
280 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
281 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
282 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
283 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
284 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
285 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
286 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
287
288 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
289 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
290 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
291 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
292 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
293 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
294 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
295
296 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
297
298 // Only for an alloca in the VGPR ("as memory") address space.
300 setOperationAction(ISD::BlockAddress, {MVT::i32, MVT::i64}, Custom);
301 setOperationAction(ISD::ExternalSymbol, {MVT::i32, MVT::i64}, Custom);
302
306 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
307
308 setOperationAction(ISD::FSQRT, {MVT::f32, MVT::f64}, Custom);
309
311 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
312
314 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
315 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
316
318 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
319 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v9i32,
320 MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32},
321 Expand);
323 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
324 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v9f32,
325 MVT::v10f32, MVT::v11f32, MVT::v12f32, MVT::v16f32},
326 Expand);
327
329 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
330 MVT::v3i16, MVT::v4i16, MVT::Other},
331 Custom);
332
335 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
336
339
342
344 Expand);
345
347
348 // We only support LOAD/STORE and vector manipulation ops for vectors
349 // with > 4 elements.
350 for (MVT VT :
351 {MVT::v8i32, MVT::v8f32, MVT::v9i32, MVT::v9f32, MVT::v10i32,
352 MVT::v10f32, MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32,
353 MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64, MVT::v4i16,
354 MVT::v4f16, MVT::v4bf16, MVT::v3i64, MVT::v3f64, MVT::v6i32,
355 MVT::v6f32, MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
356 MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
357 MVT::v16bf16, MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32,
358 MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
359 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
360 switch (Op) {
361 case ISD::LOAD:
362 case ISD::STORE:
363 case ISD::ATOMIC_LOAD:
366 case ISD::BITCAST:
367 case ISD::UNDEF:
368 case ISD::POISON:
372 case ISD::IS_FPCLASS:
373 break;
378 break;
379 default:
381 break;
382 }
383 }
384 }
385
387
388 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
389 // is expanded to avoid having two separate loops in case the index is a VGPR.
390
391 // Most operations are naturally 32-bit vector operations. We only support
392 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
393 for (MVT Vec64 : {MVT::v2i64, MVT::v2f64}) {
395 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
396
398 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
399
401 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
402
404 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
405 }
406
407 for (MVT Vec64 : {MVT::v3i64, MVT::v3f64}) {
409 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
410
412 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
413
415 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
416
418 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
419 }
420
421 for (MVT Vec64 : {MVT::v4i64, MVT::v4f64}) {
423 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
424
426 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
427
429 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
430
432 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
433 }
434
435 for (MVT Vec64 : {MVT::v8i64, MVT::v8f64}) {
437 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
438
440 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
441
443 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
444
446 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
447 }
448
449 for (MVT Vec64 : {MVT::v16i64, MVT::v16f64}) {
451 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
452
454 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
455
457 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
458
460 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
461 }
462
464 {MVT::v4i32, MVT::v4f32, MVT::v8i32, MVT::v8f32,
465 MVT::v16i32, MVT::v16f32, MVT::v32i32, MVT::v32f32},
466 Custom);
467
468 if (Subtarget->hasPkMovB32()) {
469 // TODO: 16-bit element vectors should be legal with even aligned elements.
470 // TODO: Can be legal with wider source types than the result with
471 // subregister extracts.
472 setOperationAction(ISD::VECTOR_SHUFFLE, {MVT::v2i32, MVT::v2f32}, Legal);
473 }
474
476 // Prevent SELECT v2i32 from being implemented with the above bitwise ops and
477 // instead lower to cndmask in SITargetLowering::LowerSELECT().
479 // Enable MatchRotate to produce ISD::ROTR, which is later transformed to
480 // alignbit.
481 setOperationAction(ISD::ROTR, MVT::v2i32, Custom);
482
483 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16, MVT::v4bf16},
484 Custom);
485
486 // Avoid stack access for these.
487 // TODO: Generalize to wider i8 vectors.
489 {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v2i8, MVT::v4i8,
490 MVT::v8i8, MVT::v4i16, MVT::v4f16, MVT::v4bf16},
491 Custom);
492
493 // Deal with vec3 vector operations when widened to vec4.
495 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
496
497 // Deal with vec5/6/7 vector operations when widened to vec8.
499 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
500 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32,
501 MVT::v9i32, MVT::v9f32, MVT::v10i32, MVT::v10f32,
502 MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32},
503 Custom);
504
505 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
506 // and output demarshalling
507 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
508
509 // We can't return success/failure, only the old value,
510 // let LLVM add the comparison
512 Expand);
513
514 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
515
516 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
517
518 // FIXME: This should be narrowed to i32, but that only happens if i64 is
519 // illegal.
520 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
521 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
522
523 // On SI this is s_memtime and s_memrealtime on VI.
525
526 if (Subtarget->hasSMemRealTime() ||
527 Subtarget->getGeneration() >= AMDGPUSubtarget::GFX11)
530
531 if (Subtarget->has16BitInsts()) {
534 setOperationAction(ISD::IS_FPCLASS, {MVT::f16, MVT::f32, MVT::f64}, Legal);
537 } else {
539 }
540
541 if (Subtarget->hasMadMacF32Insts())
543
547
548 // We only really have 32-bit BFE instructions (and 16-bit on VI).
549 //
550 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
551 // effort to match them now. We want this to be false for i64 cases when the
552 // extraction isn't restricted to the upper or lower half. Ideally we would
553 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
554 // span the midpoint are probably relatively rare, so don't worry about them
555 // for now.
557
558 // Clamp modifier on add/sub
559 if (Subtarget->hasIntClamp())
561
562 if (Subtarget->hasAddNoCarryInsts())
563 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
564 Legal);
565
566 // Do not have s_{min|max}_*f64 instruction f64 will only be lowered to
567 // v_{min|max}_*f64
568 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
571 {MVT::f64, MVT::f32}, Legal);
572 } else {
575 {MVT::f64, MVT::f32}, Custom);
576 // These are really only legal for ieee_mode functions. We should be
577 // avoiding them for functions that don't have ieee_mode enabled, so just
578 // say they are legal.
580 {MVT::f64, MVT::f32}, Legal);
581 }
582
583 if (Subtarget->haveRoundOpsF64())
585 Legal);
586 else
588 MVT::f64, Custom);
589
591 setOperationAction({ISD::FLDEXP, ISD::STRICT_FLDEXP}, {MVT::f32, MVT::f64},
592 Legal);
593 setOperationAction(ISD::FFREXP, {MVT::f32, MVT::f64}, Custom);
594
597
598 setOperationAction(ISD::BF16_TO_FP, {MVT::i16, MVT::f32, MVT::f64}, Expand);
599 setOperationAction(ISD::FP_TO_BF16, {MVT::i16, MVT::f32, MVT::f64}, Expand);
600
602 Custom);
604 Custom);
606 Custom);
607
608 // Custom lower these because we can't specify a rule based on an illegal
609 // source bf16.
612
613 if (Subtarget->has16BitInsts()) {
616 MVT::i16, Legal);
617
618 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
619
621 MVT::i16, Expand);
622
626 ISD::CTPOP},
627 MVT::i16, Promote);
628
630
631 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
632
634 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
636 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
637
642
644
645 // F16 - Constant Actions.
648
649 // F16 - Load/Store Actions.
651 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
653 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
654
655 // BF16 - Load/Store Actions.
657 AddPromotedToType(ISD::LOAD, MVT::bf16, MVT::i16);
659 AddPromotedToType(ISD::STORE, MVT::bf16, MVT::i16);
660
661 if (!Subtarget->useRealTrue16Insts() ||
662 !Subtarget->d16PreservesUnusedBits()) {
663 for (MVT VT : {MVT::i16, MVT::f16, MVT::bf16}) {
665 AddPromotedToType(ISD::ATOMIC_LOAD, VT, MVT::i32);
666 }
667 }
668
669 if (!Subtarget->useRealTrue16Insts()) {
670 for (MVT VT : {MVT::i16, MVT::f16, MVT::bf16}) {
673 }
674 }
675
676 // F16 - VOP1 Actions.
679 MVT::f16, Custom);
680
681 // BF16 - VOP1 Actions.
682 if (Subtarget->hasBF16TransInsts())
684
685 // F16 - VOP2 Actions.
686 setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, {MVT::f16, MVT::bf16},
687 Expand);
691
692 // F16 - VOP3 Actions.
694 if (STI.hasMadF16())
696
697 for (MVT VT :
698 {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v4i16, MVT::v4f16,
699 MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16,
700 MVT::v16f16, MVT::v16bf16, MVT::v32i16, MVT::v32f16}) {
701 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
702 switch (Op) {
703 case ISD::LOAD:
704 case ISD::STORE:
705 case ISD::ATOMIC_LOAD:
708 case ISD::BITCAST:
709 case ISD::UNDEF:
710 case ISD::POISON:
715 case ISD::IS_FPCLASS:
716 break;
719 case ISD::FSIN:
720 case ISD::FCOS:
722 break;
723 default:
725 break;
726 }
727 }
728 }
729
730 // v_perm_b32 can handle either of these.
731 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
733
734 // Legalize vector types for sat conversions to select v_cvt_pk_[iu]16_f32.
735 if (Subtarget->hasVCvtPkIU16F32())
738 {MVT::v2i16, MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16},
739 Custom);
740
741 // XXX - Do these do anything? Vector constants turn into build_vector.
742 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
743
745 {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Legal);
746
748 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
750 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
751
753 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
755 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
756
757 setOperationAction(ISD::AND, MVT::v2i16, Promote);
758 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
759 setOperationAction(ISD::OR, MVT::v2i16, Promote);
760 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
761 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
762 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
763
765 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
767 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
768 setOperationAction(ISD::LOAD, MVT::v4bf16, Promote);
769 AddPromotedToType(ISD::LOAD, MVT::v4bf16, MVT::v2i32);
770
772 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
774 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
776 AddPromotedToType(ISD::STORE, MVT::v4bf16, MVT::v2i32);
777
779 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
781 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
782 setOperationAction(ISD::LOAD, MVT::v8bf16, Promote);
783 AddPromotedToType(ISD::LOAD, MVT::v8bf16, MVT::v4i32);
784
786 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
788 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
789
791 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
793 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
795 AddPromotedToType(ISD::STORE, MVT::v8bf16, MVT::v4i32);
796
797 setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
798 AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
799 setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
800 AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
801 setOperationAction(ISD::LOAD, MVT::v16bf16, Promote);
802 AddPromotedToType(ISD::LOAD, MVT::v16bf16, MVT::v8i32);
803
805 AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
807 AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
808 setOperationAction(ISD::STORE, MVT::v16bf16, Promote);
809 AddPromotedToType(ISD::STORE, MVT::v16bf16, MVT::v8i32);
810
811 setOperationAction(ISD::LOAD, MVT::v32i16, Promote);
812 AddPromotedToType(ISD::LOAD, MVT::v32i16, MVT::v16i32);
813 setOperationAction(ISD::LOAD, MVT::v32f16, Promote);
814 AddPromotedToType(ISD::LOAD, MVT::v32f16, MVT::v16i32);
815 setOperationAction(ISD::LOAD, MVT::v32bf16, Promote);
816 AddPromotedToType(ISD::LOAD, MVT::v32bf16, MVT::v16i32);
817
819 AddPromotedToType(ISD::STORE, MVT::v32i16, MVT::v16i32);
821 AddPromotedToType(ISD::STORE, MVT::v32f16, MVT::v16i32);
822 setOperationAction(ISD::STORE, MVT::v32bf16, Promote);
823 AddPromotedToType(ISD::STORE, MVT::v32bf16, MVT::v16i32);
824
826 MVT::v2i32, Expand);
828
830 MVT::v4i32, Expand);
831
833 MVT::v8i32, Expand);
834
835 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16, MVT::v2bf16},
836 Subtarget->hasVOP3PInsts() ? Legal : Custom);
837
838 setOperationAction(ISD::FNEG, {MVT::v2f16, MVT::v2bf16}, Legal);
839 // This isn't really legal, but this avoids the legalizer unrolling it (and
840 // allows matching fneg (fabs x) patterns)
841 setOperationAction(ISD::FABS, {MVT::v2f16, MVT::v2bf16}, Legal);
842
843 // Can do this in one BFI plus a constant materialize.
845 {MVT::v2f16, MVT::v2bf16, MVT::v4f16, MVT::v4bf16,
846 MVT::v8f16, MVT::v8bf16, MVT::v16f16, MVT::v16bf16,
847 MVT::v32f16, MVT::v32bf16},
848 Custom);
849 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
852 MVT::f16, Legal);
853
856 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16}, Custom);
857 } else {
860 MVT::f16, Custom);
861
863 Legal);
864
867 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
868 Custom);
869
871 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
872 Expand);
873 }
874
875 for (MVT Vec16 :
876 {MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
877 MVT::v16bf16, MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
880 Vec16, Custom);
881 }
882 }
883
884 if (Subtarget->hasVOP3PInsts()) {
888 MVT::v2i16, Legal);
889
892 MVT::v2f16, Legal);
893
895 {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Custom);
896
898 {MVT::v4f16, MVT::v4i16, MVT::v4bf16, MVT::v8f16,
899 MVT::v8i16, MVT::v8bf16, MVT::v16f16, MVT::v16i16,
900 MVT::v16bf16, MVT::v32f16, MVT::v32i16, MVT::v32bf16},
901 Custom);
902
903 for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16})
904 // Split vector operations.
909 VT, Custom);
910
911 for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16})
912 // Split vector operations.
915 VT, Custom);
916
917 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
920 MVT::v2f16, Legal);
921 } else {
923 Legal);
924
927 {MVT::v2f16, MVT::v4f16}, Custom);
928 }
929 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
930 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16, MVT::v4bf16},
931 Custom);
932
933 if (Subtarget->hasBF16PackedInsts()) {
937 MVT::v2bf16, Legal);
938
939 for (MVT VT : {MVT::v4bf16, MVT::v8bf16, MVT::v16bf16, MVT::v32bf16})
940 // Split vector operations.
944 VT, Custom);
945 }
946
947 if (Subtarget->hasAnyPackedFP32Ops()) {
949 MVT::v2f32, Legal);
951 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
952 Custom);
953 }
954 if (Subtarget->hasAnyPackedFP64Ops()) {
957 MVT::v2f64, Legal);
960 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64}, Custom);
961
962 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
965 MVT::v2f64, Legal);
966
969 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64}, Custom);
970 } else {
972 Legal);
975 MVT::v2f64, Custom);
978 {MVT::v4f64, MVT::v8f64, MVT::v16f64, MVT::v32f64},
979 Custom);
980 }
981 }
982
983 if (Subtarget->hasAnyPackedU64Ops()) {
985 MVT::v2i64, Legal);
987 {MVT::v4i64, MVT::v8i64, MVT::v16i64, MVT::v32i64},
988 Custom);
989 }
990 }
991
993
994 if (Subtarget->has16BitInsts()) {
996 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
998 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
1000 AddPromotedToType(ISD::SELECT, MVT::v2bf16, MVT::i32);
1001 } else {
1002 // Legalization hack.
1003 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
1004
1006 }
1007
1009 {MVT::v4i16, MVT::v4f16, MVT::v4bf16, MVT::v2i8, MVT::v4i8,
1010 MVT::v8i8, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
1011 MVT::v16i16, MVT::v16f16, MVT::v16bf16, MVT::v32i16,
1012 MVT::v32f16, MVT::v32bf16},
1013 Custom);
1014
1016
1017 if (Subtarget->useVMulU64Inst())
1018 setOperationAction(ISD::MUL, MVT::i64, Legal);
1019 else if (Subtarget->hasScalarSMulU64())
1021
1022 if (Subtarget->hasMad64_32())
1024
1025 if (Subtarget->hasSafeSmemPrefetch() || Subtarget->hasVmemPrefInsts())
1027 // Type legalization cannot expand the i128 pointer of a buffer resource
1028 // prefetch; lowerPREFETCH drops the prefetch instead.
1030
1031 if (Subtarget->hasIEEEMinimumMaximumInsts()) {
1033 {MVT::f16, MVT::f32, MVT::f64, MVT::v2f16}, Legal);
1034 } else {
1035 // FIXME: For nnan fmaximum, emit the fmaximum3 instead of fmaxnum
1036 if (Subtarget->hasMinimum3Maximum3F32())
1038
1039 if (Subtarget->hasMinimum3Maximum3PKF16()) {
1041
1042 // If only the vector form is available, we need to widen to a vector.
1043 if (!Subtarget->hasMinimum3Maximum3F16())
1045 MVT::v2f16);
1046 }
1047 }
1048
1049 if (Subtarget->hasVOP3PInsts()) {
1050 // We want to break these into v2f16 pieces, not scalarize.
1052 {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
1053 Custom);
1054 }
1055
1056 if (Subtarget->useMinMaxI64Insts())
1058 Legal);
1059
1061 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
1062 MVT::bf16, MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::i128,
1063 MVT::i8},
1064 Custom);
1065
1067 {MVT::v2f16, MVT::v2i16, MVT::v2bf16, MVT::v3f16,
1068 MVT::v3i16, MVT::v4f16, MVT::v4i16, MVT::v4bf16,
1069 MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::Other, MVT::f16,
1070 MVT::i16, MVT::bf16, MVT::i8, MVT::i128},
1071 Custom);
1072
1073 // The s_buffer_load intrinsics accept any result type in IR, but only a few
1074 // of them can be selected. Mark the remaining illegal result types Custom so
1075 // ReplaceNodeResults gets a chance to diagnose them instead of letting the
1076 // type legalizer abort. Its INTRINSIC_WO_CHAIN case dispatches on the
1077 // intrinsic ID, but INTRINSIC_W_CHAIN does not, so remember the types added
1078 // here to keep other chained intrinsics on generic legalization.
1079 for (MVT VT : MVT::all_valuetypes()) {
1080 if (VT.isScalableVector() || isTypeLegal(VT))
1081 continue;
1085 SBufferLoadDiagnosticVTs.set(VT.SimpleTy);
1086 }
1087 }
1088
1090 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v2bf16,
1091 MVT::v3i16, MVT::v3f16, MVT::v4f16, MVT::v4i16,
1092 MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
1093 MVT::f16, MVT::i16, MVT::bf16, MVT::i8, MVT::i128},
1094 Custom);
1095
1101
1102 // TODO: Could move this to custom lowering, could benefit from combines on
1103 // extract of relevant bits.
1105
1107
1108 if (Subtarget->hasBF16ConversionInsts()) {
1110 {MVT::bf16, MVT::v2bf16}, Custom);
1112 }
1113
1114 if (Subtarget->hasBF16TransInsts()) {
1116 }
1117
1118 const bool HasE5M3ConversionInsts =
1119 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
1120 if (Subtarget->hasOCPFP8ConversionInsts() || HasE5M3ConversionInsts) {
1121 setOperationAction(ISD::CONVERT_FROM_ARBITRARY_FP, {MVT::f32, MVT::v2f32},
1122 Custom);
1124
1125 // i8 result promotes to i16, wider vectors split down to v2i8, and v2i8 is
1126 // handled in ReplaceNodeResults before the legalizer splits it per lane.
1127 setOperationAction(ISD::CONVERT_TO_ARBITRARY_FP, {MVT::i16, MVT::v2i8},
1128 Custom);
1129 }
1130
1131 if (Subtarget->hasFP8F16ConversionInsts()) {
1132 setOperationAction(ISD::CONVERT_FROM_ARBITRARY_FP, {MVT::f16, MVT::v2f16},
1133 Custom);
1134 }
1135
1136 if (Subtarget->hasCvtPkF16F32Inst()) {
1138 {MVT::v2f16, MVT::v4f16, MVT::v8f16, MVT::v16f16},
1139 Custom);
1140 }
1141
1144 ISD::SUB,
1145 ISD::MUL,
1146 ISD::FADD,
1147 ISD::FSUB,
1148 ISD::FDIV,
1149 ISD::FMUL,
1158 ISD::FMA,
1159 ISD::ABS,
1160 ISD::SMIN,
1161 ISD::SMAX,
1162 ISD::UMIN,
1163 ISD::UMAX,
1164 ISD::SETCC,
1166 ISD::SMIN,
1167 ISD::SMAX,
1168 ISD::UMIN,
1169 ISD::UMAX,
1172 ISD::AND,
1173 ISD::OR,
1174 ISD::XOR,
1175 ISD::SHL,
1176 ISD::SRL,
1177 ISD::SRA,
1178 ISD::FSHR,
1190
1191 if (Subtarget->has16BitInsts() && !Subtarget->hasMed3_16())
1193
1194 // All memory operations. Some folding on the pointer operand is done to help
1195 // matching the constant offsets in the addressing modes.
1197 ISD::STORE,
1222
1223 // FIXME: In other contexts we pretend this is a per-function property.
1225
1227}
1228
1229const GCNSubtarget *SITargetLowering::getSubtarget() const { return Subtarget; }
1230
1232 static const MCPhysReg RCRegs[] = {AMDGPU::MODE};
1233 return RCRegs;
1234}
1235
1236//===----------------------------------------------------------------------===//
1237// TargetLowering queries
1238//===----------------------------------------------------------------------===//
1239
1240// v_mad_mix* support a conversion from f16 to f32.
1241//
1242// There is only one special case when denormals are enabled we don't currently,
1243// where this is OK to use.
1244bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
1245 EVT DestVT, EVT SrcVT) const {
1246 return DestVT.getScalarType() == MVT::f32 &&
1247 ((((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
1248 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
1249 SrcVT.getScalarType() == MVT::f16) ||
1250 (Opcode == ISD::FMA && Subtarget->hasFmaMixBF16Insts() &&
1251 SrcVT.getScalarType() == MVT::bf16)) &&
1252 // TODO: This probably only requires no input flushing?
1254}
1255
1257 LLT DestTy, LLT SrcTy) const {
1258 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
1259 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
1260 DestTy.getScalarSizeInBits() == 32 &&
1261 SrcTy.getScalarSizeInBits() == 16 &&
1262 // TODO: This probably only requires no input flushing?
1263 denormalModeIsFlushAllF32(*MI.getMF());
1264}
1265
1267 // SI has some legal vector types, but no legal vector operations. Say no
1268 // shuffles are legal in order to prefer scalarizing some vector operations.
1269 return false;
1270}
1271
1274 EVT VT) const {
1277
1278 if (VT.isVector()) {
1279 EVT ScalarVT = VT.getScalarType();
1280 unsigned Size = ScalarVT.getSizeInBits();
1281 if (Size == 16) {
1282 return Subtarget->has16BitInsts()
1283 ? MVT::getVectorVT(ScalarVT.getSimpleVT(), 2)
1284 : MVT::i32;
1285 }
1286
1287 if (Size < 16)
1288 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1289 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1290 }
1291
1292 if (!Subtarget->has16BitInsts() && VT.getSizeInBits() == 16)
1293 return MVT::i32;
1294
1295 if (VT.getSizeInBits() > 32)
1296 return MVT::i32;
1297
1299}
1300
1303 EVT VT) const {
1306
1307 if (VT.isVector()) {
1308 unsigned NumElts = VT.getVectorNumElements();
1309 EVT ScalarVT = VT.getScalarType();
1310 unsigned Size = ScalarVT.getSizeInBits();
1311
1312 // FIXME: Should probably promote 8-bit vectors to i16.
1313 if (Size == 16)
1314 return (NumElts + 1) / 2;
1315
1316 if (Size <= 32)
1317 return NumElts;
1318
1319 if (Size > 32)
1320 return NumElts * ((Size + 31) / 32);
1321 } else if (VT.getSizeInBits() > 32)
1322 return (VT.getSizeInBits() + 31) / 32;
1323
1325}
1326
1328 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1329 unsigned &NumIntermediates, MVT &RegisterVT) const {
1330 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1331 unsigned NumElts = VT.getVectorNumElements();
1332 EVT ScalarVT = VT.getScalarType();
1333 unsigned Size = ScalarVT.getSizeInBits();
1334 // FIXME: We should fix the ABI to be the same on targets without 16-bit
1335 // support, but unless we can properly handle 3-vectors, it will be still be
1336 // inconsistent.
1337 if (Size == 16) {
1338 MVT SimpleIntermediateVT =
1340 IntermediateVT = SimpleIntermediateVT;
1341 RegisterVT = Subtarget->has16BitInsts() ? SimpleIntermediateVT : MVT::i32;
1342 NumIntermediates = (NumElts + 1) / 2;
1343 return (NumElts + 1) / 2;
1344 }
1345
1346 if (Size == 32) {
1347 RegisterVT = ScalarVT.getSimpleVT();
1348 IntermediateVT = RegisterVT;
1349 NumIntermediates = NumElts;
1350 return NumIntermediates;
1351 }
1352
1353 if (Size < 16 && Subtarget->has16BitInsts()) {
1354 // FIXME: Should probably form v2i16 pieces
1355 RegisterVT = MVT::i16;
1356 IntermediateVT = ScalarVT;
1357 NumIntermediates = NumElts;
1358 return NumIntermediates;
1359 }
1360
1361 if (Size != 16 && Size <= 32) {
1362 RegisterVT = MVT::i32;
1363 IntermediateVT = ScalarVT;
1364 NumIntermediates = NumElts;
1365 return NumIntermediates;
1366 }
1367
1368 if (Size > 32) {
1369 RegisterVT = MVT::i32;
1370 IntermediateVT = RegisterVT;
1371 NumIntermediates = NumElts * ((Size + 31) / 32);
1372 return NumIntermediates;
1373 }
1374 }
1375
1377 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1378}
1379
1381 const DataLayout &DL, Type *Ty,
1382 unsigned MaxNumLanes) {
1383 assert(MaxNumLanes != 0);
1384
1385 LLVMContext &Ctx = Ty->getContext();
1386 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1387 unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
1388 return EVT::getVectorVT(Ctx, TLI.getValueType(DL, VT->getElementType()),
1389 NumElts);
1390 }
1391
1392 return TLI.getValueType(DL, Ty);
1393}
1394
1395// Peek through TFE struct returns to only use the data size.
1397 const DataLayout &DL, Type *Ty,
1398 unsigned MaxNumLanes) {
1399 auto *ST = dyn_cast<StructType>(Ty);
1400 if (!ST)
1401 return memVTFromLoadIntrData(TLI, DL, Ty, MaxNumLanes);
1402
1403 // TFE intrinsics return an aggregate type.
1404 assert(ST->getNumContainedTypes() == 2 &&
1405 ST->getContainedType(1)->isIntegerTy(32));
1406 return memVTFromLoadIntrData(TLI, DL, ST->getContainedType(0), MaxNumLanes);
1407}
1408
1409/// Map address space 7 to MVT::amdgpuBufferFatPointer because that's its
1410/// in-memory representation. This return value is a custom type because there
1411/// is no MVT::i160 and adding one breaks integer promotion logic. While this
1412/// could cause issues during codegen, these address space 7 pointers will be
1413/// rewritten away by then. Therefore, we can return MVT::amdgpuBufferFatPointer
1414/// in order to allow pre-codegen passes that query TargetTransformInfo, often
1415/// for cost modeling, to work. (This also sets us up decently for doing the
1416/// buffer lowering in GlobalISel if SelectionDAG ever goes away.)
1418 if (AMDGPUAS::BUFFER_FAT_POINTER == AS && DL.getPointerSizeInBits(AS) == 160)
1419 return MVT::amdgpuBufferFatPointer;
1421 DL.getPointerSizeInBits(AS) == 192)
1422 return MVT::amdgpuBufferStridedPointer;
1424}
1425/// Similarly, the in-memory representation of a p7 is {p8, i32}, aka
1426/// v8i32 when padding is added.
1427/// The in-memory representation of a p9 is {p8, i32, i32}, which is
1428/// also v8i32 with padding.
1430 if ((AMDGPUAS::BUFFER_FAT_POINTER == AS &&
1431 DL.getPointerSizeInBits(AS) == 160) ||
1433 DL.getPointerSizeInBits(AS) == 192))
1434 return MVT::v8i32;
1436}
1437
1438static unsigned getIntrMemWidth(unsigned IntrID) {
1439 switch (IntrID) {
1440 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
1441 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
1442 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1443 return 8;
1444 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
1445 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
1446 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1447 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
1448 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
1449 case Intrinsic::amdgcn_flat_load_monitor_b32:
1450 case Intrinsic::amdgcn_global_load_monitor_b32:
1451 return 32;
1452 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
1453 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
1454 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1455 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
1456 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
1457 case Intrinsic::amdgcn_flat_load_monitor_b64:
1458 case Intrinsic::amdgcn_global_load_monitor_b64:
1459 return 64;
1460 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
1461 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128:
1462 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
1463 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
1464 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B:
1465 case Intrinsic::amdgcn_flat_load_monitor_b128:
1466 case Intrinsic::amdgcn_global_load_monitor_b128:
1467 return 128;
1468 default:
1469 llvm_unreachable("Unknown width");
1470 }
1471}
1472
1474 unsigned ArgIdx) {
1475 Value *OrderingArg = CI.getArgOperand(ArgIdx);
1476 unsigned Ord = cast<ConstantInt>(OrderingArg)->getZExtValue();
1477 switch (AtomicOrderingCABI(Ord)) {
1480 break;
1483 break;
1486 break;
1487 default:
1489 }
1490}
1491
1492static unsigned parseSyncscopeMDArg(const CallBase &CI, unsigned ArgIdx) {
1493 MDNode *ScopeMD = cast<MDNode>(
1494 cast<MetadataAsValue>(CI.getArgOperand(ArgIdx))->getMetadata());
1495 StringRef Scope = cast<MDString>(ScopeMD->getOperand(0))->getString();
1496 return CI.getContext().getOrInsertSyncScopeID(Scope);
1497}
1498
1500 const CallBase &CI,
1501 MachineFunction &MF,
1502 unsigned IntrID) const {
1504 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1506 if (CI.hasMetadata(LLVMContext::MD_nontemporal))
1508 Flags |= getTargetMMOFlags(CI);
1509
1510 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1512 AttributeSet Attr =
1514 MemoryEffects ME = Attr.getMemoryEffects();
1515 if (ME.doesNotAccessMemory())
1516 return;
1517
1518 const AMDGPU::BufferIntrinsicInfo *BufInfo =
1520 bool IsSPrefetch = BufInfo && BufInfo->Kind == AMDGPU::BufferKindPrefetch;
1521 std::optional<unsigned> AuxArg =
1522 BufInfo ? BufInfo->getAuxArg() : CI.arg_size() - 1;
1523 if (AuxArg) {
1524 auto *Aux = cast<ConstantInt>(CI.getArgOperand(*AuxArg));
1525 if (Aux->getZExtValue() & AMDGPU::CPol::VOLATILE)
1527 }
1528
1530
1531 IntrinsicInfo Info;
1532 // TODO: Should images get their own address space?
1534
1535 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = nullptr;
1536 if (RsrcIntr->IsImage) {
1537 const AMDGPU::ImageDimIntrinsicInfo *Intr =
1539 BaseOpcode = AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1540 Info.align.reset();
1541 }
1542
1543 Value *RsrcArg = CI.getArgOperand(RsrcIntr->RsrcArg);
1544 if (auto *RsrcPtrTy = dyn_cast<PointerType>(RsrcArg->getType())) {
1545 if (RsrcPtrTy->getAddressSpace() == AMDGPUAS::BUFFER_RESOURCE)
1546 // We conservatively set the memory operand of a buffer intrinsic to the
1547 // base resource pointer, so that we can access alias information about
1548 // those pointers. Cases like "this points at the same value
1549 // but with a different offset" are handled in
1550 // areMemAccessesTriviallyDisjoint.
1551 Info.ptrVal = RsrcArg;
1552 }
1553
1554 if (ME.onlyReadsMemory()) {
1555 if (RsrcIntr->IsImage) {
1556 unsigned MaxNumLanes = 4;
1557
1558 if (!BaseOpcode->Gather4) {
1559 // If this isn't a gather, we may have excess loaded elements in the
1560 // IR type. Check the dmask for the real number of elements loaded.
1561 unsigned DMask =
1562 cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1563 MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1564 }
1565
1566 Info.memVT = memVTFromLoadIntrReturn(*this, MF.getDataLayout(),
1567 CI.getType(), MaxNumLanes);
1568 } else {
1569 Info.memVT =
1571 std::numeric_limits<unsigned>::max());
1572 }
1573
1574 // FIXME: What does alignment mean for an image?
1575 Info.opc = ISD::INTRINSIC_W_CHAIN;
1576 Info.flags = Flags | MachineMemOperand::MOLoad;
1577 } else if (ME.onlyWritesMemory()) {
1578 Info.opc = ISD::INTRINSIC_VOID;
1579
1580 Type *DataTy = CI.getArgOperand(0)->getType();
1581 if (RsrcIntr->IsImage) {
1582 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1583 unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1584 Info.memVT = memVTFromLoadIntrData(*this, MF.getDataLayout(), DataTy,
1585 DMaskLanes);
1586 } else
1587 Info.memVT = getValueType(MF.getDataLayout(), DataTy);
1588
1589 Info.flags = Flags | MachineMemOperand::MOStore;
1590 } else {
1591 // Atomic, NoReturn Sampler or prefetch
1592 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID
1594
1595 if (BufInfo && BufInfo->Kind == AMDGPU::BufferKindLoadToLDS) {
1596 unsigned Width =
1598 ->getZExtValue();
1599
1600 // Entry 0: Load from buffer.
1601 // Don't set an offset, since the pointer value always represents the
1602 // base of the buffer.
1603 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1604 Info.flags = Flags | MachineMemOperand::MOLoad;
1605 Infos.push_back(Info);
1606
1607 // Entry 1: Store to LDS.
1608 // Instruction offset is applied, and an additional per-lane offset
1609 // which we simulate using a larger memory type.
1610 Info.memVT = EVT::getIntegerVT(
1611 CI.getContext(), Width * 8 * Subtarget->getWavefrontSize());
1612 Info.ptrVal = CI.getArgOperand(*BufInfo->getLDSPtrArg());
1613 Info.offset =
1615 ->getZExtValue();
1616 Info.fallbackAddressSpace = AMDGPUAS::LOCAL_ADDRESS;
1617 Info.flags = Flags | MachineMemOperand::MOStore;
1618 Infos.push_back(Info);
1619 return;
1620 }
1621 if (BufInfo && BufInfo->Kind == AMDGPU::BufferKindAtomicLoad) {
1622 Info.memVT =
1624 std::numeric_limits<unsigned>::max());
1625 Info.flags = Flags | MachineMemOperand::MOLoad;
1626 Infos.push_back(Info);
1627 return;
1628 }
1629
1630 Info.flags = Flags | MachineMemOperand::MOLoad;
1631 if (!IsSPrefetch)
1632 Info.flags |= MachineMemOperand::MOStore;
1633
1634 if ((RsrcIntr->IsImage && BaseOpcode->NoReturn) || IsSPrefetch) {
1635 // Fake memory access type for no return sampler intrinsics
1636 Info.memVT = MVT::i32;
1637 } else {
1638 // XXX - Should this be volatile without known ordering?
1639 Info.flags |= MachineMemOperand::MOVolatile;
1640 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1641 }
1642 }
1643 Infos.push_back(Info);
1644 return;
1645 }
1646
1647 IntrinsicInfo Info;
1648 switch (IntrID) {
1649 case Intrinsic::amdgcn_ds_ordered_add:
1650 case Intrinsic::amdgcn_ds_ordered_swap: {
1651 Info.opc = ISD::INTRINSIC_W_CHAIN;
1652 Info.memVT = MVT::getVT(CI.getType());
1653 Info.ptrVal = CI.getOperand(0);
1654 Info.align.reset();
1656
1657 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1658 if (!Vol->isZero())
1659 Info.flags |= MachineMemOperand::MOVolatile;
1660
1661 Infos.push_back(Info);
1662 return;
1663 }
1664 case Intrinsic::amdgcn_ds_add_gs_reg_rtn:
1665 case Intrinsic::amdgcn_ds_sub_gs_reg_rtn: {
1666 Info.opc = ISD::INTRINSIC_W_CHAIN;
1667 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1668 Info.ptrVal = nullptr;
1669 Info.fallbackAddressSpace = AMDGPUAS::STREAMOUT_REGISTER;
1671 Infos.push_back(Info);
1672 return;
1673 }
1674 case Intrinsic::amdgcn_ds_append:
1675 case Intrinsic::amdgcn_ds_consume: {
1676 Info.opc = ISD::INTRINSIC_W_CHAIN;
1677 Info.memVT = MVT::getVT(CI.getType());
1678 Info.ptrVal = CI.getOperand(0);
1679 Info.align.reset();
1681
1682 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1683 if (!Vol->isZero())
1684 Info.flags |= MachineMemOperand::MOVolatile;
1685
1686 Infos.push_back(Info);
1687 return;
1688 }
1689 case Intrinsic::amdgcn_ds_atomic_async_barrier_arrive_b64:
1690 case Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64: {
1691 Info.opc = (IntrID == Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64)
1694 Info.memVT = MVT::getVT(CI.getType());
1695 Info.ptrVal = CI.getOperand(0);
1696 Info.memVT = MVT::i64;
1697 Info.size = 8;
1698 Info.align.reset();
1700 Info.order = AtomicOrdering::Monotonic;
1701 Infos.push_back(Info);
1702 return;
1703 }
1704 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
1705 case Intrinsic::amdgcn_image_bvh_intersect_ray:
1706 case Intrinsic::amdgcn_image_bvh8_intersect_ray: {
1707 Info.opc = ISD::INTRINSIC_W_CHAIN;
1708 Info.memVT =
1709 MVT::getVT(IntrID == Intrinsic::amdgcn_image_bvh_intersect_ray
1710 ? CI.getType()
1712 ->getElementType(0)); // XXX: what is correct VT?
1713
1714 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1715 Info.align.reset();
1716 Info.flags = Flags | MachineMemOperand::MOLoad |
1718 Infos.push_back(Info);
1719 return;
1720 }
1721 case Intrinsic::amdgcn_global_atomic_fmin_num:
1722 case Intrinsic::amdgcn_global_atomic_fmax_num:
1723 case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1724 case Intrinsic::amdgcn_flat_atomic_fmin_num:
1725 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
1726 Info.opc = ISD::INTRINSIC_W_CHAIN;
1727 Info.memVT = MVT::getVT(CI.getType());
1728 Info.ptrVal = CI.getOperand(0);
1729 Info.align.reset();
1730 Info.flags =
1733 Infos.push_back(Info);
1734 return;
1735 }
1736 case Intrinsic::amdgcn_cluster_load_b32:
1737 case Intrinsic::amdgcn_cluster_load_b64:
1738 case Intrinsic::amdgcn_cluster_load_b128:
1739 case Intrinsic::amdgcn_ds_load_tr6_b96:
1740 case Intrinsic::amdgcn_ds_load_tr4_b64:
1741 case Intrinsic::amdgcn_ds_load_tr8_b64:
1742 case Intrinsic::amdgcn_ds_load_tr16_b128:
1743 case Intrinsic::amdgcn_global_load_tr6_b96:
1744 case Intrinsic::amdgcn_global_load_tr4_b64:
1745 case Intrinsic::amdgcn_global_load_tr_b64:
1746 case Intrinsic::amdgcn_global_load_tr_b128:
1747 case Intrinsic::amdgcn_ds_read_tr4_b64:
1748 case Intrinsic::amdgcn_ds_read_tr6_b96:
1749 case Intrinsic::amdgcn_ds_read_tr8_b64:
1750 case Intrinsic::amdgcn_ds_read_tr16_b64: {
1751 Info.opc = ISD::INTRINSIC_W_CHAIN;
1752 Info.memVT = MVT::getVT(CI.getType());
1753 Info.ptrVal = CI.getOperand(0);
1754 Info.align.reset();
1755 Info.flags = Flags | MachineMemOperand::MOLoad;
1756 Infos.push_back(Info);
1757 return;
1758 }
1759 case Intrinsic::amdgcn_flat_load_monitor_b32:
1760 case Intrinsic::amdgcn_flat_load_monitor_b64:
1761 case Intrinsic::amdgcn_flat_load_monitor_b128:
1762 case Intrinsic::amdgcn_global_load_monitor_b32:
1763 case Intrinsic::amdgcn_global_load_monitor_b64:
1764 case Intrinsic::amdgcn_global_load_monitor_b128: {
1765 Info.opc = ISD::INTRINSIC_W_CHAIN;
1766 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1767 Info.ptrVal = CI.getOperand(0);
1768 Info.align.reset();
1769 Info.flags = MachineMemOperand::MOLoad;
1770 Info.order = parseAtomicOrderingCABIArg(CI, 1);
1771 Info.ssid = parseSyncscopeMDArg(CI, 2);
1772 Infos.push_back(Info);
1773 return;
1774 }
1775 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
1776 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
1777 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B: {
1778 Info.opc = ISD::INTRINSIC_W_CHAIN;
1779 Info.memVT = MVT::getVT(CI.getType());
1780 Info.ptrVal = CI.getOperand(0);
1781 Info.align.reset();
1783 Info.order = parseAtomicOrderingCABIArg(CI, 1);
1784 Info.ssid = parseSyncscopeMDArg(CI, 2);
1785 Infos.push_back(Info);
1786 return;
1787 }
1788 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
1789 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
1790 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
1791 Info.opc = ISD::INTRINSIC_VOID;
1792 Info.memVT = MVT::getVT(CI.getArgOperand(1)->getType());
1793 Info.ptrVal = CI.getArgOperand(0);
1794 Info.align.reset();
1796 Info.order = parseAtomicOrderingCABIArg(CI, 2);
1797 Info.ssid = parseSyncscopeMDArg(CI, 3);
1798 Infos.push_back(Info);
1799 return;
1800 }
1801 case Intrinsic::amdgcn_ds_gws_init:
1802 case Intrinsic::amdgcn_ds_gws_barrier:
1803 case Intrinsic::amdgcn_ds_gws_sema_v:
1804 case Intrinsic::amdgcn_ds_gws_sema_br:
1805 case Intrinsic::amdgcn_ds_gws_sema_p:
1806 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1807 Info.opc = ISD::INTRINSIC_VOID;
1808
1809 const GCNTargetMachine &TM =
1810 static_cast<const GCNTargetMachine &>(getTargetMachine());
1811
1813 Info.ptrVal = MFI->getGWSPSV(TM);
1814
1815 // This is an abstract access, but we need to specify a type and size.
1816 Info.memVT = MVT::i32;
1817 Info.size = 4;
1818 Info.align = Align(4);
1819
1820 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1821 Info.flags = Flags | MachineMemOperand::MOLoad;
1822 else
1823 Info.flags = Flags | MachineMemOperand::MOStore;
1824 Infos.push_back(Info);
1825 return;
1826 }
1827 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
1828 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
1829 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
1830 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
1831 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
1832 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
1833 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
1834 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128: {
1835 // Entry 0: Load from source (global/flat).
1836 Info.opc = ISD::INTRINSIC_VOID;
1837 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1838 Info.ptrVal = CI.getArgOperand(0); // Global pointer
1839 Info.offset = cast<ConstantInt>(CI.getArgOperand(2))->getSExtValue();
1840 Info.flags = Flags | MachineMemOperand::MOLoad;
1841 Infos.push_back(Info);
1842
1843 // Entry 1: Store to LDS (same offset).
1844 Info.flags = Flags | MachineMemOperand::MOStore;
1845 Info.ptrVal = CI.getArgOperand(1); // LDS pointer
1846 Infos.push_back(Info);
1847 return;
1848 }
1849 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1850 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1851 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1852 case Intrinsic::amdgcn_global_store_async_from_lds_b128: {
1853 // Entry 0: Load from LDS.
1854 Info.opc = ISD::INTRINSIC_VOID;
1855 Info.memVT = EVT::getIntegerVT(CI.getContext(), getIntrMemWidth(IntrID));
1856 Info.ptrVal = CI.getArgOperand(1); // LDS pointer
1857 Info.offset = cast<ConstantInt>(CI.getArgOperand(2))->getSExtValue();
1858 Info.flags = Flags | MachineMemOperand::MOLoad;
1859 Infos.push_back(Info);
1860
1861 // Entry 1: Store to global (same offset).
1862 Info.flags = Flags | MachineMemOperand::MOStore;
1863 Info.ptrVal = CI.getArgOperand(0); // Global pointer
1864 Infos.push_back(Info);
1865 return;
1866 }
1867 case Intrinsic::amdgcn_av_load_b8:
1868 case Intrinsic::amdgcn_av_load_b16:
1869 case Intrinsic::amdgcn_av_load_b32:
1870 case Intrinsic::amdgcn_av_load_b64:
1871 case Intrinsic::amdgcn_av_load_b128:
1872 case Intrinsic::amdgcn_av_store_b8:
1873 case Intrinsic::amdgcn_av_store_b16:
1874 case Intrinsic::amdgcn_av_store_b32:
1875 case Intrinsic::amdgcn_av_store_b64:
1876 case Intrinsic::amdgcn_av_store_b128: {
1877 bool IsStore = CI.getType()->isVoidTy();
1878 Type *DataTy = IsStore ? CI.getArgOperand(1)->getType() : CI.getType();
1879 Info.opc = IsStore ? ISD::INTRINSIC_VOID : ISD::INTRINSIC_W_CHAIN;
1880 Info.memVT = MVT::getVT(DataTy);
1881 Info.ptrVal = CI.getArgOperand(0);
1882 Info.align = Align(Info.memVT.getStoreSize());
1883 Info.flags |=
1885 Info.flags |= Flags & MachineMemOperand::MONonTemporal;
1886 // Pretend to be atomic so that SIMemoryLegalizer::expandStore sets cache
1887 // flags appropriately.
1888 Info.order = AtomicOrdering::Monotonic;
1889
1890 LLVMContext &Ctx = CI.getContext();
1891 unsigned ScopeIdx = CI.arg_size() - 1;
1892 MDNode *ScopeMD = cast<MDNode>(
1893 cast<MetadataAsValue>(CI.getArgOperand(ScopeIdx))->getMetadata());
1894 StringRef Scope = cast<MDString>(ScopeMD->getOperand(0))->getString();
1895 Info.ssid = Ctx.getOrInsertSyncScopeID(Scope);
1896 Infos.push_back(Info);
1897 return;
1898 }
1899 case Intrinsic::amdgcn_load_to_lds:
1900 case Intrinsic::amdgcn_load_async_to_lds:
1901 case Intrinsic::amdgcn_global_load_lds:
1902 case Intrinsic::amdgcn_global_load_async_lds: {
1903 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1904 auto *Aux = cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1));
1905 bool IsVolatile = Aux->getZExtValue() & AMDGPU::CPol::VOLATILE;
1906 if (IsVolatile)
1908
1909 // Entry 0: Load from source (global/flat).
1910 Info.opc = ISD::INTRINSIC_VOID;
1911 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1912 Info.ptrVal = CI.getArgOperand(0); // Source pointer
1913 Info.offset = cast<ConstantInt>(CI.getArgOperand(3))->getSExtValue();
1914 Info.flags = Flags | MachineMemOperand::MOLoad;
1915 Infos.push_back(Info);
1916
1917 // Entry 1: Store to LDS.
1918 // Same offset from the instruction, but an additional per-lane offset is
1919 // added. Represent that using a wider memory type.
1920 Info.memVT = EVT::getIntegerVT(CI.getContext(),
1921 Width * 8 * Subtarget->getWavefrontSize());
1922 Info.ptrVal = CI.getArgOperand(1); // LDS destination pointer
1923 Info.flags = Flags | MachineMemOperand::MOStore;
1924 Infos.push_back(Info);
1925 return;
1926 }
1927 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
1928 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
1929 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
1930 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn: {
1931 Info.opc = ISD::INTRINSIC_W_CHAIN;
1932
1933 const GCNTargetMachine &TM =
1934 static_cast<const GCNTargetMachine &>(getTargetMachine());
1935
1937 Info.ptrVal = MFI->getGWSPSV(TM);
1938
1939 // This is an abstract access, but we need to specify a type and size.
1940 Info.memVT = MVT::i32;
1941 Info.size = 4;
1942 Info.align = Align(4);
1943
1945 Infos.push_back(Info);
1946 return;
1947 }
1948 case Intrinsic::amdgcn_s_prefetch_data:
1949 case Intrinsic::amdgcn_s_prefetch_inst:
1950 case Intrinsic::amdgcn_flat_prefetch:
1951 case Intrinsic::amdgcn_global_prefetch: {
1952 Info.opc = ISD::INTRINSIC_VOID;
1953 Info.memVT = EVT::getIntegerVT(CI.getContext(), 8);
1954 Info.ptrVal = CI.getArgOperand(0);
1955 Info.flags = Flags | MachineMemOperand::MOLoad;
1956 Infos.push_back(Info);
1957 return;
1958 }
1959 default:
1960 return;
1961 }
1962}
1963
1966 Type *&AccessTy) const {
1967 Value *Ptr = nullptr;
1968 switch (II->getIntrinsicID()) {
1969 case Intrinsic::amdgcn_cluster_load_b128:
1970 case Intrinsic::amdgcn_cluster_load_b64:
1971 case Intrinsic::amdgcn_cluster_load_b32:
1972 case Intrinsic::amdgcn_ds_append:
1973 case Intrinsic::amdgcn_ds_consume:
1974 case Intrinsic::amdgcn_ds_load_tr8_b64:
1975 case Intrinsic::amdgcn_ds_load_tr16_b128:
1976 case Intrinsic::amdgcn_ds_load_tr4_b64:
1977 case Intrinsic::amdgcn_ds_load_tr6_b96:
1978 case Intrinsic::amdgcn_ds_read_tr4_b64:
1979 case Intrinsic::amdgcn_ds_read_tr6_b96:
1980 case Intrinsic::amdgcn_ds_read_tr8_b64:
1981 case Intrinsic::amdgcn_ds_read_tr16_b64:
1982 case Intrinsic::amdgcn_ds_ordered_add:
1983 case Intrinsic::amdgcn_ds_ordered_swap:
1984 case Intrinsic::amdgcn_ds_atomic_async_barrier_arrive_b64:
1985 case Intrinsic::amdgcn_ds_atomic_barrier_arrive_rtn_b64:
1986 case Intrinsic::amdgcn_flat_atomic_fmax_num:
1987 case Intrinsic::amdgcn_flat_atomic_fmin_num:
1988 case Intrinsic::amdgcn_global_atomic_fmax_num:
1989 case Intrinsic::amdgcn_global_atomic_fmin_num:
1990 case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1991 case Intrinsic::amdgcn_global_load_tr_b64:
1992 case Intrinsic::amdgcn_global_load_tr_b128:
1993 case Intrinsic::amdgcn_global_load_tr4_b64:
1994 case Intrinsic::amdgcn_global_load_tr6_b96:
1995 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
1996 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
1997 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
1998 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
1999 case Intrinsic::amdgcn_av_load_b8:
2000 case Intrinsic::amdgcn_av_load_b16:
2001 case Intrinsic::amdgcn_av_load_b32:
2002 case Intrinsic::amdgcn_av_load_b64:
2003 case Intrinsic::amdgcn_av_load_b128:
2004 case Intrinsic::amdgcn_av_store_b8:
2005 case Intrinsic::amdgcn_av_store_b16:
2006 case Intrinsic::amdgcn_av_store_b32:
2007 case Intrinsic::amdgcn_av_store_b64:
2008 case Intrinsic::amdgcn_av_store_b128:
2009 Ptr = II->getArgOperand(0);
2010 break;
2011 case Intrinsic::amdgcn_load_to_lds:
2012 case Intrinsic::amdgcn_load_async_to_lds:
2013 case Intrinsic::amdgcn_global_load_lds:
2014 case Intrinsic::amdgcn_global_load_async_lds:
2015 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
2016 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
2017 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
2018 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
2019 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
2020 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
2021 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
2022 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128:
2023 Ptr = II->getArgOperand(1);
2024 break;
2025 default:
2026 return false;
2027 }
2028 AccessTy = II->getType();
2029 Ops.push_back(Ptr);
2030 return true;
2031}
2032
2034 unsigned AddrSpace) const {
2035 if (!Subtarget->hasFlatInstOffsets()) {
2036 // Flat instructions do not have offsets, and only have the register
2037 // address.
2038 return AM.BaseOffs == 0 && AM.Scale == 0;
2039 }
2040
2042 FlatAddrSpace FlatVariant =
2043 AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ? FlatAddrSpace::FlatGlobal
2044 : AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ? FlatAddrSpace::FlatScratch
2045 : FlatAddrSpace::FLAT;
2046
2047 return AM.Scale == 0 &&
2048 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
2049 AM.BaseOffs, AddrSpace, FlatVariant));
2050}
2051
2053 if (Subtarget->hasFlatGlobalInsts())
2055
2056 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
2057 // Assume the we will use FLAT for all global memory accesses
2058 // on VI.
2059 // FIXME: This assumption is currently wrong. On VI we still use
2060 // MUBUF instructions for the r + i addressing mode. As currently
2061 // implemented, the MUBUF instructions only work on buffer < 4GB.
2062 // It may be possible to support > 4GB buffers with MUBUF instructions,
2063 // by setting the stride value in the resource descriptor which would
2064 // increase the size limit to (stride * 4GB). However, this is risky,
2065 // because it has never been validated.
2067 }
2068
2069 return isLegalMUBUFAddressingMode(AM);
2070}
2071
2072bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
2073 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
2074 // additionally can do r + r + i with addr64. 32-bit has more addressing
2075 // mode options. Depending on the resource constant, it can also do
2076 // (i64 r0) + (i32 r1) * (i14 i).
2077 //
2078 // Private arrays end up using a scratch buffer most of the time, so also
2079 // assume those use MUBUF instructions. Scratch loads / stores are currently
2080 // implemented as mubuf instructions with offen bit set, so slightly
2081 // different than the normal addr64.
2082 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2083 if (!TII->isLegalMUBUFImmOffset(AM.BaseOffs))
2084 return false;
2085
2086 // FIXME: Since we can split immediate into soffset and immediate offset,
2087 // would it make sense to allow any immediate?
2088
2089 switch (AM.Scale) {
2090 case 0: // r + i or just i, depending on HasBaseReg.
2091 return true;
2092 case 1:
2093 return true; // We have r + r or r + i.
2094 case 2:
2095 if (AM.HasBaseReg) {
2096 // Reject 2 * r + r.
2097 return false;
2098 }
2099
2100 // Allow 2 * r as r + r
2101 // Or 2 * r + i is allowed as r + r + i.
2102 return true;
2103 default: // Don't allow n * r
2104 return false;
2105 }
2106}
2107
2109 const AddrMode &AM, Type *Ty,
2110 unsigned AS,
2111 Instruction *I) const {
2112 // No global is ever allowed as a base.
2113 if (AM.BaseGV)
2114 return false;
2115
2116 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
2117 return isLegalGlobalAddressingMode(AM);
2118
2119 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
2123 // If the offset isn't a multiple of 4, it probably isn't going to be
2124 // correctly aligned.
2125 // FIXME: Can we get the real alignment here?
2126 if (AM.BaseOffs % 4 != 0)
2127 return isLegalMUBUFAddressingMode(AM);
2128
2129 if (!Subtarget->hasScalarSubwordLoads()) {
2130 // There are no SMRD extloads, so if we have to do a small type access we
2131 // will use a MUBUF load.
2132 // FIXME?: We also need to do this if unaligned, but we don't know the
2133 // alignment here.
2134 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
2135 return isLegalGlobalAddressingMode(AM);
2136 }
2137
2138 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
2139 // SMRD instructions have an 8-bit, dword offset on SI.
2140 if (!isUInt<8>(AM.BaseOffs / 4))
2141 return false;
2142 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
2143 // On CI+, this can also be a 32-bit literal constant offset. If it fits
2144 // in 8-bits, it can use a smaller encoding.
2145 if (!isUInt<32>(AM.BaseOffs / 4))
2146 return false;
2147 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX9) {
2148 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
2149 if (!isUInt<20>(AM.BaseOffs))
2150 return false;
2151 } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX12) {
2152 // On GFX9 the offset is signed 21-bit in bytes (but must not be negative
2153 // for S_BUFFER_* instructions).
2154 if (!isInt<21>(AM.BaseOffs))
2155 return false;
2156 } else {
2157 // On GFX12, all offsets are signed 24-bit in bytes.
2158 if (!isInt<24>(AM.BaseOffs))
2159 return false;
2160 }
2161
2162 if ((AS == AMDGPUAS::CONSTANT_ADDRESS ||
2164 AM.BaseOffs < 0) {
2165 // Scalar (non-buffer) loads can only use a negative offset if
2166 // soffset+offset is non-negative. Since the compiler can only prove that
2167 // in a few special cases, it is safer to claim that negative offsets are
2168 // not supported.
2169 return false;
2170 }
2171
2172 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
2173 return true;
2174
2175 if (AM.Scale == 1 && AM.HasBaseReg)
2176 return true;
2177
2178 return false;
2179 }
2180
2181 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
2182 return Subtarget->hasFlatScratchEnabled()
2184 : isLegalMUBUFAddressingMode(AM);
2185
2186 if (AS == AMDGPUAS::LOCAL_ADDRESS ||
2187 (AS == AMDGPUAS::REGION_ADDRESS && Subtarget->hasGDS())) {
2188 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
2189 // field.
2190 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
2191 // an 8-bit dword offset but we don't know the alignment here.
2192 if (!isUInt<16>(AM.BaseOffs))
2193 return false;
2194
2195 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
2196 return true;
2197
2198 if (AM.Scale == 1 && AM.HasBaseReg)
2199 return true;
2200
2201 return false;
2202 }
2203
2205 // For an unknown address space, this usually means that this is for some
2206 // reason being used for pure arithmetic, and not based on some addressing
2207 // computation. We don't have instructions that compute pointers with any
2208 // addressing modes, so treat them as having no offset like flat
2209 // instructions.
2211 }
2212
2213 // Assume a user alias of global for unknown address spaces.
2214 return isLegalGlobalAddressingMode(AM);
2215}
2216
2218 const MachineFunction &MF) const {
2220 return (MemVT.getSizeInBits() <= 4 * 32);
2221 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
2222 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
2223 return (MemVT.getSizeInBits() <= MaxPrivateBits);
2224 }
2226 return (MemVT.getSizeInBits() <= 2 * 32);
2227 return true;
2228}
2229
2231 unsigned Size, unsigned AddrSpace, Align Alignment,
2232 MachineMemOperand::Flags Flags, unsigned *IsFast) const {
2233 if (IsFast)
2234 *IsFast = 0;
2235
2236 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
2237 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
2238 // Check if alignment requirements for ds_read/write instructions are
2239 // disabled.
2240 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
2241 return false;
2242
2243 Align RequiredAlignment(
2244 PowerOf2Ceil(divideCeil(Size, 8))); // Natural alignment.
2245 if (Subtarget->hasLDSMisalignedBugInWGPMode() && Size > 32 &&
2246 Alignment < RequiredAlignment)
2247 return false;
2248
2249 // Either, the alignment requirements are "enabled", or there is an
2250 // unaligned LDS access related hardware bug though alignment requirements
2251 // are "disabled". In either case, we need to check for proper alignment
2252 // requirements.
2253 //
2254 switch (Size) {
2255 case 64:
2256 // SI has a hardware bug in the LDS / GDS bounds checking: if the base
2257 // address is negative, then the instruction is incorrectly treated as
2258 // out-of-bounds even if base + offsets is in bounds. Split vectorized
2259 // loads here to avoid emitting ds_read2_b32. We may re-combine the
2260 // load later in the SILoadStoreOptimizer.
2261 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
2262 return false;
2263
2264 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
2265 // can do a 4 byte aligned, 8 byte access in a single operation using
2266 // ds_read2/write2_b32 with adjacent offsets.
2267 RequiredAlignment = Align(4);
2268
2269 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2270 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
2271 // ds_write2_b32 depending on the alignment. In either case with either
2272 // alignment there is no faster way of doing this.
2273
2274 // The numbers returned here and below are not additive, it is a 'speed
2275 // rank'. They are just meant to be compared to decide if a certain way
2276 // of lowering an operation is faster than another. For that purpose
2277 // naturally aligned operation gets it bitsize to indicate that "it
2278 // operates with a speed comparable to N-bit wide load". With the full
2279 // alignment ds128 is slower than ds96 for example. If underaligned it
2280 // is comparable to a speed of a single dword access, which would then
2281 // mean 32 < 128 and it is faster to issue a wide load regardless.
2282 // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
2283 // wider load which will not be aligned anymore the latter is slower.
2284 if (IsFast)
2285 *IsFast = (Alignment >= RequiredAlignment) ? 64
2286 : (Alignment < Align(4)) ? 32
2287 : 1;
2288 return true;
2289 }
2290
2291 break;
2292 case 96:
2293 if (!Subtarget->hasDS96AndDS128())
2294 return false;
2295
2296 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
2297 // gfx8 and older.
2298
2299 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2300 // Naturally aligned access is fastest. However, also report it is Fast
2301 // if memory is aligned less than DWORD. A narrow load or store will be
2302 // be equally slow as a single ds_read_b96/ds_write_b96, but there will
2303 // be more of them, so overall we will pay less penalty issuing a single
2304 // instruction.
2305
2306 // See comment on the values above.
2307 if (IsFast)
2308 *IsFast = (Alignment >= RequiredAlignment) ? 96
2309 : (Alignment < Align(4)) ? 32
2310 : 1;
2311 return true;
2312 }
2313
2314 break;
2315 case 128:
2316 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
2317 return false;
2318
2319 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
2320 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
2321 // single operation using ds_read2/write2_b64.
2322 RequiredAlignment = Align(8);
2323
2324 if (Subtarget->hasUnalignedDSAccessEnabled()) {
2325 // Naturally aligned access is fastest. However, also report it is Fast
2326 // if memory is aligned less than DWORD. A narrow load or store will be
2327 // be equally slow as a single ds_read_b128/ds_write_b128, but there
2328 // will be more of them, so overall we will pay less penalty issuing a
2329 // single instruction.
2330
2331 // See comment on the values above.
2332 if (IsFast)
2333 *IsFast = (Alignment >= RequiredAlignment) ? 128
2334 : (Alignment < Align(4)) ? 32
2335 : 1;
2336 return true;
2337 }
2338
2339 break;
2340 default:
2341 if (Size > 32)
2342 return false;
2343
2344 break;
2345 }
2346
2347 // See comment on the values above.
2348 // Note that we have a single-dword or sub-dword here, so if underaligned
2349 // it is a slowest possible access, hence returned value is 0.
2350 if (IsFast)
2351 *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
2352
2353 return Alignment >= RequiredAlignment ||
2354 Subtarget->hasUnalignedDSAccessEnabled();
2355 }
2356
2357 // FIXME: We have to be conservative here and assume that flat operations
2358 // will access scratch. If we had access to the IR function, then we
2359 // could determine if any private memory was used in the function.
2360 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
2361 AddrSpace == AMDGPUAS::FLAT_ADDRESS) {
2362 bool AlignedBy4 = Alignment >= Align(4);
2363 if (Subtarget->hasUnalignedScratchAccessEnabled()) {
2364 if (IsFast)
2365 *IsFast = AlignedBy4 ? Size : 1;
2366 return true;
2367 }
2368
2369 if (IsFast)
2370 *IsFast = AlignedBy4;
2371
2372 return AlignedBy4;
2373 }
2374
2375 // So long as they are correct, wide global memory operations perform better
2376 // than multiple smaller memory ops -- even when misaligned
2377 if (AMDGPU::isExtendedGlobalAddrSpace(AddrSpace)) {
2378 if (IsFast)
2379 *IsFast = Size;
2380
2381 return Alignment >= Align(4) ||
2382 Subtarget->hasUnalignedBufferAccessEnabled();
2383 }
2384
2385 // Ensure robust out-of-bounds guarantees for buffer accesses are met when the
2386 // "amdgpu.buffer.oob.mode" module flag has not enabled relaxed untyped-buffer
2387 // OOB semantics. Normally hardware will ensure proper
2388 // out-of-bounds behavior, but in the edge case where an access starts
2389 // out-of-bounds and then enters in-bounds, the entire access would be treated
2390 // as out-of-bounds. Prevent misaligned memory accesses by requiring the
2391 // natural alignment of buffer accesses.
2392 if (AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER ||
2393 AddrSpace == AMDGPUAS::BUFFER_RESOURCE ||
2394 AddrSpace == AMDGPUAS::BUFFER_STRIDED_POINTER) {
2395 if (!Subtarget->hasRelaxedBufferOOBMode() &&
2396 Alignment < Align(PowerOf2Ceil(divideCeil(Size, 8))))
2397 return false;
2398 }
2399
2400 // Smaller than dword value must be aligned.
2401 if (Size < 32)
2402 return false;
2403
2404 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
2405 // byte-address are ignored, thus forcing Dword alignment.
2406 // This applies to private, global, and constant memory.
2407 if (IsFast)
2408 *IsFast = 1;
2409
2410 return Size >= 32 && Alignment >= Align(4);
2411}
2412
2414 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
2415 unsigned *IsFast) const {
2417 Alignment, Flags, IsFast);
2418}
2419
2421 const DataLayout &DL, EVT VT,
2422 unsigned AddrSpace, Align Alignment,
2424 unsigned *IsFast) const {
2425 // Sub-dword accesses aren't lowered yet, so combines must not narrow an
2426 // access to one.
2427 if (AddrSpace == AMDGPUAS::VGPR && VT.getSizeInBits() < 32)
2428 return false;
2429 return TargetLowering::allowsMemoryAccess(Context, DL, VT, AddrSpace,
2430 Alignment, Flags, IsFast);
2431}
2432
2434 LLVMContext &Context, const MemOp &Op,
2435 const AttributeList &FuncAttributes) const {
2436 // FIXME: Should account for address space here.
2437
2438 // The default fallback uses the private pointer size as a guess for a type to
2439 // use. Make sure we switch these to 64-bit accesses.
2440
2441 if (Op.size() >= 16 &&
2442 Op.isDstAligned(Align(4))) // XXX: Should only do for global
2443 return MVT::v4i32;
2444
2445 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
2446 return MVT::v2i32;
2447
2448 // Use the default.
2449 return MVT::Other;
2450}
2451
2453 const MemSDNode *MemNode = cast<MemSDNode>(N);
2454 return MemNode->getMemOperand()->getFlags() & MONoClobber;
2455}
2456
2461
2463 unsigned DestAS) const {
2464 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
2465 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
2466 Subtarget->hasGloballyAddressableScratch()) {
2467 // Flat -> private requires subtracting src_flat_scratch_base_lo.
2468 return false;
2469 }
2470
2471 // Flat -> private/local is a simple truncate.
2472 // Flat -> global is no-op
2473 return true;
2474 }
2475
2476 const GCNTargetMachine &TM =
2477 static_cast<const GCNTargetMachine &>(getTargetMachine());
2478 return TM.isNoopAddrSpaceCast(DL, SrcAS, DestAS);
2479}
2480
2488
2490 Type *Ty) const {
2491 // FIXME: Could be smarter if called for vector constants.
2492 return true;
2493}
2494
2497 unsigned Index) const {
2500
2501 // TODO: Add more cases that are cheap.
2502 if (Index == 0)
2505}
2506
2507bool SITargetLowering::isExtractVecEltCheap(EVT VT, unsigned Index) const {
2508 // TODO: This should be more aggressive, particular for 16-bit element
2509 // vectors. However there are some mixed improvements and regressions.
2510 EVT EltTy = VT.getVectorElementType();
2511 unsigned MinAlign = Subtarget->useRealTrue16Insts() ? 16 : 32;
2512 return EltTy.getSizeInBits() % MinAlign == 0;
2513}
2514
2516 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
2517 switch (Op) {
2518 case ISD::LOAD:
2519 case ISD::STORE:
2520 return true;
2521 default:
2522 return false;
2523 }
2524 }
2525
2526 // SimplifySetCC uses this function to determine whether or not it should
2527 // create setcc with i1 operands. We don't have instructions for i1 setcc.
2528 if (VT == MVT::i1 && Op == ISD::SETCC)
2529 return false;
2530
2531 if (VT.getScalarType() == MVT::i64 &&
2533 return false;
2534
2535 // The DAGCombiner replaces a conversion from i1 with a select of the two
2536 // exact results. The select avoids an f32 conversion plus rounding for
2537 // f16/bf16, a 64-bit conversion for f64 and a missing libcall for f128, and
2538 // is the same single v_cndmask for f32.
2539 if (VT == MVT::i1 && (Op == ISD::SINT_TO_FP || Op == ISD::UINT_TO_FP))
2540 return false;
2541
2543}
2544
2546 // Do not convert uniform loads to 16-bit.
2547 // Uniform 16-bit loads are legalized to i16 = trunc (zextload i16->i32)
2548 // to match subword load patterns. Allowing conversion back to a 16-bit
2549 // load would create an infinite loop.
2550 if (Subtarget->hasScalarSubwordLoads() && N->getOpcode() == ISD::LOAD &&
2551 !VT.isVector() && VT.getSizeInBits() == 16) {
2552 auto *Load = dyn_cast<LoadSDNode>(N);
2553 if (Load && isUniformLoad(Load)) {
2554 return false;
2555 }
2556 }
2557
2558 return isTypeDesirableForOp(N->getOpcode(), VT);
2559}
2560
2562 const MachineMemOperand *MMO = Load->getMemOperand();
2563
2564 // FIXME: We ought to able able to take the direct isDivergent result. We
2565 // cannot rely on the MMO for a uniformity check, and should stop using
2566 // it. This is a hack for 2 ways that the IR divergence analysis is superior
2567 // to the DAG divergence: Recognizing shift-of-workitem-id as always
2568 // uniform, and isSingleLaneExecution. These should be handled in the DAG
2569 // version, and then this can be dropped.
2570 if (Load->isDivergent() && !AMDGPU::isUniformMMO(MMO))
2571 return false;
2572
2573 return MMO->getSize().hasValue() &&
2574 Load->getAlign() >=
2575 Align(std::min(MMO->getSize().getValue().getKnownMinValue(),
2576 uint64_t(4))) &&
2577 (MMO->isInvariant() ||
2578 (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
2579 Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ||
2580 (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
2581 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load)));
2582}
2583
2586 // This isn't really a constant pool but close enough.
2589 return PtrInfo;
2590}
2591
2592SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
2593 const SDLoc &SL,
2594 SDValue Chain,
2595 uint64_t Offset) const {
2596 const DataLayout &DL = DAG.getDataLayout();
2600
2601 auto [InputPtrReg, RC, ArgTy] =
2602 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
2603
2604 // We may not have the kernarg segment argument if we have no kernel
2605 // arguments.
2606 if (!InputPtrReg)
2607 return DAG.getConstant(Offset, SL, PtrVT);
2608
2610 SDValue BasePtr = DAG.getCopyFromReg(
2611 Chain, SL, MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
2612
2613 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Offset));
2614}
2615
2616SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
2617 const SDLoc &SL) const {
2620 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
2621}
2622
2623SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
2624 const SDLoc &SL) const {
2625
2627 std::optional<uint32_t> KnownSize =
2629 if (KnownSize.has_value())
2630 return DAG.getConstant(*KnownSize, SL, MVT::i32);
2631 return SDValue();
2632}
2633
2634SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
2635 const SDLoc &SL, SDValue Val,
2636 bool Signed,
2637 const ISD::InputArg *Arg) const {
2638 // First, if it is a widened vector, narrow it.
2639 if (VT.isVector() &&
2641 EVT NarrowedVT =
2644 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
2645 DAG.getConstant(0, SL, MVT::i32));
2646 }
2647
2648 // Then convert the vector elements or scalar value.
2649 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && VT.bitsLT(MemVT)) {
2650 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
2651 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
2652 }
2653
2654 if (MemVT.isFloatingPoint()) {
2655 if (VT.isFloatingPoint()) {
2656 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
2657 } else {
2658 assert(!MemVT.isVector());
2659 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
2660 SDValue Cast = DAG.getBitcast(IntVT, Val);
2661 Val = DAG.getAnyExtOrTrunc(Cast, SL, VT);
2662 }
2663 } else if (Signed)
2664 Val = DAG.getSExtOrTrunc(Val, SL, VT);
2665 else
2666 Val = DAG.getZExtOrTrunc(Val, SL, VT);
2667
2668 return Val;
2669}
2670
2671SDValue SITargetLowering::lowerKernargMemParameter(
2672 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
2673 uint64_t Offset, Align Alignment, bool Signed,
2674 const ISD::InputArg *Arg) const {
2675
2676 MachinePointerInfo PtrInfo =
2678
2679 // Try to avoid using an extload by loading earlier than the argument address,
2680 // and extracting the relevant bits. The load should hopefully be merged with
2681 // the previous argument.
2682 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
2683 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
2684 int64_t AlignDownOffset = alignDown(Offset, 4);
2685 int64_t OffsetDiff = Offset - AlignDownOffset;
2686
2687 EVT IntVT = MemVT.changeTypeToInteger();
2688
2689 // TODO: If we passed in the base kernel offset we could have a better
2690 // alignment than 4, but we don't really need it.
2691 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
2692 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr,
2693 PtrInfo.getWithOffset(AlignDownOffset), Align(4),
2696
2697 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
2698 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
2699
2700 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
2701 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
2702 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
2703
2704 return DAG.getMergeValues({ArgVal, Load.getValue(1)}, SL);
2705 }
2706
2707 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
2708 SDValue Load = DAG.getLoad(
2709 MemVT, SL, Chain, Ptr, PtrInfo.getWithOffset(Offset), Alignment,
2711
2712 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
2713 return DAG.getMergeValues({Val, Load.getValue(1)}, SL);
2714}
2715
2716/// Coerce an argument which was passed in a different ABI type to the original
2717/// expected value type.
2718SDValue SITargetLowering::convertABITypeToValueType(SelectionDAG &DAG,
2719 SDValue Val,
2720 CCValAssign &VA,
2721 const SDLoc &SL) const {
2722 EVT ValVT = VA.getValVT();
2723
2724 // If this is an 8 or 16-bit value, it is really passed promoted
2725 // to 32 bits. Insert an assert[sz]ext to capture this, then
2726 // truncate to the right size.
2727 switch (VA.getLocInfo()) {
2728 case CCValAssign::Full:
2729 return Val;
2730 case CCValAssign::BCvt:
2731 return DAG.getNode(ISD::BITCAST, SL, ValVT, Val);
2732 case CCValAssign::SExt:
2733 Val = DAG.getNode(ISD::AssertSext, SL, VA.getLocVT(), Val,
2734 DAG.getValueType(ValVT));
2735 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2736 case CCValAssign::ZExt:
2737 Val = DAG.getNode(ISD::AssertZext, SL, VA.getLocVT(), Val,
2738 DAG.getValueType(ValVT));
2739 return DAG.getNode(ISD::TRUNCATE, SL, ValVT, Val);
2740 case CCValAssign::AExt:
2741 Val = DAG.getNode(ISD::TRUNCATE, SL, ValVT.changeTypeToInteger(), Val);
2742 return DAG.getBitcast(ValVT, Val);
2743 default:
2744 llvm_unreachable("Unknown loc info!");
2745 }
2746}
2747
2748SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG,
2749 CCValAssign &VA, const SDLoc &SL,
2750 SDValue Chain,
2751 const ISD::InputArg &Arg) const {
2753 MachineFrameInfo &MFI = MF.getFrameInfo();
2754
2755 if (Arg.Flags.isByVal()) {
2756 unsigned Size = Arg.Flags.getByValSize();
2757 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
2758 return DAG.getFrameIndex(FrameIdx, MVT::i32);
2759 }
2760
2761 unsigned ArgOffset = VA.getLocMemOffset();
2762 unsigned ArgSize = VA.getValVT().getStoreSize();
2763
2764 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
2765
2766 // Create load nodes to retrieve arguments from the stack.
2767 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2768 MachinePointerInfo PtrInfo =
2770 if (VA.getLocInfo() == CCValAssign::AExt)
2771 return DAG.getLoad(VA.getValVT(), SL, Chain, FIN, PtrInfo);
2772
2773 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2775 MVT MemVT = VA.getValVT();
2776
2777 switch (VA.getLocInfo()) {
2778 default:
2779 break;
2780 case CCValAssign::BCvt:
2781 MemVT = VA.getLocVT();
2782 break;
2783 case CCValAssign::SExt:
2784 ExtType = ISD::SEXTLOAD;
2785 break;
2786 case CCValAssign::ZExt:
2787 ExtType = ISD::ZEXTLOAD;
2788 break;
2789 }
2790
2791 SDValue ArgValue =
2792 DAG.getExtLoad(ExtType, SL, VA.getLocVT(), Chain, FIN, PtrInfo, MemVT);
2793
2794 SDValue ConvertedVal = convertABITypeToValueType(DAG, ArgValue, VA, SL);
2795 if (ConvertedVal == ArgValue)
2796 return ConvertedVal;
2797
2798 return DAG.getMergeValues({ConvertedVal, ArgValue.getValue(1)}, SL);
2799}
2800
2801// Read the cluster ID field of IB_STS2. It is 0 if and only if clusters are
2802// disabled.
2803static SDValue readClusterIdField(SelectionDAG &DAG, const SDLoc &SL, EVT VT) {
2804 using namespace AMDGPU::Hwreg;
2805 SDValue ClusterIdField =
2806 DAG.getTargetConstant(HwregEncoding::encode(ID_IB_STS2, 6, 4), SL, VT);
2807 SDNode *GetReg =
2808 DAG.getMachineNode(AMDGPU::S_GETREG_B32_const, SL, VT, ClusterIdField);
2809 return SDValue(GetReg, 0);
2810}
2811
2812SDValue SITargetLowering::lowerWorkGroupId(
2813 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2816 AMDGPUFunctionArgInfo::PreloadedValue ClusterWorkGroupIdPV) const {
2817 if (!Subtarget->hasClusters())
2818 return getPreloadedValue(DAG, MFI, VT, WorkGroupIdPV);
2819
2820 // Clusters are supported. Return the global position in the grid. If clusters
2821 // are enabled, WorkGroupIdPV returns the cluster ID not the workgroup ID.
2822
2823 // WorkGroupIdXYZ = ClusterId == 0 ?
2824 // ClusterIdXYZ :
2825 // ClusterIdXYZ * (ClusterMaxIdXYZ + 1) + ClusterWorkGroupIdXYZ
2826 SDValue ClusterIdXYZ = getPreloadedValue(DAG, MFI, VT, WorkGroupIdPV);
2827 SDLoc SL(ClusterIdXYZ);
2828 SDValue ClusterMaxIdXYZ = getPreloadedValue(DAG, MFI, VT, ClusterMaxIdPV);
2829 SDValue One = DAG.getConstant(1, SL, VT);
2830 SDValue ClusterSizeXYZ = DAG.getNode(ISD::ADD, SL, VT, ClusterMaxIdXYZ, One);
2831 SDValue ClusterWorkGroupIdXYZ =
2832 getPreloadedValue(DAG, MFI, VT, ClusterWorkGroupIdPV);
2833 SDValue GlobalIdXYZ =
2834 DAG.getNode(ISD::ADD, SL, VT, ClusterWorkGroupIdXYZ,
2835 DAG.getNode(ISD::MUL, SL, VT, ClusterIdXYZ, ClusterSizeXYZ));
2836
2837 switch (MFI.getClusterDims().getKind()) {
2840 return GlobalIdXYZ;
2842 return ClusterIdXYZ;
2844 SDValue ClusterId = readClusterIdField(DAG, SL, VT);
2845 SDValue Zero = DAG.getConstant(0, SL, VT);
2846 return DAG.getNode(ISD::SELECT_CC, SL, VT, ClusterId, Zero, ClusterIdXYZ,
2847 GlobalIdXYZ, DAG.getCondCode(ISD::SETEQ));
2848 }
2849 }
2850
2851 llvm_unreachable("nothing should reach here");
2852}
2853
2854SDValue SITargetLowering::lowerClusterWorkGroupValue(
2855 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2857 if (!Subtarget->hasClusters())
2858 return DAG.getPOISON(VT);
2859
2860 // TTMP6 holds these values only if cluster is enabled. The programming model
2861 // treats a launch without clusters as an implicit 1x1x1 cluster, so all of
2862 // these values are 0.
2863 switch (MFI.getClusterDims().getKind()) {
2866 return getPreloadedValue(DAG, MFI, VT, PV);
2868 return DAG.getConstant(0, SDLoc(), VT);
2870 SDValue Value = getPreloadedValue(DAG, MFI, VT, PV);
2871 SDLoc SL(Value);
2872 SDValue ClusterId = readClusterIdField(DAG, SL, VT);
2873 SDValue Zero = DAG.getConstant(0, SL, VT);
2874 return DAG.getNode(ISD::SELECT_CC, SL, VT, ClusterId, Zero, Zero, Value,
2875 DAG.getCondCode(ISD::SETEQ));
2876 }
2877 }
2878
2879 llvm_unreachable("nothing should reach here");
2880}
2881
2882SDValue SITargetLowering::getPreloadedValue(
2883 SelectionDAG &DAG, const SIMachineFunctionInfo &MFI, EVT VT,
2885 const ArgDescriptor *Reg = nullptr;
2886 const TargetRegisterClass *RC = nullptr;
2887 LLT Ty;
2888
2890 const ArgDescriptor WorkGroupIDX =
2891 ArgDescriptor::createRegister(AMDGPU::TTMP9);
2892 // If GridZ is not programmed in an entry function then the hardware will set
2893 // it to all zeros, so there is no need to mask the GridY value in the low
2894 // order bits.
2895 const ArgDescriptor WorkGroupIDY = ArgDescriptor::createRegister(
2896 AMDGPU::TTMP7,
2897 AMDGPU::isEntryFunctionCC(CC) && !MFI.hasWorkGroupIDZ() ? ~0u : 0xFFFFu);
2898 const ArgDescriptor WorkGroupIDZ =
2899 ArgDescriptor::createRegister(AMDGPU::TTMP7, 0xFFFF0000u);
2900 const ArgDescriptor ClusterWorkGroupIDX =
2901 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000000Fu);
2902 const ArgDescriptor ClusterWorkGroupIDY =
2903 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000000F0u);
2904 const ArgDescriptor ClusterWorkGroupIDZ =
2905 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00000F00u);
2906 const ArgDescriptor ClusterWorkGroupMaxIDX =
2907 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0000F000u);
2908 const ArgDescriptor ClusterWorkGroupMaxIDY =
2909 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x000F0000u);
2910 const ArgDescriptor ClusterWorkGroupMaxIDZ =
2911 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x00F00000u);
2912 const ArgDescriptor ClusterWorkGroupMaxFlatID =
2913 ArgDescriptor::createRegister(AMDGPU::TTMP6, 0x0F000000u);
2914
2915 auto LoadConstant = [&](unsigned N) {
2916 return DAG.getConstant(N, SDLoc(), VT);
2917 };
2918
2919 if (Subtarget->hasArchitectedSGPRs() &&
2922 AMDGPU::ClusterDimsAttr ClusterDims = MFI.getClusterDims();
2923 bool HasFixedDims = ClusterDims.isFixedDims();
2924
2925 switch (PVID) {
2927 Reg = &WorkGroupIDX;
2928 RC = &AMDGPU::SReg_32RegClass;
2929 Ty = LLT::scalar(32);
2930 break;
2932 Reg = &WorkGroupIDY;
2933 RC = &AMDGPU::SReg_32RegClass;
2934 Ty = LLT::scalar(32);
2935 break;
2937 Reg = &WorkGroupIDZ;
2938 RC = &AMDGPU::SReg_32RegClass;
2939 Ty = LLT::scalar(32);
2940 break;
2942 if (HasFixedDims && ClusterDims.getDims()[0] == 1)
2943 return LoadConstant(0);
2944 Reg = &ClusterWorkGroupIDX;
2945 RC = &AMDGPU::SReg_32RegClass;
2946 Ty = LLT::scalar(32);
2947 break;
2949 if (HasFixedDims && ClusterDims.getDims()[1] == 1)
2950 return LoadConstant(0);
2951 Reg = &ClusterWorkGroupIDY;
2952 RC = &AMDGPU::SReg_32RegClass;
2953 Ty = LLT::scalar(32);
2954 break;
2956 if (HasFixedDims && ClusterDims.getDims()[2] == 1)
2957 return LoadConstant(0);
2958 Reg = &ClusterWorkGroupIDZ;
2959 RC = &AMDGPU::SReg_32RegClass;
2960 Ty = LLT::scalar(32);
2961 break;
2963 if (HasFixedDims)
2964 return LoadConstant(ClusterDims.getDims()[0] - 1);
2965 Reg = &ClusterWorkGroupMaxIDX;
2966 RC = &AMDGPU::SReg_32RegClass;
2967 Ty = LLT::scalar(32);
2968 break;
2970 if (HasFixedDims)
2971 return LoadConstant(ClusterDims.getDims()[1] - 1);
2972 Reg = &ClusterWorkGroupMaxIDY;
2973 RC = &AMDGPU::SReg_32RegClass;
2974 Ty = LLT::scalar(32);
2975 break;
2977 if (HasFixedDims)
2978 return LoadConstant(ClusterDims.getDims()[2] - 1);
2979 Reg = &ClusterWorkGroupMaxIDZ;
2980 RC = &AMDGPU::SReg_32RegClass;
2981 Ty = LLT::scalar(32);
2982 break;
2984 if (HasFixedDims) {
2985 const std::array<unsigned, 3> &Dims = ClusterDims.getDims();
2986 return LoadConstant(Dims[0] * Dims[1] * Dims[2] - 1);
2987 }
2988 Reg = &ClusterWorkGroupMaxFlatID;
2989 RC = &AMDGPU::SReg_32RegClass;
2990 Ty = LLT::scalar(32);
2991 break;
2992 default:
2993 break;
2994 }
2995 }
2996
2997 if (!Reg)
2998 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
2999 if (!Reg) {
3001 // It's possible for a kernarg intrinsic call to appear in a kernel with
3002 // no allocated segment, in which case we do not add the user sgpr
3003 // argument, so just return null.
3004 return DAG.getConstant(0, SDLoc(), VT);
3005 }
3006
3007 // It's undefined behavior if a function marked with the amdgpu-no-*
3008 // attributes uses the corresponding intrinsic.
3009 return DAG.getPOISON(VT);
3010 }
3011
3012 return loadInputValue(DAG, RC, VT, SDLoc(DAG.getEntryNode()), *Reg);
3013}
3014
3016 CallingConv::ID CallConv,
3017 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
3018 FunctionType *FType,
3019 SIMachineFunctionInfo *Info) {
3020 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
3021 const ISD::InputArg *Arg = &Ins[I];
3022
3023 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
3024 "vector type argument should have been split");
3025
3026 // First check if it's a PS input addr.
3027 if (CallConv == CallingConv::AMDGPU_PS && !Arg->Flags.isInReg() &&
3028 PSInputNum <= 15) {
3029 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
3030
3031 // Inconveniently only the first part of the split is marked as isSplit,
3032 // so skip to the end. We only want to increment PSInputNum once for the
3033 // entire split argument.
3034 if (Arg->Flags.isSplit()) {
3035 while (!Arg->Flags.isSplitEnd()) {
3036 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
3037 "unexpected vector split in ps argument type");
3038 if (!SkipArg)
3039 Splits.push_back(*Arg);
3040 Arg = &Ins[++I];
3041 }
3042 }
3043
3044 if (SkipArg) {
3045 // We can safely skip PS inputs.
3046 Skipped.set(Arg->getOrigArgIndex());
3047 ++PSInputNum;
3048 continue;
3049 }
3050
3051 Info->markPSInputAllocated(PSInputNum);
3052 if (Arg->Used)
3053 Info->markPSInputEnabled(PSInputNum);
3054
3055 ++PSInputNum;
3056 }
3057
3058 Splits.push_back(*Arg);
3059 }
3060}
3061
3062// Allocate special inputs passed in VGPRs.
3064 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3065 SIMachineFunctionInfo &Info) const {
3066 const LLT I32 = LLT::integer(32);
3068
3069 if (Info.hasWorkItemIDX()) {
3070 Register Reg = AMDGPU::VGPR0;
3071 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3072
3073 CCInfo.AllocateReg(Reg);
3074 unsigned Mask =
3075 (Subtarget->hasPackedTID() && Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
3076 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
3077 }
3078
3079 if (Info.hasWorkItemIDY()) {
3080 assert(Info.hasWorkItemIDX());
3081 if (Subtarget->hasPackedTID()) {
3082 Info.setWorkItemIDY(
3083 ArgDescriptor::createRegister(AMDGPU::VGPR0, 0x3ff << 10));
3084 } else {
3085 unsigned Reg = AMDGPU::VGPR1;
3086 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3087
3088 CCInfo.AllocateReg(Reg);
3089 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
3090 }
3091 }
3092
3093 if (Info.hasWorkItemIDZ()) {
3094 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
3095 if (Subtarget->hasPackedTID()) {
3096 Info.setWorkItemIDZ(
3097 ArgDescriptor::createRegister(AMDGPU::VGPR0, 0x3ff << 20));
3098 } else {
3099 unsigned Reg = AMDGPU::VGPR2;
3100 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), I32);
3101
3102 CCInfo.AllocateReg(Reg);
3103 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
3104 }
3105 }
3106}
3107
3109 const TargetRegisterClass *RC,
3110 unsigned NumArgRegs) {
3111 ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
3112 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
3113 if (RegIdx == ArgSGPRs.size())
3114 report_fatal_error("ran out of SGPRs for arguments");
3115
3116 unsigned Reg = ArgSGPRs[RegIdx];
3117 Reg = CCInfo.AllocateReg(Reg);
3118 assert(Reg != AMDGPU::NoRegister);
3119
3120 MachineFunction &MF = CCInfo.getMachineFunction();
3121 MF.addLiveIn(Reg, RC);
3123}
3124
3125// If this has a fixed position, we still should allocate the register in the
3126// CCInfo state. Technically we could get away with this for values passed
3127// outside of the normal argument range.
3129 const TargetRegisterClass *RC,
3130 MCRegister Reg) {
3131 Reg = CCInfo.AllocateReg(Reg);
3132 assert(Reg != AMDGPU::NoRegister);
3133 MachineFunction &MF = CCInfo.getMachineFunction();
3134 MF.addLiveIn(Reg, RC);
3135}
3136
3137static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
3138 if (Arg) {
3139 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
3140 Arg.getRegister());
3141 } else
3142 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
3143}
3144
3145static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
3146 if (Arg) {
3147 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
3148 Arg.getRegister());
3149 } else
3150 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
3151}
3152
3153/// Allocate implicit function VGPR arguments in fixed registers.
3155 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3156 SIMachineFunctionInfo &Info) const {
3157 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
3158 if (!Reg)
3159 report_fatal_error("failed to allocate VGPR for implicit arguments");
3160
3161 const unsigned Mask = 0x3ff;
3162 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
3163 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
3164 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
3165}
3166
3168 CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI,
3169 SIMachineFunctionInfo &Info) const {
3170 auto &ArgInfo = Info.getArgInfo();
3171 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
3172
3173 // TODO: Unify handling with private memory pointers.
3174 if (UserSGPRInfo.hasDispatchPtr())
3175 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
3176
3177 if (UserSGPRInfo.hasQueuePtr())
3178 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
3179
3180 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
3181 // constant offset from the kernarg segment.
3182 if (Info.hasImplicitArgPtr())
3183 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
3184
3185 if (UserSGPRInfo.hasDispatchID())
3186 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
3187
3188 // flat_scratch_init is not applicable for non-kernel functions.
3189
3190 if (Info.hasWorkGroupIDX())
3191 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
3192
3193 if (Info.hasWorkGroupIDY())
3194 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
3195
3196 if (Info.hasWorkGroupIDZ())
3197 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
3198
3199 if (Info.hasLDSKernelId())
3200 allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
3201}
3202
3203// Allocate special inputs passed in user SGPRs.
3205 MachineFunction &MF,
3206 const SIRegisterInfo &TRI,
3207 SIMachineFunctionInfo &Info) const {
3208 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
3209 if (UserSGPRInfo.hasImplicitBufferPtr()) {
3210 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
3211 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
3212 CCInfo.AllocateReg(ImplicitBufferPtrReg);
3213 }
3214
3215 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
3216 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
3217 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
3218 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
3219 CCInfo.AllocateReg(PrivateSegmentBufferReg);
3220 }
3221
3222 if (UserSGPRInfo.hasDispatchPtr()) {
3223 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
3224 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
3225 CCInfo.AllocateReg(DispatchPtrReg);
3226 }
3227
3228 if (UserSGPRInfo.hasQueuePtr()) {
3229 Register QueuePtrReg = Info.addQueuePtr(TRI);
3230 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
3231 CCInfo.AllocateReg(QueuePtrReg);
3232 }
3233
3234 if (UserSGPRInfo.hasKernargSegmentPtr()) {
3236 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
3237 CCInfo.AllocateReg(InputPtrReg);
3238
3239 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
3240 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
3241 }
3242
3243 if (UserSGPRInfo.hasDispatchID()) {
3244 Register DispatchIDReg = Info.addDispatchID(TRI);
3245 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
3246 CCInfo.AllocateReg(DispatchIDReg);
3247 }
3248
3249 if (UserSGPRInfo.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
3250 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
3251 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
3252 CCInfo.AllocateReg(FlatScratchInitReg);
3253 }
3254
3255 if (UserSGPRInfo.hasPrivateSegmentSize()) {
3256 Register PrivateSegmentSizeReg = Info.addPrivateSegmentSize(TRI);
3257 MF.addLiveIn(PrivateSegmentSizeReg, &AMDGPU::SGPR_32RegClass);
3258 CCInfo.AllocateReg(PrivateSegmentSizeReg);
3259 }
3260
3261 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
3262 // these from the dispatch pointer.
3263}
3264
3265// Allocate pre-loaded kernel arguemtns. Arguments to be preloading must be
3266// sequential starting from the first argument.
3268 CCState &CCInfo, SmallVectorImpl<CCValAssign> &ArgLocs,
3270 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
3271 Function &F = MF.getFunction();
3272 unsigned LastExplicitArgOffset = Subtarget->getExplicitKernelArgOffset();
3273 GCNUserSGPRUsageInfo &SGPRInfo = Info.getUserSGPRInfo();
3274 bool InPreloadSequence = true;
3275 unsigned InIdx = 0;
3276 bool AlignedForImplictArgs = false;
3277 unsigned ImplicitArgOffset = 0;
3278 for (auto &Arg : F.args()) {
3279 if (!InPreloadSequence || !Arg.hasInRegAttr())
3280 break;
3281
3282 unsigned ArgIdx = Arg.getArgNo();
3283 // Don't preload non-original args or parts not in the current preload
3284 // sequence.
3285 if (InIdx < Ins.size() &&
3286 (!Ins[InIdx].isOrigArg() || Ins[InIdx].getOrigArgIndex() != ArgIdx))
3287 break;
3288
3289 for (; InIdx < Ins.size() && Ins[InIdx].isOrigArg() &&
3290 Ins[InIdx].getOrigArgIndex() == ArgIdx;
3291 InIdx++) {
3292 assert(ArgLocs[ArgIdx].isMemLoc());
3293 auto &ArgLoc = ArgLocs[InIdx];
3294 const Align KernelArgBaseAlign = Align(16);
3295 unsigned ArgOffset = ArgLoc.getLocMemOffset();
3296 Align Alignment = commonAlignment(KernelArgBaseAlign, ArgOffset);
3297 unsigned NumAllocSGPRs =
3298 alignTo(ArgLoc.getLocVT().getFixedSizeInBits(), 32) / 32;
3299
3300 // Fix alignment for hidden arguments.
3301 if (Arg.hasAttribute("amdgpu-hidden-argument")) {
3302 if (!AlignedForImplictArgs) {
3303 ImplicitArgOffset =
3304 alignTo(LastExplicitArgOffset,
3305 Subtarget->getAlignmentForImplicitArgPtr()) -
3306 LastExplicitArgOffset;
3307 AlignedForImplictArgs = true;
3308 }
3309 ArgOffset += ImplicitArgOffset;
3310 }
3311
3312 // Arg is preloaded into the previous SGPR.
3313 if (ArgLoc.getLocVT().getStoreSize() < 4 && Alignment < 4) {
3314 assert(InIdx >= 1 && "No previous SGPR");
3315 Info.getArgInfo().PreloadKernArgs[InIdx].Regs.push_back(
3316 Info.getArgInfo().PreloadKernArgs[InIdx - 1].Regs[0]);
3317 continue;
3318 }
3319
3320 unsigned Padding = ArgOffset - LastExplicitArgOffset;
3321 unsigned PaddingSGPRs = alignTo(Padding, 4) / 4;
3322 // Check for free user SGPRs for preloading.
3323 if (PaddingSGPRs + NumAllocSGPRs > SGPRInfo.getNumFreeUserSGPRs()) {
3324 InPreloadSequence = false;
3325 break;
3326 }
3327
3328 // Preload this argument.
3329 const TargetRegisterClass *RC =
3330 TRI.getSGPRClassForBitWidth(NumAllocSGPRs * 32);
3331 SmallVectorImpl<MCRegister> *PreloadRegs =
3332 Info.addPreloadedKernArg(TRI, RC, NumAllocSGPRs, InIdx, PaddingSGPRs);
3333
3334 if (PreloadRegs->size() > 1)
3335 RC = &AMDGPU::SGPR_32RegClass;
3336 for (auto &Reg : *PreloadRegs) {
3337 assert(Reg);
3338 MF.addLiveIn(Reg, RC);
3339 CCInfo.AllocateReg(Reg);
3340 }
3341
3342 LastExplicitArgOffset = NumAllocSGPRs * 4 + ArgOffset;
3343 }
3344 }
3345}
3346
3348 const SIRegisterInfo &TRI,
3349 SIMachineFunctionInfo &Info) const {
3350 // Always allocate this last since it is a synthetic preload.
3351 if (Info.hasLDSKernelId()) {
3352 Register Reg = Info.addLDSKernelId();
3353 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3354 CCInfo.AllocateReg(Reg);
3355 }
3356}
3357
3358// Allocate special input registers that are initialized per-wave.
3361 CallingConv::ID CallConv,
3362 bool IsShader) const {
3363 bool HasArchitectedSGPRs = Subtarget->hasArchitectedSGPRs();
3364 if (Subtarget->hasUserSGPRInit16BugInWave32() && !IsShader) {
3365 // Note: user SGPRs are handled by the front-end for graphics shaders
3366 // Pad up the used user SGPRs with dead inputs.
3367
3368 // TODO: NumRequiredSystemSGPRs computation should be adjusted appropriately
3369 // before enabling architected SGPRs for workgroup IDs.
3370 assert(!HasArchitectedSGPRs && "Unhandled feature for the subtarget");
3371
3372 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
3373 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
3374 // rely on it to reach 16 since if we end up having no stack usage, it will
3375 // not really be added.
3376 unsigned NumRequiredSystemSGPRs =
3377 Info.hasWorkGroupIDX() + Info.hasWorkGroupIDY() +
3378 Info.hasWorkGroupIDZ() + Info.hasWorkGroupInfo();
3379 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
3380 Register Reg = Info.addReservedUserSGPR();
3381 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3382 CCInfo.AllocateReg(Reg);
3383 }
3384 }
3385
3386 if (!HasArchitectedSGPRs) {
3387 if (Info.hasWorkGroupIDX()) {
3388 Register Reg = Info.addWorkGroupIDX();
3389 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3390 CCInfo.AllocateReg(Reg);
3391 }
3392
3393 if (Info.hasWorkGroupIDY()) {
3394 Register Reg = Info.addWorkGroupIDY();
3395 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3396 CCInfo.AllocateReg(Reg);
3397 }
3398
3399 if (Info.hasWorkGroupIDZ()) {
3400 Register Reg = Info.addWorkGroupIDZ();
3401 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3402 CCInfo.AllocateReg(Reg);
3403 }
3404 }
3405
3406 if (Info.hasWorkGroupInfo()) {
3407 Register Reg = Info.addWorkGroupInfo();
3408 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
3409 CCInfo.AllocateReg(Reg);
3410 }
3411
3412 if (Info.hasPrivateSegmentWaveByteOffset()) {
3413 // Scratch wave offset passed in system SGPR.
3414 unsigned PrivateSegmentWaveByteOffsetReg;
3415
3416 if (IsShader) {
3417 PrivateSegmentWaveByteOffsetReg =
3418 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
3419
3420 // This is true if the scratch wave byte offset doesn't have a fixed
3421 // location.
3422 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
3423 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
3424 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
3425 }
3426 } else
3427 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
3428
3429 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
3430 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
3431 }
3432
3433 assert(!Subtarget->hasUserSGPRInit16BugInWave32() || IsShader ||
3434 Info.getNumPreloadedSGPRs() >= 16);
3435}
3436
3438 MachineFunction &MF,
3439 const SIRegisterInfo &TRI,
3440 SIMachineFunctionInfo &Info) {
3441 // Now that we've figured out where the scratch register inputs are, see if
3442 // should reserve the arguments and use them directly.
3443 MachineFrameInfo &MFI = MF.getFrameInfo();
3444 bool HasStackObjects = MFI.hasStackObjects();
3445 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3446
3447 // Record that we know we have non-spill stack objects so we don't need to
3448 // check all stack objects later.
3449 if (HasStackObjects)
3450 Info.setHasNonSpillStackObjects(true);
3451
3452 // Everything live out of a block is spilled with fast regalloc, so it's
3453 // almost certain that spilling will be required.
3455 HasStackObjects = true;
3456
3457 // For now assume stack access is needed in any callee functions, so we need
3458 // the scratch registers to pass in.
3459 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
3460
3461 if (!ST.hasFlatScratchEnabled()) {
3462 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
3463 // If we have stack objects, we unquestionably need the private buffer
3464 // resource. For the Code Object V2 ABI, this will be the first 4 user
3465 // SGPR inputs. We can reserve those and use them directly.
3466
3467 Register PrivateSegmentBufferReg =
3469 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
3470 } else {
3471 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
3472 // We tentatively reserve the last registers (skipping the last registers
3473 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
3474 // we'll replace these with the ones immediately after those which were
3475 // really allocated. In the prologue copies will be inserted from the
3476 // argument to these reserved registers.
3477
3478 // Without HSA, relocations are used for the scratch pointer and the
3479 // buffer resource setup is always inserted in the prologue. Scratch wave
3480 // offset is still in an input SGPR.
3481 Info.setScratchRSrcReg(ReservedBufferReg);
3482 }
3483 }
3484
3486
3487 // For entry functions we have to set up the stack pointer if we use it,
3488 // whereas non-entry functions get this "for free". This means there is no
3489 // intrinsic advantage to using S32 over S34 in cases where we do not have
3490 // calls but do need a frame pointer (i.e. if we are requested to have one
3491 // because frame pointer elimination is disabled). To keep things simple we
3492 // only ever use S32 as the call ABI stack pointer, and so using it does not
3493 // imply we need a separate frame pointer.
3494 //
3495 // Try to use s32 as the SP, but move it if it would interfere with input
3496 // arguments. This won't work with calls though.
3497 //
3498 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
3499 // registers.
3500 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
3501 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
3502 } else {
3504
3505 if (MFI.hasCalls())
3506 report_fatal_error("call in graphics shader with too many input SGPRs");
3507
3508 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
3509 if (!MRI.isLiveIn(Reg)) {
3510 Info.setStackPtrOffsetReg(Reg);
3511 break;
3512 }
3513 }
3514
3515 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
3516 report_fatal_error("failed to find register for SP");
3517 }
3518
3519 // hasFP should be accurate for entry functions even before the frame is
3520 // finalized, because it does not rely on the known stack size, only
3521 // properties like whether variable sized objects are present.
3522 if (ST.getFrameLowering()->hasFP(MF)) {
3523 Info.setFrameOffsetReg(AMDGPU::SGPR33);
3524 }
3525}
3526
3529 return !Info->isEntryFunction();
3530}
3531
3533
3535 MachineBasicBlock *Entry,
3536 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3538
3539 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
3540 if (!IStart)
3541 return;
3542
3543 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3544 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
3545 MachineBasicBlock::iterator MBBI = Entry->begin();
3546 for (const MCPhysReg *I = IStart; *I; ++I) {
3547 const TargetRegisterClass *RC = nullptr;
3548 if (AMDGPU::SReg_64RegClass.contains(*I))
3549 RC = &AMDGPU::SGPR_64RegClass;
3550 else if (AMDGPU::SReg_32RegClass.contains(*I))
3551 RC = &AMDGPU::SGPR_32RegClass;
3552 else
3553 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3554
3555 Register NewVR = MRI->createVirtualRegister(RC);
3556 // Create copy from CSR to a virtual register.
3557 Entry->addLiveIn(*I);
3558 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
3559 .addReg(*I);
3560
3561 // Insert the copy-back instructions right before the terminator.
3562 for (auto *Exit : Exits)
3563 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
3564 TII->get(TargetOpcode::COPY), *I)
3565 .addReg(NewVR);
3566 }
3567}
3568
3570 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3571 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3572 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3574
3576 const Function &Fn = MF.getFunction();
3579 bool IsError = false;
3580
3581 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
3583 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()));
3584 IsError = true;
3585 }
3586
3589 BitVector Skipped(Fn.arg_size());
3590 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3591 *DAG.getContext());
3592
3593 bool IsGraphics = AMDGPU::isGraphics(CallConv);
3594 bool IsKernel = AMDGPU::isKernel(CallConv);
3595 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
3596
3597 if (IsGraphics) {
3598 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();
3599 assert(!UserSGPRInfo.hasDispatchPtr() &&
3600 !UserSGPRInfo.hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() &&
3601 !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
3602 !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
3603 (void)UserSGPRInfo;
3604 if (!Subtarget->hasFlatScratchEnabled())
3605 assert(!UserSGPRInfo.hasFlatScratchInit());
3606 if ((CallConv != CallingConv::AMDGPU_CS &&
3607 CallConv != CallingConv::AMDGPU_Gfx &&
3608 CallConv != CallingConv::AMDGPU_Gfx_WholeWave) ||
3609 !Subtarget->hasArchitectedSGPRs())
3610 assert(!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
3611 !Info->hasWorkGroupIDZ());
3612 }
3613
3614 bool IsWholeWaveFunc = Info->isWholeWaveFunction();
3615
3616 if (CallConv == CallingConv::AMDGPU_PS) {
3617 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
3618
3619 // At least one interpolation mode must be enabled or else the GPU will
3620 // hang.
3621 //
3622 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
3623 // set PSInputAddr, the user wants to enable some bits after the compilation
3624 // based on run-time states. Since we can't know what the final PSInputEna
3625 // will look like, so we shouldn't do anything here and the user should take
3626 // responsibility for the correct programming.
3627 //
3628 // Otherwise, the following restrictions apply:
3629 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
3630 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
3631 // enabled too.
3632 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
3633 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
3634 CCInfo.AllocateReg(AMDGPU::VGPR0);
3635 CCInfo.AllocateReg(AMDGPU::VGPR1);
3636 Info->markPSInputAllocated(0);
3637 Info->markPSInputEnabled(0);
3638 }
3639 if (Subtarget->isAmdPalOS()) {
3640 // For isAmdPalOS, the user does not enable some bits after compilation
3641 // based on run-time states; the register values being generated here are
3642 // the final ones set in hardware. Therefore we need to apply the
3643 // workaround to PSInputAddr and PSInputEnable together. (The case where
3644 // a bit is set in PSInputAddr but not PSInputEnable is where the
3645 // frontend set up an input arg for a particular interpolation mode, but
3646 // nothing uses that input arg. Really we should have an earlier pass
3647 // that removes such an arg.)
3648 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
3649 if ((PsInputBits & 0x7F) == 0 ||
3650 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
3651 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
3652 }
3653 } else if (IsKernel) {
3654 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
3655 } else {
3656 Splits.append(IsWholeWaveFunc ? std::next(Ins.begin()) : Ins.begin(),
3657 Ins.end());
3658 }
3659
3660 if (IsKernel)
3661 analyzeFormalArgumentsCompute(CCInfo, Ins);
3662
3663 if (IsEntryFunc) {
3664 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
3665 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
3666 if (IsKernel && Subtarget->hasKernargPreload())
3667 allocatePreloadKernArgSGPRs(CCInfo, ArgLocs, Ins, MF, *TRI, *Info);
3668
3669 allocateLDSKernelId(CCInfo, MF, *TRI, *Info);
3670 } else if (!IsGraphics) {
3671 // For the fixed ABI, pass workitem IDs in the last argument register.
3672 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
3673
3674 // FIXME: Sink this into allocateSpecialInputSGPRs
3675 if (!Subtarget->hasFlatScratchEnabled())
3676 CCInfo.AllocateReg(Info->getScratchRSrcReg());
3677
3678 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
3679 }
3680
3681 if (!IsKernel) {
3682 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
3683 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
3684
3685 // This assumes the registers are allocated by CCInfo in ascending order
3686 // with no gaps.
3687 Info->setNumWaveDispatchSGPRs(
3688 CCInfo.getFirstUnallocated(AMDGPU::SGPR_32RegClass.getRegisters()));
3689 Info->setNumWaveDispatchVGPRs(
3690 CCInfo.getFirstUnallocated(AMDGPU::VGPR_32RegClass.getRegisters()));
3691 } else if (Info->getNumKernargPreloadedSGPRs()) {
3692 Info->setNumWaveDispatchSGPRs(Info->getNumUserSGPRs());
3693 }
3694
3696
3697 if (IsWholeWaveFunc) {
3698 SDValue Setup = DAG.getNode(AMDGPUISD::WHOLE_WAVE_SETUP, DL,
3699 {MVT::i1, MVT::Other}, Chain);
3700 InVals.push_back(Setup.getValue(0));
3701 Chains.push_back(Setup.getValue(1));
3702 }
3703
3704 // FIXME: This is the minimum kernel argument alignment. We should improve
3705 // this to the maximum alignment of the arguments.
3706 //
3707 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
3708 // kern arg offset.
3709 const Align KernelArgBaseAlign = Align(16);
3710
3711 for (unsigned i = IsWholeWaveFunc ? 1 : 0, e = Ins.size(), ArgIdx = 0; i != e;
3712 ++i) {
3713 const ISD::InputArg &Arg = Ins[i];
3714 if ((Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) || IsError) {
3715 InVals.push_back(DAG.getPOISON(Arg.VT));
3716 continue;
3717 }
3718
3719 CCValAssign &VA = ArgLocs[ArgIdx++];
3720 MVT VT = VA.getLocVT();
3721
3722 if (IsEntryFunc && VA.isMemLoc()) {
3723 VT = Ins[i].VT;
3724 EVT MemVT = VA.getLocVT();
3725
3726 const uint64_t Offset = VA.getLocMemOffset();
3727 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
3728
3729 if (Arg.Flags.isByRef()) {
3730 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
3731
3732 const GCNTargetMachine &TM =
3733 static_cast<const GCNTargetMachine &>(getTargetMachine());
3734 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(),
3736 Arg.Flags.getPointerAddrSpace())) {
3739 }
3740
3741 InVals.push_back(Ptr);
3742 continue;
3743 }
3744
3745 SDValue NewArg;
3746 if (Arg.isOrigArg() && Info->getArgInfo().PreloadKernArgs.count(i)) {
3747 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
3748 // In this case the argument is packed into the previous preload SGPR.
3749 int64_t AlignDownOffset = alignDown(Offset, 4);
3750 int64_t OffsetDiff = Offset - AlignDownOffset;
3751 EVT IntVT = MemVT.changeTypeToInteger();
3752
3753 const SIMachineFunctionInfo *Info =
3756 Register Reg =
3757 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs[0];
3758
3759 assert(Reg);
3760 Register VReg = MRI.getLiveInVirtReg(Reg);
3761 SDValue Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
3762
3763 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, DL, MVT::i32);
3764 SDValue Extract = DAG.getNode(ISD::SRL, DL, MVT::i32, Copy, ShiftAmt);
3765
3766 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Extract);
3767 ArgVal = DAG.getNode(ISD::BITCAST, DL, MemVT, ArgVal);
3768 NewArg = convertArgType(DAG, VT, MemVT, DL, ArgVal,
3769 Ins[i].Flags.isSExt(), &Ins[i]);
3770
3771 NewArg = DAG.getMergeValues({NewArg, Copy.getValue(1)}, DL);
3772 } else {
3773 const SIMachineFunctionInfo *Info =
3776 const SmallVectorImpl<MCRegister> &PreloadRegs =
3777 Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs;
3778
3779 SDValue Copy;
3780 if (PreloadRegs.size() == 1) {
3781 Register VReg = MRI.getLiveInVirtReg(PreloadRegs[0]);
3782 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
3783 NewArg = DAG.getCopyFromReg(
3784 Chain, DL, VReg,
3786 TRI->getRegSizeInBits(*RC)));
3787
3788 } else {
3789 // If the kernarg alignment does not match the alignment of the SGPR
3790 // tuple RC that can accommodate this argument, it will be built up
3791 // via copies from from the individual SGPRs that the argument was
3792 // preloaded to.
3794 for (auto Reg : PreloadRegs) {
3795 Register VReg = MRI.getLiveInVirtReg(Reg);
3796 Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
3797 Elts.push_back(Copy);
3798 }
3799 NewArg =
3800 DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3801 PreloadRegs.size()),
3802 DL, Elts);
3803 }
3804
3805 // If the argument was preloaded to multiple consecutive 32-bit
3806 // registers because of misalignment between addressable SGPR tuples
3807 // and the argument size, we can still assume that because of kernarg
3808 // segment alignment restrictions that NewArg's size is the same as
3809 // MemVT and just do a bitcast. If MemVT is less than 32-bits we add a
3810 // truncate since we cannot preload to less than a single SGPR and the
3811 // MemVT may be smaller.
3812 EVT MemVTInt =
3814 if (MemVT.bitsLT(NewArg.getSimpleValueType()))
3815 NewArg = DAG.getNode(ISD::TRUNCATE, DL, MemVTInt, NewArg);
3816
3817 NewArg = DAG.getBitcast(MemVT, NewArg);
3818 NewArg = convertArgType(DAG, VT, MemVT, DL, NewArg,
3819 Ins[i].Flags.isSExt(), &Ins[i]);
3820 NewArg = DAG.getMergeValues({NewArg, Chain}, DL);
3821 }
3822 } else {
3823 // Hidden arguments that are in the kernel signature must be preloaded
3824 // to user SGPRs. Print a diagnostic error if a hidden argument is in
3825 // the argument list and is not preloaded.
3826 if (Arg.isOrigArg()) {
3827 Argument *OrigArg = Fn.getArg(Arg.getOrigArgIndex());
3828 if (OrigArg->hasAttribute("amdgpu-hidden-argument")) {
3830 *OrigArg->getParent(),
3831 "hidden argument in kernel signature was not preloaded",
3832 DL.getDebugLoc()));
3833 }
3834 }
3835
3836 NewArg =
3837 lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset,
3838 Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
3839 }
3840 Chains.push_back(NewArg.getValue(1));
3841
3842 auto *ParamTy =
3843 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
3844 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
3845 ParamTy &&
3846 (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
3847 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
3848 // On SI local pointers are just offsets into LDS, so they are always
3849 // less than 16-bits. On CI and newer they could potentially be
3850 // real pointers, so we can't guarantee their size.
3851 NewArg = DAG.getNode(ISD::AssertZext, DL, NewArg.getValueType(), NewArg,
3852 DAG.getValueType(MVT::i16));
3853 }
3854
3855 InVals.push_back(NewArg);
3856 continue;
3857 }
3858 if (!IsEntryFunc && VA.isMemLoc()) {
3859 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
3860 InVals.push_back(Val);
3861 if (!Arg.Flags.isByVal())
3862 Chains.push_back(Val.getValue(1));
3863 continue;
3864 }
3865
3866 assert(VA.isRegLoc() && "Parameter must be in a register!");
3867
3868 Register Reg = VA.getLocReg();
3869 const TargetRegisterClass *RC = nullptr;
3870 if (AMDGPU::VGPR_32RegClass.contains(Reg))
3871 RC = &AMDGPU::VGPR_32RegClass;
3872 else if (AMDGPU::SGPR_32RegClass.contains(Reg))
3873 RC = &AMDGPU::SGPR_32RegClass;
3874 else
3875 llvm_unreachable("Unexpected register class in LowerFormalArguments!");
3876
3877 Reg = MF.addLiveIn(Reg, RC);
3878 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
3879 if (Arg.Flags.isInReg() && RC == &AMDGPU::VGPR_32RegClass) {
3880 // FIXME: Need to forward the chains created by `CopyFromReg`s, make sure
3881 // they will read physical regs before any side effect instructions.
3882 SDValue ReadFirstLane =
3883 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
3885 ReadFirstLane, Val);
3886 }
3887
3888 if (Arg.Flags.isSRet()) {
3889 // The return object should be reasonably addressable.
3890 Val = annotateStackObjectPointer(Val, DAG, DL,
3892 }
3893
3894 Val = convertABITypeToValueType(DAG, Val, VA, DL);
3895 InVals.push_back(Val);
3896 }
3897
3898 // Start adding system SGPRs.
3899 if (IsEntryFunc)
3900 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
3901
3902 unsigned StackArgSize = CCInfo.getStackSize();
3903 Info->setBytesInStackArgArea(StackArgSize);
3904
3905 return Chains.empty() ? Chain
3906 : DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3907}
3908
3909// TODO: If return values can't fit in registers, we should return as many as
3910// possible in registers before passing on stack.
3912 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
3914 const Type *RetTy) const {
3915 // Replacing returns with sret/stack usage doesn't make sense for shaders.
3916 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
3917 // for shaders. Vector types should be explicitly handled by CC.
3918 if (AMDGPU::isEntryFunctionCC(CallConv))
3919 return true;
3920
3922 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3923 if (!CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)))
3924 return false;
3925
3926 // We must use the stack if return would require unavailable registers.
3927 unsigned MaxNumVGPRs = Subtarget->getMaxNumVGPRs(MF);
3928 unsigned TotalNumVGPRs = Subtarget->getAddressableNumArchVGPRs();
3929 for (unsigned i = MaxNumVGPRs; i < TotalNumVGPRs; ++i)
3930 if (CCInfo.isAllocated(AMDGPU::VGPR_32RegClass.getRegister(i)))
3931 return false;
3932
3933 return true;
3934}
3935
3936SDValue
3938 bool isVarArg,
3940 const SmallVectorImpl<SDValue> &OutVals,
3941 const SDLoc &DL, SelectionDAG &DAG) const {
3945
3946 if (AMDGPU::isKernel(CallConv)) {
3947 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
3948 OutVals, DL, DAG);
3949 }
3950
3951 bool IsShader = AMDGPU::isShader(CallConv);
3952
3953 Info->setIfReturnsVoid(Outs.empty());
3954 bool IsWaveEnd = Info->returnsVoid() && IsShader;
3955
3956 // CCValAssign - represent the assignment of the return value to a location.
3958
3959 // CCState - Info about the registers and stack slots.
3960 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3961 *DAG.getContext());
3962
3963 // Analyze outgoing return values.
3964 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3965
3966 SDValue Glue;
3968 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3969
3970 SDValue ReadFirstLane =
3971 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
3972 // Copy the result values into the output registers.
3973 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
3974 ++I, ++RealRVLocIdx) {
3975 CCValAssign &VA = RVLocs[I];
3976 assert(VA.isRegLoc() && "Can only return in registers!");
3977 // TODO: Partially return in registers if return values don't fit.
3978 SDValue Arg = OutVals[RealRVLocIdx];
3979
3980 // Copied from other backends.
3981 switch (VA.getLocInfo()) {
3982 case CCValAssign::Full:
3983 break;
3984 case CCValAssign::BCvt:
3985 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3986 break;
3987 case CCValAssign::SExt:
3988 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3989 break;
3990 case CCValAssign::ZExt:
3991 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3992 break;
3993 case CCValAssign::AExt:
3994 Arg = DAG.getBitcast(VA.getValVT().changeTypeToInteger(), Arg);
3995 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3996 break;
3997 default:
3998 llvm_unreachable("Unknown loc info!");
3999 }
4000 if (TRI->isSGPRPhysReg(VA.getLocReg()))
4002 ReadFirstLane, Arg);
4003 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Glue);
4004 Glue = Chain.getValue(1);
4005 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4006 }
4007
4008 // FIXME: Does sret work properly?
4009 if (!Info->isEntryFunction()) {
4010 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4011 const MCPhysReg *I =
4012 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4013 if (I) {
4014 for (; *I; ++I) {
4015 if (AMDGPU::SReg_64RegClass.contains(*I))
4016 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4017 else if (AMDGPU::SReg_32RegClass.contains(*I))
4018 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
4019 else
4020 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4021 }
4022 }
4023 }
4024
4025 // Update chain and glue.
4026 RetOps[0] = Chain;
4027 if (Glue.getNode())
4028 RetOps.push_back(Glue);
4029
4030 unsigned Opc = AMDGPUISD::ENDPGM;
4031 if (!IsWaveEnd)
4032 Opc = Info->isWholeWaveFunction() ? AMDGPUISD::WHOLE_WAVE_RETURN
4033 : IsShader ? AMDGPUISD::RETURN_TO_EPILOG
4034 : AMDGPUISD::RET_GLUE;
4035 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
4036}
4037
4039 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
4040 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4041 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
4042 SDValue ThisVal) const {
4043 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
4044
4045 // Assign locations to each value returned by this call.
4047 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
4048 *DAG.getContext());
4049 CCInfo.AnalyzeCallResult(Ins, RetCC);
4050
4051 // Copy all of the result registers out of their specified physreg.
4052 for (CCValAssign VA : RVLocs) {
4053 SDValue Val;
4054
4055 if (VA.isRegLoc()) {
4056 Val =
4057 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
4058 Chain = Val.getValue(1);
4059 InGlue = Val.getValue(2);
4060 } else if (VA.isMemLoc()) {
4061 report_fatal_error("TODO: return values in memory");
4062 } else
4063 llvm_unreachable("unknown argument location type");
4064
4065 Val = convertABITypeToValueType(DAG, Val, VA, DL);
4066
4067 InVals.push_back(Val);
4068 }
4069
4070 return Chain;
4071}
4072
4073// Add code to pass special inputs required depending on used features separate
4074// from the explicit user arguments present in the IR.
4076 CallLoweringInfo &CLI, CCState &CCInfo, const SIMachineFunctionInfo &Info,
4077 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4078 SmallVectorImpl<SDValue> &MemOpChains, SDValue Chain) const {
4079 // If we don't have a call site, this was a call inserted by
4080 // legalization. These can never use special inputs.
4081 if (!CLI.CB)
4082 return;
4083
4084 SelectionDAG &DAG = CLI.DAG;
4085 const SDLoc &DL = CLI.DL;
4086 const Function &F = DAG.getMachineFunction().getFunction();
4087
4088 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4089 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
4090
4091 const AMDGPUFunctionArgInfo &CalleeArgInfo =
4093
4094 // TODO: Unify with private memory register handling. This is complicated by
4095 // the fact that at least in kernels, the input argument is not necessarily
4096 // in the same location as the input.
4097 // clang-format off
4098 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
4099 std::array<StringLiteral, 2>> ImplicitAttrs[] = {
4100 {AMDGPUFunctionArgInfo::DISPATCH_PTR, {"amdgpu-no-dispatch-ptr", ""}},
4101 {AMDGPUFunctionArgInfo::QUEUE_PTR, {"amdgpu-no-queue-ptr", ""}},
4102 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, {"amdgpu-no-implicitarg-ptr", ""}},
4103 {AMDGPUFunctionArgInfo::DISPATCH_ID, {"amdgpu-no-dispatch-id", ""}},
4104 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, {"amdgpu-no-workgroup-id-x", "amdgpu-no-cluster-id-x"}},
4105 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, {"amdgpu-no-workgroup-id-y", "amdgpu-no-cluster-id-y"}},
4106 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, {"amdgpu-no-workgroup-id-z", "amdgpu-no-cluster-id-z"}},
4107 {AMDGPUFunctionArgInfo::LDS_KERNEL_ID, {"amdgpu-no-lds-kernel-id", ""}},
4108 };
4109 // clang-format on
4110
4111 for (auto [InputID, Attrs] : ImplicitAttrs) {
4112 // If the callee does not use the attribute value, skip copying the value.
4113 if (all_of(Attrs, [&](StringRef Attr) {
4114 return Attr.empty() || CLI.CB->hasFnAttr(Attr);
4115 }))
4116 continue;
4117
4118 const auto [OutgoingArg, ArgRC, ArgTy] =
4119 CalleeArgInfo.getPreloadedValue(InputID);
4120 if (!OutgoingArg)
4121 continue;
4122
4123 const auto [IncomingArg, IncomingArgRC, Ty] =
4124 CallerArgInfo.getPreloadedValue(InputID);
4125 assert(IncomingArgRC == ArgRC);
4126
4127 // All special arguments are ints for now.
4128 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
4129 SDValue InputReg;
4130
4131 if (IncomingArg) {
4132 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
4133 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
4134 // The implicit arg ptr is special because it doesn't have a corresponding
4135 // input for kernels, and is computed from the kernarg segment pointer.
4136 InputReg = getImplicitArgPtr(DAG, DL);
4137 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
4138 std::optional<uint32_t> Id =
4140 if (Id.has_value()) {
4141 InputReg = DAG.getConstant(*Id, DL, ArgVT);
4142 } else {
4143 InputReg = DAG.getPOISON(ArgVT);
4144 }
4145 } else {
4146 // We may have proven the input wasn't needed, although the ABI is
4147 // requiring it. We just need to allocate the register appropriately.
4148 InputReg = DAG.getPOISON(ArgVT);
4149 }
4150
4151 if (OutgoingArg->isRegister()) {
4152 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
4153 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
4154 report_fatal_error("failed to allocate implicit input argument");
4155 } else {
4156 unsigned SpecialArgOffset =
4157 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
4158 SDValue ArgStore =
4159 storeStackInputValue(DAG, DL, Chain, InputReg, SpecialArgOffset);
4160 MemOpChains.push_back(ArgStore);
4161 }
4162 }
4163
4164 // Pack workitem IDs into a single register or pass it as is if already
4165 // packed.
4166
4167 auto [OutgoingArg, ArgRC, Ty] =
4169 if (!OutgoingArg)
4170 std::tie(OutgoingArg, ArgRC, Ty) =
4172 if (!OutgoingArg)
4173 std::tie(OutgoingArg, ArgRC, Ty) =
4175 if (!OutgoingArg)
4176 return;
4177
4178 const ArgDescriptor *IncomingArgX = std::get<0>(
4180 const ArgDescriptor *IncomingArgY = std::get<0>(
4182 const ArgDescriptor *IncomingArgZ = std::get<0>(
4184
4185 SDValue InputReg;
4186 SDLoc SL;
4187
4188 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
4189 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
4190 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
4191
4192 // If incoming ids are not packed we need to pack them.
4193 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX &&
4194 NeedWorkItemIDX) {
4195 if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
4196 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
4197 } else {
4198 InputReg = DAG.getConstant(0, DL, MVT::i32);
4199 }
4200 }
4201
4202 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY &&
4203 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
4204 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
4205 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
4206 DAG.getShiftAmountConstant(10, MVT::i32, SL));
4207 InputReg = InputReg.getNode()
4208 ? DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y)
4209 : Y;
4210 }
4211
4212 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ &&
4213 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
4214 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
4215 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
4216 DAG.getShiftAmountConstant(20, MVT::i32, SL));
4217 InputReg = InputReg.getNode()
4218 ? DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z)
4219 : Z;
4220 }
4221
4222 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
4223 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
4224 // We're in a situation where the outgoing function requires the workitem
4225 // ID, but the calling function does not have it (e.g a graphics function
4226 // calling a C calling convention function). This is illegal, but we need
4227 // to produce something.
4228 InputReg = DAG.getPOISON(MVT::i32);
4229 } else {
4230 // Workitem ids are already packed, any of present incoming arguments
4231 // will carry all required fields.
4232 ArgDescriptor IncomingArg =
4233 ArgDescriptor::createArg(IncomingArgX ? *IncomingArgX
4234 : IncomingArgY ? *IncomingArgY
4235 : *IncomingArgZ,
4236 ~0u);
4237 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
4238 }
4239 }
4240
4241 if (OutgoingArg->isRegister()) {
4242 if (InputReg)
4243 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
4244
4245 CCInfo.AllocateReg(OutgoingArg->getRegister());
4246 } else {
4247 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
4248 if (InputReg) {
4249 SDValue ArgStore =
4250 storeStackInputValue(DAG, DL, Chain, InputReg, SpecialArgOffset);
4251 MemOpChains.push_back(ArgStore);
4252 }
4253 }
4254}
4255
4257 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
4259 const SmallVectorImpl<SDValue> &OutVals,
4260 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4261 if (AMDGPU::isChainCC(CalleeCC))
4262 return true;
4263
4264 if (!AMDGPU::mayTailCallThisCC(CalleeCC))
4265 return false;
4266
4267 // For a divergent call target, we need to do a waterfall loop over the
4268 // possible callees which precludes us from using a simple jump.
4269 if (Callee->isDivergent())
4270 return false;
4271
4273 const Function &CallerF = MF.getFunction();
4274 CallingConv::ID CallerCC = CallerF.getCallingConv();
4276 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4277
4278 // Kernels aren't callable, and don't have a live in return address so it
4279 // doesn't make sense to do a tail call with entry functions.
4280 if (!CallerPreserved)
4281 return false;
4282
4283 bool CCMatch = CallerCC == CalleeCC;
4284
4286 if (AMDGPU::canGuaranteeTCO(CalleeCC) && CCMatch)
4287 return true;
4288 return false;
4289 }
4290
4291 // TODO: Can we handle var args?
4292 if (IsVarArg)
4293 return false;
4294
4295 for (const Argument &Arg : CallerF.args()) {
4296 if (Arg.hasByValAttr())
4297 return false;
4298 }
4299
4300 LLVMContext &Ctx = *DAG.getContext();
4301
4302 // Check that the call results are passed in the same way.
4303 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
4304 CCAssignFnForCall(CalleeCC, IsVarArg),
4305 CCAssignFnForCall(CallerCC, IsVarArg)))
4306 return false;
4307
4308 // The callee has to preserve all registers the caller needs to preserve.
4309 if (!CCMatch) {
4310 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4311 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4312 return false;
4313 }
4314
4315 // Nothing more to check if the callee is taking no arguments.
4316 if (Outs.empty())
4317 return true;
4318
4320 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
4321
4322 // FIXME: We are not allocating special input registers, so we will be
4323 // deciding based on incorrect register assignments.
4324 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
4325
4326 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
4327 // If the stack arguments for this call do not fit into our own save area then
4328 // the call cannot be made tail.
4329 // TODO: Is this really necessary?
4330 if (CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea())
4331 return false;
4332
4333 for (const auto &[CCVA, ArgVal] : zip_equal(ArgLocs, OutVals)) {
4334 // FIXME: What about inreg arguments that end up passed in memory?
4335 if (!CCVA.isRegLoc())
4336 continue;
4337
4338 // If we are passing an argument in an SGPR, and the value is divergent,
4339 // this call requires a waterfall loop.
4340 if (ArgVal->isDivergent() && TRI->isSGPRPhysReg(CCVA.getLocReg())) {
4341 LLVM_DEBUG(
4342 dbgs() << "Cannot tail call due to divergent outgoing argument in "
4343 << printReg(CCVA.getLocReg(), TRI) << '\n');
4344 return false;
4345 }
4346 }
4347
4348 const MachineRegisterInfo &MRI = MF.getRegInfo();
4349 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
4350}
4351
4353 if (!CI->isTailCall())
4354 return false;
4355
4356 const Function *ParentFn = CI->getFunction();
4358 return false;
4359 return true;
4360}
4361
4362namespace {
4363// Chain calls have special arguments that we need to handle. These are
4364// tagging along at the end of the arguments list(s), after the SGPR and VGPR
4365// arguments (index 0 and 1 respectively).
4366enum ChainCallArgIdx {
4367 Exec = 2,
4368 Flags,
4369 NumVGPRs,
4370 FallbackExec,
4371 FallbackCallee
4372};
4373} // anonymous namespace
4374
4375// The wave scratch offset register is used as the global base pointer.
4377 SmallVectorImpl<SDValue> &InVals) const {
4378 CallingConv::ID CallConv = CLI.CallConv;
4379 bool IsChainCallConv = AMDGPU::isChainCC(CallConv);
4380
4381 SelectionDAG &DAG = CLI.DAG;
4382
4383 const SDLoc &DL = CLI.DL;
4384 SDValue Chain = CLI.Chain;
4385 SDValue Callee = CLI.Callee;
4386
4387 llvm::SmallVector<SDValue, 6> ChainCallSpecialArgs;
4388 bool UsesDynamicVGPRs = false;
4389 if (IsChainCallConv) {
4390 // The last arguments should be the value that we need to put in EXEC,
4391 // followed by the flags and any other arguments with special meanings.
4392 // Pop them out of CLI.Outs and CLI.OutVals before we do any processing so
4393 // we don't treat them like the "real" arguments.
4394 auto RequestedExecIt =
4395 llvm::find_if(CLI.Outs, [](const ISD::OutputArg &Arg) {
4396 return Arg.OrigArgIndex == 2;
4397 });
4398 assert(RequestedExecIt != CLI.Outs.end() && "No node for EXEC");
4399
4400 size_t SpecialArgsBeginIdx = RequestedExecIt - CLI.Outs.begin();
4401 CLI.OutVals.erase(CLI.OutVals.begin() + SpecialArgsBeginIdx,
4402 CLI.OutVals.end());
4403 CLI.Outs.erase(RequestedExecIt, CLI.Outs.end());
4404
4405 assert(CLI.Outs.back().OrigArgIndex < 2 &&
4406 "Haven't popped all the special args");
4407
4408 TargetLowering::ArgListEntry RequestedExecArg =
4409 CLI.Args[ChainCallArgIdx::Exec];
4410 if (!RequestedExecArg.Ty->isIntegerTy(Subtarget->getWavefrontSize()))
4411 return lowerUnhandledCall(CLI, InVals, "Invalid value for EXEC");
4412
4413 // Convert constants into TargetConstants, so they become immediate operands
4414 // instead of being selected into S_MOV.
4415 auto PushNodeOrTargetConstant = [&](TargetLowering::ArgListEntry Arg) {
4416 if (const auto *ArgNode = dyn_cast<ConstantSDNode>(Arg.Node)) {
4417 ChainCallSpecialArgs.push_back(DAG.getTargetConstant(
4418 ArgNode->getAPIntValue(), DL, ArgNode->getValueType(0)));
4419 } else
4420 ChainCallSpecialArgs.push_back(Arg.Node);
4421 };
4422
4423 PushNodeOrTargetConstant(RequestedExecArg);
4424
4425 // Process any other special arguments depending on the value of the flags.
4426 TargetLowering::ArgListEntry Flags = CLI.Args[ChainCallArgIdx::Flags];
4427
4428 const APInt &FlagsValue = cast<ConstantSDNode>(Flags.Node)->getAPIntValue();
4429 if (FlagsValue.isZero()) {
4430 if (CLI.Args.size() > ChainCallArgIdx::Flags + 1)
4431 return lowerUnhandledCall(CLI, InVals,
4432 "no additional args allowed if flags == 0");
4433 } else if (FlagsValue.isOneBitSet(0)) {
4434 if (CLI.Args.size() != ChainCallArgIdx::FallbackCallee + 1) {
4435 return lowerUnhandledCall(CLI, InVals, "expected 3 additional args");
4436 }
4437
4438 if (!Subtarget->isWave32()) {
4439 return lowerUnhandledCall(
4440 CLI, InVals, "dynamic VGPR mode is only supported for wave32");
4441 }
4442
4443 UsesDynamicVGPRs = true;
4444 std::for_each(CLI.Args.begin() + ChainCallArgIdx::NumVGPRs,
4445 CLI.Args.end(), PushNodeOrTargetConstant);
4446 }
4447 }
4448
4450 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4452 bool &IsTailCall = CLI.IsTailCall;
4453 bool IsVarArg = CLI.IsVarArg;
4454 bool IsSibCall = false;
4456
4457 if (Callee.isUndef() || isNullConstant(Callee)) {
4458 if (!CLI.IsTailCall) {
4459 for (ISD::InputArg &Arg : CLI.Ins)
4460 InVals.push_back(DAG.getPOISON(Arg.VT));
4461 }
4462
4463 return Chain;
4464 }
4465
4466 if (IsVarArg) {
4467 return lowerUnhandledCall(CLI, InVals,
4468 "unsupported call to variadic function ");
4469 }
4470
4471 if (!CLI.CB)
4472 return lowerUnhandledCall(CLI, InVals, "unsupported libcall legalization");
4473
4474 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
4475 return lowerUnhandledCall(CLI, InVals,
4476 "unsupported required tail call to function ");
4477 }
4478
4479 if (IsTailCall) {
4480 IsTailCall = isEligibleForTailCallOptimization(Callee, CallConv, IsVarArg,
4481 Outs, OutVals, Ins, DAG);
4482 if (!IsTailCall &&
4483 ((CLI.CB && CLI.CB->isMustTailCall()) || IsChainCallConv)) {
4484 report_fatal_error("failed to perform tail call elimination on a call "
4485 "site marked musttail or on llvm.amdgcn.cs.chain");
4486 }
4487
4488 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4489
4490 // A sibling call is one where we're under the usual C ABI and not planning
4491 // to change that but can still do a tail call:
4492 if (!TailCallOpt && IsTailCall)
4493 IsSibCall = true;
4494
4495 if (IsTailCall)
4496 ++NumTailCalls;
4497 }
4498
4501 SmallVector<SDValue, 8> MemOpChains;
4502
4503 // Analyze operands of the call, assigning locations to each operand.
4505 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
4506 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
4507
4508 if (CallConv != CallingConv::AMDGPU_Gfx && !AMDGPU::isChainCC(CallConv) &&
4510 // With a fixed ABI, allocate fixed registers before user arguments.
4511 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
4512 }
4513
4514 // Mark the scratch resource descriptor as allocated so the CC analysis
4515 // does not assign user arguments to these registers, matching the callee.
4516 if (!Subtarget->hasFlatScratchEnabled()) {
4517 CCInfo.AllocateReg(
4519 }
4520
4521 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
4522
4523 // Get a count of how many bytes are to be pushed on the stack.
4524 unsigned NumBytes = CCInfo.getStackSize();
4525
4526 if (IsSibCall) {
4527 // Since we're not changing the ABI to make this a tail call, the memory
4528 // operands are already available in the caller's incoming argument space.
4529 NumBytes = 0;
4530 }
4531
4532 // FPDiff is the byte offset of the call's argument area from the callee's.
4533 // Stores to callee stack arguments will be placed in FixedStackSlots offset
4534 // by this amount for a tail call. In a sibling call it must be 0 because the
4535 // caller will deallocate the entire stack and the callee still expects its
4536 // arguments to begin at SP+0. Completely unused for non-tail calls.
4537 int32_t FPDiff = 0;
4538 MachineFrameInfo &MFI = MF.getFrameInfo();
4539 auto *TRI = Subtarget->getRegisterInfo();
4540
4541 // Adjust the stack pointer for the new arguments...
4542 // These operations are automatically eliminated by the prolog/epilog pass
4543 if (!IsSibCall)
4544 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
4545
4546 if (!IsSibCall || IsChainCallConv) {
4547 if (!Subtarget->hasFlatScratchEnabled()) {
4548 SmallVector<SDValue, 4> CopyFromChains;
4549
4550 // In the HSA case, this should be an identity copy.
4551 SDValue ScratchRSrcReg =
4552 DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
4553 RegsToPass.emplace_back(
4555 ScratchRSrcReg);
4556 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
4557 Chain = DAG.getTokenFactor(DL, CopyFromChains);
4558 }
4559 }
4560
4561 const unsigned NumSpecialInputs = RegsToPass.size();
4562
4563 MVT PtrVT = MVT::i32;
4564
4565 // Walk the register/memloc assignments, inserting copies/loads.
4566 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4567 CCValAssign &VA = ArgLocs[i];
4568 SDValue Arg = OutVals[i];
4569
4570 // Promote the value if needed.
4571 switch (VA.getLocInfo()) {
4572 case CCValAssign::Full:
4573 break;
4574 case CCValAssign::BCvt:
4575 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4576 break;
4577 case CCValAssign::ZExt:
4578 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4579 break;
4580 case CCValAssign::SExt:
4581 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4582 break;
4583 case CCValAssign::AExt:
4584 Arg = DAG.getBitcast(VA.getValVT().changeTypeToInteger(), Arg);
4585 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4586 break;
4587 case CCValAssign::FPExt:
4588 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4589 break;
4590 default:
4591 llvm_unreachable("Unknown loc info!");
4592 }
4593
4594 if (VA.isRegLoc()) {
4595 RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
4596 } else {
4597 assert(VA.isMemLoc());
4598
4599 SDValue DstAddr;
4600 MachinePointerInfo DstInfo;
4601
4602 unsigned LocMemOffset = VA.getLocMemOffset();
4603 int32_t Offset = LocMemOffset;
4604
4605 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
4606 MaybeAlign Alignment;
4607
4608 if (IsTailCall) {
4609 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4610 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize()
4611 : VA.getValVT().getStoreSize();
4612
4613 // FIXME: We can have better than the minimum byval required alignment.
4614 Alignment =
4615 Flags.isByVal()
4616 ? Flags.getNonZeroByValAlign()
4617 : commonAlignment(Subtarget->getStackAlignment(), Offset);
4618
4619 Offset = Offset + FPDiff;
4620 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
4621
4622 DstAddr = DAG.getFrameIndex(FI, PtrVT);
4623 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
4624
4625 // Make sure any stack arguments overlapping with where we're storing
4626 // are loaded before this eventual operation. Otherwise they'll be
4627 // clobbered.
4628
4629 // FIXME: Why is this really necessary? This seems to just result in a
4630 // lot of code to copy the stack and write them back to the same
4631 // locations, which are supposed to be immutable?
4632 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
4633 } else {
4634 // Stores to the argument stack area are relative to the stack pointer.
4635 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
4636 MVT::i32);
4637 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
4638 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
4639 Alignment =
4640 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
4641 }
4642
4643 if (Outs[i].Flags.isByVal()) {
4644 SDValue SizeNode =
4645 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
4646 SDValue Cpy =
4647 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
4648 Outs[i].Flags.getNonZeroByValAlign(),
4649 Outs[i].Flags.getNonZeroByValAlign(),
4650 /*isVol = */ false, /*AlwaysInline = */ true,
4651 /*CI=*/nullptr, std::nullopt, DstInfo,
4653
4654 MemOpChains.push_back(Cpy);
4655 } else {
4656 SDValue Store =
4657 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
4658 MemOpChains.push_back(Store);
4659 }
4660 }
4661 }
4662
4663 if (!MemOpChains.empty())
4664 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4665
4666 SDValue ReadFirstLaneID =
4667 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
4668
4669 SDValue TokenGlue;
4670 if (CLI.ConvergenceControlToken) {
4671 TokenGlue = DAG.getNode(ISD::CONVERGENCECTRL_GLUE, DL, MVT::Glue,
4673 }
4674
4675 // Build a sequence of copy-to-reg nodes chained together with token chain
4676 // and flag operands which copy the outgoing args into the appropriate regs.
4677 SDValue InGlue;
4678
4679 unsigned ArgIdx = 0;
4680 for (auto [Reg, Val] : RegsToPass) {
4681 if (ArgIdx++ >= NumSpecialInputs &&
4682 (IsChainCallConv || !Val->isDivergent()) && TRI->isSGPRPhysReg(Reg)) {
4683 // For chain calls, the inreg arguments are required to be
4684 // uniform. Speculatively Insert a readfirstlane in case we cannot prove
4685 // they are uniform.
4686 //
4687 // For other calls, if an inreg arguments is known to be uniform,
4688 // speculatively insert a readfirstlane in case it is in a VGPR.
4689 //
4690 // FIXME: We need to execute this in a waterfall loop if it is a divergent
4691 // value, so let that continue to produce invalid code.
4692
4693 SmallVector<SDValue, 3> ReadfirstlaneArgs({ReadFirstLaneID, Val});
4694 if (TokenGlue)
4695 ReadfirstlaneArgs.push_back(TokenGlue);
4697 ReadfirstlaneArgs);
4698 }
4699
4700 Chain = DAG.getCopyToReg(Chain, DL, Reg, Val, InGlue);
4701 InGlue = Chain.getValue(1);
4702 }
4703
4704 // We don't usually want to end the call-sequence here because we would tidy
4705 // the frame up *after* the call, however in the ABI-changing tail-call case
4706 // we've carefully laid out the parameters so that when sp is reset they'll be
4707 // in the correct location.
4708 if (IsTailCall && !IsSibCall) {
4709 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
4710 InGlue = Chain.getValue(1);
4711 }
4712
4713 std::vector<SDValue> Ops({Chain});
4714
4715 // Add a redundant copy of the callee global which will not be legalized, as
4716 // we need direct access to the callee later.
4718 const GlobalValue *GV = GSD->getGlobal();
4719 Ops.push_back(Callee);
4720 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
4721 } else {
4722 if (IsTailCall) {
4723 // isEligibleForTailCallOptimization considered whether the call target is
4724 // divergent, but we may still end up with a uniform value in a VGPR.
4725 // Insert a readfirstlane just in case.
4726 SDValue ReadFirstLaneID =
4727 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
4728
4729 SmallVector<SDValue, 3> ReadfirstlaneArgs({ReadFirstLaneID, Callee});
4730 if (TokenGlue)
4731 ReadfirstlaneArgs.push_back(TokenGlue); // Wire up convergence token.
4732 Callee = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Callee.getValueType(),
4733 ReadfirstlaneArgs);
4734 }
4735
4736 Ops.push_back(Callee);
4737 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
4738 }
4739
4740 if (IsTailCall) {
4741 // Each tail call may have to adjust the stack by a different amount, so
4742 // this information must travel along with the operation for eventual
4743 // consumption by emitEpilogue.
4744 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4745 }
4746
4747 if (IsChainCallConv)
4748 llvm::append_range(Ops, ChainCallSpecialArgs);
4749
4750 // Add argument registers to the end of the list so that they are known live
4751 // into the call.
4752 for (auto &[Reg, Val] : RegsToPass)
4753 Ops.push_back(DAG.getRegister(Reg, Val.getValueType()));
4754
4755 // Add a register mask operand representing the call-preserved registers.
4756 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
4757 assert(Mask && "Missing call preserved mask for calling convention");
4758 Ops.push_back(DAG.getRegisterMask(Mask));
4759
4760 if (SDValue Token = CLI.ConvergenceControlToken) {
4762 GlueOps.push_back(Token);
4763 if (InGlue)
4764 GlueOps.push_back(InGlue);
4765
4766 InGlue = SDValue(DAG.getMachineNode(TargetOpcode::CONVERGENCECTRL_GLUE, DL,
4767 MVT::Glue, GlueOps),
4768 0);
4769 }
4770
4771 if (InGlue)
4772 Ops.push_back(InGlue);
4773
4774 // If we're doing a tall call, use a TC_RETURN here rather than an
4775 // actual call instruction.
4776 if (IsTailCall) {
4777 MFI.setHasTailCall();
4778 unsigned OPC = AMDGPUISD::TC_RETURN;
4779 switch (CallConv) {
4781 OPC = AMDGPUISD::TC_RETURN_GFX;
4782 break;
4785 OPC = UsesDynamicVGPRs ? AMDGPUISD::TC_RETURN_CHAIN_DVGPR
4786 : AMDGPUISD::TC_RETURN_CHAIN;
4787 break;
4788 }
4789
4790 // If the caller is a whole wave function, we need to use a special opcode
4791 // so we can patch up EXEC.
4792 if (Info->isWholeWaveFunction())
4793 OPC = AMDGPUISD::TC_RETURN_GFX_WholeWave;
4794
4795 SDValue Ret = DAG.getNode(OPC, DL, MVT::Other, Ops);
4796 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
4797 return Ret;
4798 }
4799
4800 // Returns a chain and a flag for retval copy to use.
4801 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
4802 DAG.addNoMergeSiteInfo(Call.getNode(), CLI.NoMerge);
4803 Chain = Call.getValue(0);
4804 InGlue = Call.getValue(1);
4805
4806 uint64_t CalleePopBytes = NumBytes;
4807 Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InGlue, DL);
4808 if (!Ins.empty())
4809 InGlue = Chain.getValue(1);
4810
4811 // Handle result values, copying them out of physregs into vregs that we
4812 // return.
4813 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
4814 InVals, /*IsThisReturn=*/false, SDValue());
4815}
4816
4817// This is similar to the default implementation in ExpandDYNAMIC_STACKALLOC,
4818// except for:
4819// 1. Stack growth direction(default: downwards, AMDGPU: upwards), and
4820// 2. Scale size where, scale = wave-reduction(alloca-size) * wave-size
4822 SelectionDAG &DAG) const {
4823 const MachineFunction &MF = DAG.getMachineFunction();
4825
4826 SDLoc dl(Op);
4827 EVT VT = Op.getValueType();
4828 SDValue Chain = Op.getOperand(0);
4829 Register SPReg = Info->getStackPtrOffsetReg();
4830
4831 // Chain the dynamic stack allocation so that it doesn't modify the stack
4832 // pointer when other instructions are using the stack.
4833 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
4834
4835 SDValue Size = Op.getOperand(1);
4836 SDValue BaseAddr = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
4837 Align Alignment = cast<ConstantSDNode>(Op.getOperand(2))->getAlignValue();
4838
4839 const TargetFrameLowering *TFL = Subtarget->getFrameLowering();
4841 "Stack grows upwards for AMDGPU");
4842
4843 Chain = BaseAddr.getValue(1);
4844 // When using flat-scratch, the stack offset is unscaled.
4845 const bool HasFlatScratch = Subtarget->hasFlatScratchEnabled();
4846 const unsigned WavefrontSizeLog2 = Subtarget->getWavefrontSizeLog2();
4847
4848 Align StackAlign = TFL->getStackAlign();
4849 if (Alignment > StackAlign) {
4850 uint64_t ScaledAlignment = Alignment.value()
4851 << (HasFlatScratch ? 0 : WavefrontSizeLog2);
4852 uint64_t StackAlignMask = ScaledAlignment - 1;
4853 SDValue TmpAddr = DAG.getNode(ISD::ADD, dl, VT, BaseAddr,
4854 DAG.getConstant(StackAlignMask, dl, VT));
4855 BaseAddr = DAG.getNode(ISD::AND, dl, VT, TmpAddr,
4856 DAG.getSignedConstant(~StackAlignMask, dl, VT));
4857 }
4858
4859 assert(Size.getValueType() == MVT::i32 && "Size must be 32-bit");
4860 SDValue NewSP;
4862 // Increase the stack pointer by the size of the alloca.
4863 // If not using flat-scratch, we have to scale the size by the wave-size.
4864 SDValue ScaledSize =
4865 HasFlatScratch
4866 ? Size
4867 : DAG.getNode(ISD::SHL, dl, VT, Size,
4868 DAG.getConstant(WavefrontSizeLog2, dl, MVT::i32));
4869 NewSP = DAG.getNode(ISD::ADD, dl, VT, BaseAddr, ScaledSize); // Value
4870 } else {
4871 // For dynamic sized alloca, perform wave-wide reduction to get max of
4872 // alloca size(divergent), and then scale it (when not using flat-scratch)
4873 // by wave-size.
4874 SDValue WaveReduction =
4875 DAG.getTargetConstant(Intrinsic::amdgcn_wave_reduce_umax, dl, MVT::i32);
4876 Size = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, WaveReduction,
4877 Size, DAG.getTargetConstant(0, dl, MVT::i32));
4878 SDValue ScaledSize = Size;
4879 if (!HasFlatScratch) {
4880 ScaledSize =
4881 DAG.getNode(ISD::SHL, dl, VT, Size,
4882 DAG.getConstant(WavefrontSizeLog2, dl, MVT::i32));
4883 }
4884 NewSP =
4885 DAG.getNode(ISD::ADD, dl, VT, BaseAddr, ScaledSize); // Value in vgpr.
4886 SDValue ReadFirstLaneID =
4887 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, dl, MVT::i32);
4888 NewSP = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, ReadFirstLaneID,
4889 NewSP);
4890 }
4891
4892 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP); // Output chain
4893 SDValue CallSeqEnd = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
4894
4895 return DAG.getMergeValues({BaseAddr, CallSeqEnd}, dl);
4896}
4897
4899 if (Op.getValueType() != MVT::i32)
4900 return Op; // Defer to cannot select error.
4901
4903 SDLoc SL(Op);
4904
4905 SDValue CopyFromSP = DAG.getCopyFromReg(Op->getOperand(0), SL, SP, MVT::i32);
4906
4907 // Convert from wave uniform to swizzled vector address. This should protect
4908 // from any edge cases where the stacksave result isn't directly used with
4909 // stackrestore.
4910 SDValue VectorAddress =
4911 DAG.getNode(AMDGPUISD::WAVE_ADDRESS, SL, MVT::i32, CopyFromSP);
4912 return DAG.getMergeValues({VectorAddress, CopyFromSP.getValue(1)}, SL);
4913}
4914
4916 SelectionDAG &DAG) const {
4917 SDLoc SL(Op);
4918 assert(Op.getValueType() == MVT::i32);
4919
4920 uint32_t BothRoundHwReg =
4922 SDValue GetRoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
4923
4924 SDValue IntrinID =
4925 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
4926 SDValue GetReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, Op->getVTList(),
4927 Op.getOperand(0), IntrinID, GetRoundBothImm);
4928
4929 // There are two rounding modes, one for f32 and one for f64/f16. We only
4930 // report in the standard value range if both are the same.
4931 //
4932 // The raw values also differ from the expected FLT_ROUNDS values. Nearest
4933 // ties away from zero is not supported, and the other values are rotated by
4934 // 1.
4935 //
4936 // If the two rounding modes are not the same, report a target defined value.
4937
4938 // Mode register rounding mode fields:
4939 //
4940 // [1:0] Single-precision round mode.
4941 // [3:2] Double/Half-precision round mode.
4942 //
4943 // 0=nearest even; 1= +infinity; 2= -infinity, 3= toward zero.
4944 //
4945 // Hardware Spec
4946 // Toward-0 3 0
4947 // Nearest Even 0 1
4948 // +Inf 1 2
4949 // -Inf 2 3
4950 // NearestAway0 N/A 4
4951 //
4952 // We have to handle 16 permutations of a 4-bit value, so we create a 64-bit
4953 // table we can index by the raw hardware mode.
4954 //
4955 // (trunc (FltRoundConversionTable >> MODE.fp_round)) & 0xf
4956
4957 SDValue BitTable =
4959
4960 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
4961 SDValue RoundModeTimesNumBits =
4962 DAG.getNode(ISD::SHL, SL, MVT::i32, GetReg, Two);
4963
4964 // TODO: We could possibly avoid a 64-bit shift and use a simpler table if we
4965 // knew only one mode was demanded.
4966 SDValue TableValue =
4967 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
4968 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
4969
4970 SDValue EntryMask = DAG.getConstant(0xf, SL, MVT::i32);
4971 SDValue TableEntry =
4972 DAG.getNode(ISD::AND, SL, MVT::i32, TruncTable, EntryMask);
4973
4974 // There's a gap in the 4-bit encoded table and actual enum values, so offset
4975 // if it's an extended value.
4976 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
4977 SDValue IsStandardValue =
4978 DAG.getSetCC(SL, MVT::i1, TableEntry, Four, ISD::SETULT);
4979 SDValue EnumOffset = DAG.getNode(ISD::ADD, SL, MVT::i32, TableEntry, Four);
4980 SDValue Result = DAG.getNode(ISD::SELECT, SL, MVT::i32, IsStandardValue,
4981 TableEntry, EnumOffset);
4982
4983 return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
4984}
4985
4987 SelectionDAG &DAG) const {
4988 SDLoc SL(Op);
4989
4990 SDValue NewMode = Op.getOperand(1);
4991 assert(NewMode.getValueType() == MVT::i32);
4992
4993 // Index a table of 4-bit entries mapping from the C FLT_ROUNDS values to the
4994 // hardware MODE.fp_round values.
4995 if (auto *ConstMode = dyn_cast<ConstantSDNode>(NewMode)) {
4996 uint32_t ClampedVal = std::min(
4997 static_cast<uint32_t>(ConstMode->getZExtValue()),
4999 NewMode = DAG.getConstant(
5000 AMDGPU::decodeFltRoundToHWConversionTable(ClampedVal), SL, MVT::i32);
5001 } else {
5002 // If we know the input can only be one of the supported standard modes in
5003 // the range 0-3, we can use a simplified mapping to hardware values.
5004 KnownBits KB = DAG.computeKnownBits(NewMode);
5005 const bool UseReducedTable = KB.countMinLeadingZeros() >= 30;
5006 // The supported standard values are 0-3. The extended values start at 8. We
5007 // need to offset by 4 if the value is in the extended range.
5008
5009 if (UseReducedTable) {
5010 // Truncate to the low 32-bits.
5011 SDValue BitTable = DAG.getConstant(
5012 AMDGPU::FltRoundToHWConversionTable & 0xffff, SL, MVT::i32);
5013
5014 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
5015 SDValue RoundModeTimesNumBits =
5016 DAG.getNode(ISD::SHL, SL, MVT::i32, NewMode, Two);
5017
5018 NewMode =
5019 DAG.getNode(ISD::SRL, SL, MVT::i32, BitTable, RoundModeTimesNumBits);
5020
5021 // TODO: SimplifyDemandedBits on the setreg source here can likely reduce
5022 // the table extracted bits into inline immediates.
5023 } else {
5024 // table_index = umin(value, value - 4)
5025 // MODE.fp_round = (bit_table >> (table_index << 2)) & 0xf
5026 SDValue BitTable =
5028
5029 SDValue Four = DAG.getConstant(4, SL, MVT::i32);
5030 SDValue OffsetEnum = DAG.getNode(ISD::SUB, SL, MVT::i32, NewMode, Four);
5031 SDValue IndexVal =
5032 DAG.getNode(ISD::UMIN, SL, MVT::i32, NewMode, OffsetEnum);
5033
5034 SDValue Two = DAG.getConstant(2, SL, MVT::i32);
5035 SDValue RoundModeTimesNumBits =
5036 DAG.getNode(ISD::SHL, SL, MVT::i32, IndexVal, Two);
5037
5038 SDValue TableValue =
5039 DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
5040 SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
5041
5042 // No need to mask out the high bits since the setreg will ignore them
5043 // anyway.
5044 NewMode = TruncTable;
5045 }
5046
5047 // Insert a readfirstlane in case the value is a VGPR. We could do this
5048 // earlier and keep more operations scalar, but that interferes with
5049 // combining the source.
5050 SDValue ReadFirstLaneID =
5051 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, SL, MVT::i32);
5052 NewMode = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5053 ReadFirstLaneID, NewMode);
5054 }
5055
5056 // N.B. The setreg will be later folded into s_round_mode on supported
5057 // targets.
5058 SDValue IntrinID =
5059 DAG.getTargetConstant(Intrinsic::amdgcn_s_setreg, SL, MVT::i32);
5060 uint32_t BothRoundHwReg =
5062 SDValue RoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
5063
5064 SDValue SetReg =
5065 DAG.getNode(ISD::INTRINSIC_VOID, SL, Op->getVTList(), Op.getOperand(0),
5066 IntrinID, RoundBothImm, NewMode);
5067
5068 return SetReg;
5069}
5070
5072 unsigned AS = cast<MemSDNode>(Op)->getAddressSpace();
5073 if (AS == AMDGPUAS::BUFFER_RESOURCE)
5074 return Op.getOperand(0);
5076 return SDValue();
5077
5078 // I$ prefetch
5079 if (!Subtarget->hasSafeSmemPrefetch() && !Op.getConstantOperandVal(4))
5080 return SDValue();
5081
5082 return Op;
5083}
5084
5085// Work around DAG legality rules only based on the result type.
5087 bool IsStrict = Op.getOpcode() == ISD::STRICT_FP_EXTEND;
5088 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
5089 EVT SrcVT = Src.getValueType();
5090
5091 if (SrcVT.getScalarType() != MVT::bf16)
5092 return Op;
5093
5094 SDLoc SL(Op);
5095 SDValue BitCast =
5096 DAG.getNode(ISD::BITCAST, SL, SrcVT.changeTypeToInteger(), Src);
5097
5098 EVT DstVT = Op.getValueType();
5099 if (IsStrict)
5100 llvm_unreachable("Need STRICT_BF16_TO_FP");
5101
5102 return DAG.getNode(ISD::BF16_TO_FP, SL, DstVT, BitCast);
5103}
5104
5106 SDLoc SL(Op);
5107 if (Op.getValueType() != MVT::i64)
5108 return Op;
5109
5110 uint32_t ModeHwReg =
5112 SDValue ModeHwRegImm = DAG.getTargetConstant(ModeHwReg, SL, MVT::i32);
5113 uint32_t TrapHwReg =
5115 SDValue TrapHwRegImm = DAG.getTargetConstant(TrapHwReg, SL, MVT::i32);
5116
5117 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::Other);
5118 SDValue IntrinID =
5119 DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
5120 SDValue GetModeReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, VTList,
5121 Op.getOperand(0), IntrinID, ModeHwRegImm);
5122 SDValue GetTrapReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, VTList,
5123 Op.getOperand(0), IntrinID, TrapHwRegImm);
5124 SDValue TokenReg =
5125 DAG.getNode(ISD::TokenFactor, SL, MVT::Other, GetModeReg.getValue(1),
5126 GetTrapReg.getValue(1));
5127
5128 SDValue CvtPtr =
5129 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, GetModeReg, GetTrapReg);
5130 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5131
5132 return DAG.getMergeValues({Result, TokenReg}, SL);
5133}
5134
5136 SDLoc SL(Op);
5137 if (Op.getOperand(1).getValueType() != MVT::i64)
5138 return Op;
5139
5140 SDValue Input = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op.getOperand(1));
5141 SDValue NewModeReg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Input,
5142 DAG.getConstant(0, SL, MVT::i32));
5143 SDValue NewTrapReg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Input,
5144 DAG.getConstant(1, SL, MVT::i32));
5145
5146 SDValue ReadFirstLaneID =
5147 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, SL, MVT::i32);
5148 NewModeReg = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5149 ReadFirstLaneID, NewModeReg);
5150 NewTrapReg = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
5151 ReadFirstLaneID, NewTrapReg);
5152
5153 unsigned ModeHwReg =
5155 SDValue ModeHwRegImm = DAG.getTargetConstant(ModeHwReg, SL, MVT::i32);
5156 unsigned TrapHwReg =
5158 SDValue TrapHwRegImm = DAG.getTargetConstant(TrapHwReg, SL, MVT::i32);
5159
5160 SDValue IntrinID =
5161 DAG.getTargetConstant(Intrinsic::amdgcn_s_setreg, SL, MVT::i32);
5162 SDValue SetModeReg =
5163 DAG.getNode(ISD::INTRINSIC_VOID, SL, MVT::Other, Op.getOperand(0),
5164 IntrinID, ModeHwRegImm, NewModeReg);
5165 SDValue SetTrapReg =
5166 DAG.getNode(ISD::INTRINSIC_VOID, SL, MVT::Other, Op.getOperand(0),
5167 IntrinID, TrapHwRegImm, NewTrapReg);
5168 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, SetTrapReg, SetModeReg);
5169}
5170
5172 const MachineFunction &MF) const {
5173 Register Reg =
5175 .Case("m0", AMDGPU::M0)
5176 .Case("exec", AMDGPU::EXEC)
5177 .Case("exec_lo", AMDGPU::EXEC_LO)
5178 .Case("exec_hi", AMDGPU::EXEC_HI)
5179 .Case("flat_scratch", AMDGPU::FLAT_SCR)
5180 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
5181 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
5182 .Case("src_flat_scratch_base", AMDGPU::SRC_FLAT_SCRATCH_BASE)
5183 .Case("src_flat_scratch_base_lo", AMDGPU::SRC_FLAT_SCRATCH_BASE_LO)
5184 .Case("src_flat_scratch_base_hi", AMDGPU::SRC_FLAT_SCRATCH_BASE_HI)
5185 .Default(Register());
5186 if (!Reg)
5187 return Reg;
5188
5189 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
5190 if (!Subtarget->hasFlatScrRegister() &&
5191 TRI->regsOverlap(Reg, AMDGPU::FLAT_SCR))
5192 return Register();
5193
5194 if (!Subtarget->hasGloballyAddressableScratch() &&
5195 TRI->regsOverlap(Reg, AMDGPU::SRC_FLAT_SCRATCH_BASE))
5196 return Register();
5197
5198 switch (Reg) {
5199 case AMDGPU::M0:
5200 case AMDGPU::EXEC_LO:
5201 case AMDGPU::EXEC_HI:
5202 case AMDGPU::FLAT_SCR_LO:
5203 case AMDGPU::FLAT_SCR_HI:
5204 case AMDGPU::SRC_FLAT_SCRATCH_BASE_LO:
5205 case AMDGPU::SRC_FLAT_SCRATCH_BASE_HI:
5206 if (VT.getSizeInBits() == 32)
5207 return Reg;
5208 break;
5209 case AMDGPU::EXEC:
5210 case AMDGPU::FLAT_SCR:
5211 case AMDGPU::SRC_FLAT_SCRATCH_BASE:
5212 if (VT.getSizeInBits() == 64)
5213 return Reg;
5214 break;
5215 default:
5216 llvm_unreachable("missing register type checking");
5217 }
5218
5220 Twine("invalid type for register \"" + StringRef(RegName) + "\"."));
5221}
5222
5223// If kill is not the last instruction, split the block so kill is always a
5224// proper terminator.
5227 MachineBasicBlock *BB) const {
5228 MachineBasicBlock *SplitBB = BB->splitAt(MI, /*UpdateLiveIns=*/true);
5230 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
5231 return SplitBB;
5232}
5233
5234// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
5235// \p MI will be the only instruction in the loop body block. Otherwise, it will
5236// be the first instruction in the remainder block.
5237//
5238/// \returns { LoopBody, Remainder }
5239static std::pair<MachineBasicBlock *, MachineBasicBlock *>
5241 MachineFunction *MF = MBB.getParent();
5243
5244 // To insert the loop we need to split the block. Move everything after this
5245 // point to a new block, and insert a new empty block between the two.
5247 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
5249 ++MBBI;
5250
5251 MF->insert(MBBI, LoopBB);
5252 MF->insert(MBBI, RemainderBB);
5253
5254 LoopBB->addSuccessor(LoopBB);
5255 LoopBB->addSuccessor(RemainderBB);
5256
5257 // Move the rest of the block into a new block.
5258 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5259
5260 if (InstInLoop) {
5261 auto Next = std::next(I);
5262
5263 // Move instruction to loop body.
5264 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
5265
5266 // Move the rest of the block.
5267 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
5268 } else {
5269 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
5270 }
5271
5272 MBB.addSuccessor(LoopBB);
5273
5274 return std::pair(LoopBB, RemainderBB);
5275}
5276
5277/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
5279 MachineBasicBlock *MBB = MI.getParent();
5281 auto I = MI.getIterator();
5282 auto E = std::next(I);
5283
5284 // clang-format off
5285 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
5286 .addImm(0);
5287 // clang-format on
5288
5289 MIBundleBuilder Bundler(*MBB, I, E);
5290 finalizeBundle(*MBB, Bundler.begin());
5291}
5292
5295 MachineBasicBlock *BB) const {
5296 const DebugLoc &DL = MI.getDebugLoc();
5297
5299
5301
5302 // Apparently kill flags are only valid if the def is in the same block?
5303 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
5304 Src->setIsKill(false);
5305
5306 auto [LoopBB, RemainderBB] = splitBlockForLoop(MI, *BB, true);
5307
5308 MachineBasicBlock::iterator I = LoopBB->end();
5309
5310 const unsigned EncodedReg = AMDGPU::Hwreg::HwregEncoding::encode(
5312
5313 // Clear TRAP_STS.MEM_VIOL
5314 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
5315 .addImm(0)
5316 .addImm(EncodedReg);
5317
5319
5320 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5321
5322 // Load and check TRAP_STS.MEM_VIOL
5323 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
5324 .addImm(EncodedReg);
5325
5326 // clang-format off
5327 // FIXME: Do we need to use an isel pseudo that may clobber scc?
5328 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
5329 .addReg(Reg)
5330 .addImm(0);
5331 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
5332 .addMBB(LoopBB);
5333 // clang-format on
5334
5335 return RemainderBB;
5336}
5337
5338// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
5339// wavefront. If the value is uniform and just happens to be in a VGPR, this
5340// will only do one iteration. In the worst case, this will loop 64 times.
5341//
5342// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
5345 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5346 const DebugLoc &DL, const MachineOperand &Idx,
5347 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
5348 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
5349 Register &SGPRIdxReg) {
5350
5351 MachineFunction *MF = OrigBB.getParent();
5352 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5353 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5356
5357 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
5358 Register PhiExec = MRI.createVirtualRegister(BoolRC);
5359 Register NewExec = MRI.createVirtualRegister(BoolRC);
5360 Register CurrentIdxReg =
5361 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5362 Register CondReg = MRI.createVirtualRegister(BoolRC);
5363
5364 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
5365 .addReg(InitReg)
5366 .addMBB(&OrigBB)
5367 .addReg(ResultReg)
5368 .addMBB(&LoopBB);
5369
5370 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
5371 .addReg(InitSaveExecReg)
5372 .addMBB(&OrigBB)
5373 .addReg(NewExec)
5374 .addMBB(&LoopBB);
5375
5376 // Read the next variant <- also loop target.
5377 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
5378 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
5379
5380 // Compare the just read M0 value to all possible Idx values.
5381 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
5382 .addReg(CurrentIdxReg)
5383 .addReg(Idx.getReg(), {}, Idx.getSubReg());
5384
5385 // Update EXEC, save the original EXEC value to VCC.
5386 BuildMI(LoopBB, I, DL, TII->get(LMC.AndSaveExecOpc), NewExec)
5387 .addReg(CondReg)
5388 .setOperandDead(3); // Dead scc
5389
5390 MRI.setSimpleHint(NewExec, CondReg);
5391
5392 if (UseGPRIdxMode) {
5393 if (Offset == 0) {
5394 SGPRIdxReg = CurrentIdxReg;
5395 } else {
5396 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5397 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
5398 .addReg(CurrentIdxReg)
5399 .addImm(Offset)
5400 .setOperandDead(3); // Dead scc
5401 }
5402 } else {
5403 // Move index from VCC into M0
5404 if (Offset == 0) {
5405 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::M0)
5406 .addReg(CurrentIdxReg);
5407 } else {
5408 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
5409 .addReg(CurrentIdxReg)
5410 .addImm(Offset)
5411 .setOperandDead(3); // Dead scc
5412 }
5413 }
5414
5415 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5417 BuildMI(LoopBB, I, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
5418 .addReg(LMC.ExecReg)
5419 .addReg(NewExec)
5420 .setOperandDead(3); // Dead scc
5421
5422 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
5423 // s_cbranch_scc0?
5424
5425 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
5426 // clang-format off
5427 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
5428 .addMBB(&LoopBB);
5429 // clang-format on
5430
5431 return InsertPt->getIterator();
5432}
5433
5434// This has slightly sub-optimal regalloc when the source vector is killed by
5435// the read. The register allocator does not understand that the kill is
5436// per-workitem, so is kept alive for the whole loop so we end up not re-using a
5437// subregister from it, using 1 more VGPR than necessary. This was saved when
5438// this was expanded after register allocation.
5441 unsigned InitResultReg, unsigned PhiReg, int Offset,
5442 bool UseGPRIdxMode, Register &SGPRIdxReg) {
5443 MachineFunction *MF = MBB.getParent();
5444 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5445 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5447 const DebugLoc &DL = MI.getDebugLoc();
5449
5450 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
5451 Register DstReg = MI.getOperand(0).getReg();
5452 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5453 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
5455
5456 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
5457
5458 // Save the EXEC mask
5459 // clang-format off
5460 BuildMI(MBB, I, DL, TII->get(LMC.MovOpc), SaveExec)
5461 .addReg(LMC.ExecReg);
5462 // clang-format on
5463
5464 auto [LoopBB, RemainderBB] = splitBlockForLoop(MI, MBB, false);
5465
5466 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5467
5468 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
5469 InitResultReg, DstReg, PhiReg, TmpExec,
5470 Offset, UseGPRIdxMode, SGPRIdxReg);
5471
5472 MachineBasicBlock *LandingPad = MF->CreateMachineBasicBlock();
5474 ++MBBI;
5475 MF->insert(MBBI, LandingPad);
5476 LoopBB->removeSuccessor(RemainderBB);
5477 LandingPad->addSuccessor(RemainderBB);
5478 LoopBB->addSuccessor(LandingPad);
5479 MachineBasicBlock::iterator First = LandingPad->begin();
5480 // clang-format off
5481 BuildMI(*LandingPad, First, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
5482 .addReg(SaveExec);
5483 // clang-format on
5484
5485 return InsPt;
5486}
5487
5488// Returns subreg index, offset
5489static std::pair<unsigned, int>
5491 const TargetRegisterClass *SuperRC, unsigned VecReg,
5492 int Offset) {
5493 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
5494
5495 // Skip out of bounds offsets, or else we would end up using an undefined
5496 // register.
5497 if (Offset >= NumElts || Offset < 0)
5498 return std::pair(AMDGPU::sub0, Offset);
5499
5500 return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
5501}
5502
5505 int Offset) {
5506 MachineBasicBlock *MBB = MI.getParent();
5507 const DebugLoc &DL = MI.getDebugLoc();
5509
5510 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5511
5512 assert(Idx->getReg() != AMDGPU::NoRegister);
5513
5514 if (Offset == 0) {
5515 // clang-format off
5516 BuildMI(*MBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::M0)
5517 .add(*Idx);
5518 // clang-format on
5519 } else {
5520 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
5521 .add(*Idx)
5522 .addImm(Offset)
5523 .setOperandDead(3); // Dead scc
5524 }
5525}
5526
5529 int Offset) {
5530 MachineBasicBlock *MBB = MI.getParent();
5531 const DebugLoc &DL = MI.getDebugLoc();
5533
5534 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5535
5536 if (Offset == 0)
5537 return Idx->getReg();
5538
5539 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5540 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
5541 .add(*Idx)
5542 .addImm(Offset)
5543 .setOperandDead(3); // Dead scc
5544 return Tmp;
5545}
5546
5549 const GCNSubtarget &ST) {
5550 const SIInstrInfo *TII = ST.getInstrInfo();
5551 const SIRegisterInfo &TRI = TII->getRegisterInfo();
5552 MachineFunction *MF = MBB.getParent();
5554
5555 Register Dst = MI.getOperand(0).getReg();
5556 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5557 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
5558 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
5559
5560 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
5561 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
5562
5563 unsigned SubReg;
5564 std::tie(SubReg, Offset) =
5565 computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
5566
5567 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
5568
5569 // Check for a SGPR index.
5570 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
5572 const DebugLoc &DL = MI.getDebugLoc();
5573
5574 if (UseGPRIdxMode) {
5575 // TODO: Look at the uses to avoid the copy. This may require rescheduling
5576 // to avoid interfering with other uses, so probably requires a new
5577 // optimization pass.
5579
5580 const MCInstrDesc &GPRIDXDesc =
5581 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
5582 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
5583 .addReg(SrcReg)
5584 .addReg(Idx)
5585 .addImm(SubReg);
5586 } else {
5588
5589 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
5590 .addReg(SrcReg, {}, SubReg)
5591 .addReg(SrcReg, RegState::Implicit);
5592 }
5593
5594 MI.eraseFromParent();
5595
5596 return &MBB;
5597 }
5598
5599 // Control flow needs to be inserted if indexing with a VGPR.
5600 const DebugLoc &DL = MI.getDebugLoc();
5602
5603 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5604 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5605
5606 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
5607
5608 Register SGPRIdxReg;
5609 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
5610 UseGPRIdxMode, SGPRIdxReg);
5611
5612 MachineBasicBlock *LoopBB = InsPt->getParent();
5613
5614 if (UseGPRIdxMode) {
5615 const MCInstrDesc &GPRIDXDesc =
5616 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
5617
5618 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
5619 .addReg(SrcReg)
5620 .addReg(SGPRIdxReg)
5621 .addImm(SubReg);
5622 } else {
5623 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
5624 .addReg(SrcReg, {}, SubReg)
5625 .addReg(SrcReg, RegState::Implicit);
5626 }
5627
5628 MI.eraseFromParent();
5629
5630 return LoopBB;
5631}
5632
5635 const GCNSubtarget &ST) {
5636 const SIInstrInfo *TII = ST.getInstrInfo();
5637 const SIRegisterInfo &TRI = TII->getRegisterInfo();
5638 MachineFunction *MF = MBB.getParent();
5640
5641 Register Dst = MI.getOperand(0).getReg();
5642 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
5643 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
5644 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
5645 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
5646 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
5647 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
5648
5649 // This can be an immediate, but will be folded later.
5650 assert(Val->getReg());
5651
5652 unsigned SubReg;
5653 std::tie(SubReg, Offset) =
5654 computeIndirectRegAndOffset(TRI, VecRC, SrcVec->getReg(), Offset);
5655 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
5656
5657 if (Idx->getReg() == AMDGPU::NoRegister) {
5659 const DebugLoc &DL = MI.getDebugLoc();
5660
5661 assert(Offset == 0);
5662
5663 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
5664 .add(*SrcVec)
5665 .add(*Val)
5666 .addImm(SubReg);
5667
5668 MI.eraseFromParent();
5669 return &MBB;
5670 }
5671
5672 // Check for a SGPR index.
5673 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
5675 const DebugLoc &DL = MI.getDebugLoc();
5676
5677 if (UseGPRIdxMode) {
5679
5680 const MCInstrDesc &GPRIDXDesc =
5681 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
5682 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
5683 .addReg(SrcVec->getReg())
5684 .add(*Val)
5685 .addReg(Idx)
5686 .addImm(SubReg);
5687 } else {
5689
5690 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
5691 TRI.getRegSizeInBits(*VecRC), 32, false);
5692 BuildMI(MBB, I, DL, MovRelDesc, Dst)
5693 .addReg(SrcVec->getReg())
5694 .add(*Val)
5695 .addImm(SubReg);
5696 }
5697 MI.eraseFromParent();
5698 return &MBB;
5699 }
5700
5701 // Control flow needs to be inserted if indexing with a VGPR.
5702 const DebugLoc &DL = MI.getDebugLoc();
5703
5704 Register PhiReg = MRI.createVirtualRegister(VecRC);
5705
5706 Register SGPRIdxReg;
5707 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
5708 UseGPRIdxMode, SGPRIdxReg);
5709 MachineBasicBlock *LoopBB = InsPt->getParent();
5710
5711 if (UseGPRIdxMode) {
5712 const MCInstrDesc &GPRIDXDesc =
5713 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
5714
5715 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
5716 .addReg(PhiReg)
5717 .add(*Val)
5718 .addReg(SGPRIdxReg)
5719 .addImm(SubReg);
5720 } else {
5721 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
5722 TRI.getRegSizeInBits(*VecRC), 32, false);
5723 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
5724 .addReg(PhiReg)
5725 .add(*Val)
5726 .addImm(SubReg);
5727 }
5728
5729 MI.eraseFromParent();
5730 return LoopBB;
5731}
5732
5734 MachineBasicBlock *BB) {
5735 // For targets older than GFX12, we emit a sequence of 32-bit operations.
5736 // For GFX12, we emit s_add_u64 and s_sub_u64.
5737 MachineFunction *MF = BB->getParent();
5738 const SIInstrInfo *TII = MF->getSubtarget<GCNSubtarget>().getInstrInfo();
5739 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5741 const DebugLoc &DL = MI.getDebugLoc();
5742 MachineOperand &Dest = MI.getOperand(0);
5743 MachineOperand &Src0 = MI.getOperand(1);
5744 MachineOperand &Src1 = MI.getOperand(2);
5745 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
5746 if (ST.hasScalarAddSub64()) {
5747 // FIXME: If scc is used, this deletes the def
5748 unsigned Opc = IsAdd ? AMDGPU::S_ADD_U64 : AMDGPU::S_SUB_U64;
5749 // clang-format off
5750 BuildMI(*BB, MI, DL, TII->get(Opc), Dest.getReg())
5751 .add(Src0)
5752 .add(Src1);
5753 // clang-format on
5754 } else {
5755 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5756 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
5757
5758 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5759 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
5760
5761 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5762 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
5763 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5764 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
5765
5766 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5767 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
5768 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5769 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
5770
5771 const MachineOperand &ImpDefSCC = MI.getOperand(3);
5772 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
5773
5774 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
5775 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
5776 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
5777 auto Hi = BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
5778 .add(Src0Sub1)
5779 .add(Src1Sub1);
5780 if (ImpDefSCC.isDead())
5781 Hi.setOperandDead(3);
5782 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
5783 .addReg(DestSub0)
5784 .addImm(AMDGPU::sub0)
5785 .addReg(DestSub1)
5786 .addImm(AMDGPU::sub1);
5787 }
5788 MI.eraseFromParent();
5789 return BB;
5790}
5791
5793 MachineFunction *MF = BB->getParent();
5794 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5795 const SIInstrInfo *TII = ST.getInstrInfo();
5796 const SIRegisterInfo *TRI = ST.getRegisterInfo();
5798 const DebugLoc &DL = MI.getDebugLoc();
5799 Register Dst = MI.getOperand(0).getReg();
5800 const MachineOperand &Src0 = MI.getOperand(1);
5801 const MachineOperand &Src1 = MI.getOperand(2);
5802 Register SrcCond = MI.getOperand(3).getReg();
5803
5804 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5805 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5806 const TargetRegisterClass *CondRC = TRI->getWaveMaskRegClass();
5807 Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
5808
5809 int Src0Idx =
5810 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
5811 int Src1Idx =
5812 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
5813 const TargetRegisterClass *Src0RC =
5814 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), Src0Idx));
5815 const TargetRegisterClass *Src1RC =
5816 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), Src1Idx));
5817
5818 const TargetRegisterClass *Src0SubRC =
5819 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
5820 const TargetRegisterClass *Src1SubRC =
5821 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
5822
5823 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5824 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
5825 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5826 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
5827
5828 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5829 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
5830 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5831 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
5832
5833 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy).addReg(SrcCond);
5834 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
5835 .addImm(0)
5836 .add(Src0Sub0)
5837 .addImm(0)
5838 .add(Src1Sub0)
5839 .addReg(SrcCondCopy);
5840
5841 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
5842 .addImm(0)
5843 .add(Src0Sub1)
5844 .addImm(0)
5845 .add(Src1Sub1)
5846 .addReg(SrcCondCopy);
5847
5848 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
5849 .addReg(DstLo)
5850 .addImm(AMDGPU::sub0)
5851 .addReg(DstHi)
5852 .addImm(AMDGPU::sub1);
5853 MI.eraseFromParent();
5854}
5855
5857 switch (Opc) {
5858 case AMDGPU::S_MIN_U32:
5859 return std::numeric_limits<uint32_t>::max();
5860 case AMDGPU::S_MIN_I32:
5861 return std::numeric_limits<int32_t>::max();
5862 case AMDGPU::S_MAX_U32:
5863 return std::numeric_limits<uint32_t>::min();
5864 case AMDGPU::S_MAX_I32:
5865 return std::numeric_limits<int32_t>::min();
5866 case AMDGPU::V_ADD_F32_e64: // -0.0
5867 return 0x80000000;
5868 case AMDGPU::V_SUB_F32_e64: // +0.0
5869 return 0x0;
5870 case AMDGPU::S_ADD_I32:
5871 case AMDGPU::S_SUB_I32:
5872 case AMDGPU::S_OR_B32:
5873 case AMDGPU::S_XOR_B32:
5874 return std::numeric_limits<uint32_t>::min();
5875 case AMDGPU::S_AND_B32:
5876 return std::numeric_limits<uint32_t>::max();
5877 case AMDGPU::V_MIN_F32_e64:
5878 case AMDGPU::V_MAX_F32_e64:
5879 return 0x7fc00000; // qNAN
5880 case AMDGPU::V_CMP_LT_U64_e64: // umin.u64
5881 return std::numeric_limits<uint64_t>::max();
5882 case AMDGPU::V_CMP_LT_I64_e64: // min.i64
5883 return std::numeric_limits<int64_t>::max();
5884 case AMDGPU::V_CMP_GT_U64_e64: // umax.u64
5885 return std::numeric_limits<uint64_t>::min();
5886 case AMDGPU::V_CMP_GT_I64_e64: // max.i64
5887 return std::numeric_limits<int64_t>::min();
5888 case AMDGPU::V_MIN_F64_e64:
5889 case AMDGPU::V_MAX_F64_e64:
5890 case AMDGPU::V_MIN_NUM_F64_e64:
5891 case AMDGPU::V_MAX_NUM_F64_e64:
5892 return 0x7FF8000000000000; // qNAN
5893 case AMDGPU::S_ADD_U64_PSEUDO:
5894 case AMDGPU::S_SUB_U64_PSEUDO:
5895 case AMDGPU::S_OR_B64:
5896 case AMDGPU::S_XOR_B64:
5897 return std::numeric_limits<uint64_t>::min();
5898 case AMDGPU::S_AND_B64:
5899 return std::numeric_limits<uint64_t>::max();
5900 case AMDGPU::V_ADD_F64_e64:
5901 case AMDGPU::V_ADD_F64_pseudo_e64:
5902 return 0x8000000000000000; // -0.0
5903 default:
5904 llvm_unreachable("Unexpected opcode in getIdentityValueForWaveReduction");
5905 }
5906}
5907
5908static bool is32bitWaveReduceOperation(unsigned Opc) {
5909 return Opc == AMDGPU::S_MIN_U32 || Opc == AMDGPU::S_MIN_I32 ||
5910 Opc == AMDGPU::S_MAX_U32 || Opc == AMDGPU::S_MAX_I32 ||
5911 Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32 ||
5912 Opc == AMDGPU::S_AND_B32 || Opc == AMDGPU::S_OR_B32 ||
5913 Opc == AMDGPU::S_XOR_B32 || Opc == AMDGPU::V_MIN_F32_e64 ||
5914 Opc == AMDGPU::V_MAX_F32_e64 || Opc == AMDGPU::V_ADD_F32_e64 ||
5915 Opc == AMDGPU::V_SUB_F32_e64;
5916}
5917
5919 return Opc == AMDGPU::V_MIN_F32_e64 || Opc == AMDGPU::V_MAX_F32_e64 ||
5920 Opc == AMDGPU::V_ADD_F32_e64 || Opc == AMDGPU::V_SUB_F32_e64 ||
5921 Opc == AMDGPU::V_MIN_F64_e64 || Opc == AMDGPU::V_MAX_F64_e64 ||
5922 Opc == AMDGPU::V_MIN_NUM_F64_e64 || Opc == AMDGPU::V_MAX_NUM_F64_e64 ||
5923 Opc == AMDGPU::V_ADD_F64_e64 || Opc == AMDGPU::V_ADD_F64_pseudo_e64;
5924}
5925
5926static std::tuple<unsigned, unsigned>
5928 unsigned DPPOpc;
5929 switch (Opc) {
5930 case AMDGPU::S_MIN_U32:
5931 DPPOpc = AMDGPU::V_MIN_U32_dpp;
5932 break;
5933 case AMDGPU::S_MIN_I32:
5934 DPPOpc = AMDGPU::V_MIN_I32_dpp;
5935 break;
5936 case AMDGPU::S_MAX_U32:
5937 DPPOpc = AMDGPU::V_MAX_U32_dpp;
5938 break;
5939 case AMDGPU::S_MAX_I32:
5940 DPPOpc = AMDGPU::V_MAX_I32_dpp;
5941 break;
5942 case AMDGPU::S_ADD_I32:
5943 case AMDGPU::S_SUB_I32:
5944 DPPOpc = ST.hasAddNoCarryInsts() ? AMDGPU::V_ADD_U32_dpp
5945 : AMDGPU::V_ADD_CO_U32_dpp;
5946 break;
5947 case AMDGPU::S_AND_B32:
5948 DPPOpc = AMDGPU::V_AND_B32_dpp;
5949 break;
5950 case AMDGPU::S_OR_B32:
5951 DPPOpc = AMDGPU::V_OR_B32_dpp;
5952 break;
5953 case AMDGPU::S_XOR_B32:
5954 DPPOpc = AMDGPU::V_XOR_B32_dpp;
5955 break;
5956 case AMDGPU::V_ADD_F32_e64:
5957 case AMDGPU::V_SUB_F32_e64:
5958 DPPOpc = AMDGPU::V_ADD_F32_dpp;
5959 break;
5960 case AMDGPU::V_MIN_F32_e64:
5961 DPPOpc = AMDGPU::V_MIN_F32_dpp;
5962 break;
5963 case AMDGPU::V_MAX_F32_e64:
5964 DPPOpc = AMDGPU::V_MAX_F32_dpp;
5965 break;
5966 case AMDGPU::V_CMP_LT_U64_e64: // umin.u64
5967 case AMDGPU::V_CMP_LT_I64_e64: // min.i64
5968 case AMDGPU::V_CMP_GT_U64_e64: // umax.u64
5969 case AMDGPU::V_CMP_GT_I64_e64: // max.i64
5970 case AMDGPU::S_ADD_U64_PSEUDO:
5971 case AMDGPU::S_SUB_U64_PSEUDO:
5972 case AMDGPU::S_AND_B64:
5973 case AMDGPU::S_OR_B64:
5974 case AMDGPU::S_XOR_B64:
5975 case AMDGPU::V_MIN_NUM_F64_e64:
5976 case AMDGPU::V_MIN_F64_e64:
5977 case AMDGPU::V_MAX_NUM_F64_e64:
5978 case AMDGPU::V_MAX_F64_e64:
5979 case AMDGPU::V_ADD_F64_pseudo_e64:
5980 case AMDGPU::V_ADD_F64_e64:
5981 DPPOpc = AMDGPU::V_MOV_B64_DPP_PSEUDO;
5982 break;
5983 default:
5984 llvm_unreachable("unhandled lane op");
5985 }
5986 unsigned ClampOpc = Opc;
5987 if (Opc == AMDGPU::V_SUB_F32_e64)
5988 ClampOpc = AMDGPU::V_ADD_F32_e64;
5989 if (!ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/false)) {
5990 if (Opc == AMDGPU::S_SUB_I32)
5991 ClampOpc = AMDGPU::S_ADD_I32;
5992 if (Opc == AMDGPU::S_ADD_U64_PSEUDO || Opc == AMDGPU::S_SUB_U64_PSEUDO)
5993 ClampOpc = AMDGPU::V_ADD_CO_U32_e64;
5994 else if (Opc == AMDGPU::S_AND_B64)
5995 ClampOpc = AMDGPU::V_AND_B32_e64;
5996 else if (Opc == AMDGPU::S_OR_B64)
5997 ClampOpc = AMDGPU::V_OR_B32_e64;
5998 else if (Opc == AMDGPU::S_XOR_B64)
5999 ClampOpc = AMDGPU::V_XOR_B32_e64;
6000 else
6001 ClampOpc = ST.getInstrInfo()->getVALUOp(ClampOpc);
6002 }
6003 return {DPPOpc, ClampOpc};
6004}
6005
6006static std::pair<Register, Register>
6008 const TargetRegisterClass *SrcRC, const GCNSubtarget &ST,
6010 const SIRegisterInfo *TRI = ST.getRegisterInfo();
6011 const SIInstrInfo *TII = ST.getInstrInfo();
6012 const TargetRegisterClass *SrcSubRC =
6013 TRI->getSubRegisterClass(SrcRC, AMDGPU::sub0);
6014 Register Op1L =
6015 TII->buildExtractSubReg(MI, MRI, Op, SrcRC, AMDGPU::sub0, SrcSubRC);
6016 Register Op1H =
6017 TII->buildExtractSubReg(MI, MRI, Op, SrcRC, AMDGPU::sub1, SrcSubRC);
6018 return {Op1L, Op1H};
6019}
6020
6023 const GCNSubtarget &ST,
6024 unsigned Opc) {
6026 const SIRegisterInfo *TRI = ST.getRegisterInfo();
6027 const DebugLoc &DL = MI.getDebugLoc();
6028 const SIInstrInfo *TII = ST.getInstrInfo();
6029
6030 // Reduction operations depend on whether the input operand is SGPR or VGPR.
6031 Register SrcReg = MI.getOperand(1).getReg();
6032 bool isSGPR = TRI->isSGPRClass(MRI.getRegClass(SrcReg));
6033 Register DstReg = MI.getOperand(0).getReg();
6034 unsigned Stratergy = static_cast<unsigned>(MI.getOperand(2).getImm());
6035 enum WAVE_REDUCE_STRATEGY : unsigned { DEFAULT = 0, ITERATIVE = 1, DPP = 2 };
6036 MachineBasicBlock *RetBB = nullptr;
6037 unsigned MIOpc = MI.getOpcode();
6038 auto BuildRegSequence = [&](MachineBasicBlock &BB,
6040 Register Src0, Register Src1) {
6041 auto RegSequence =
6042 BuildMI(BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dst)
6043 .addReg(Src0)
6044 .addImm(AMDGPU::sub0)
6045 .addReg(Src1)
6046 .addImm(AMDGPU::sub1);
6047 return RegSequence;
6048 };
6049 if (isSGPR) {
6050 switch (Opc) {
6051 case AMDGPU::S_MIN_U32:
6052 case AMDGPU::S_MIN_I32:
6053 case AMDGPU::V_MIN_F32_e64:
6054 case AMDGPU::S_MAX_U32:
6055 case AMDGPU::S_MAX_I32:
6056 case AMDGPU::V_MAX_F32_e64:
6057 case AMDGPU::S_AND_B32:
6058 case AMDGPU::S_OR_B32: {
6059 // Idempotent operations.
6060 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg).addReg(SrcReg);
6061 RetBB = &BB;
6062 break;
6063 }
6064 case AMDGPU::V_CMP_LT_U64_e64: // umin
6065 case AMDGPU::V_CMP_LT_I64_e64: // min
6066 case AMDGPU::V_CMP_GT_U64_e64: // umax
6067 case AMDGPU::V_CMP_GT_I64_e64: // max
6068 case AMDGPU::V_MIN_F64_e64:
6069 case AMDGPU::V_MIN_NUM_F64_e64:
6070 case AMDGPU::V_MAX_F64_e64:
6071 case AMDGPU::V_MAX_NUM_F64_e64:
6072 case AMDGPU::S_AND_B64:
6073 case AMDGPU::S_OR_B64: {
6074 // Idempotent operations.
6075 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B64), DstReg).addReg(SrcReg);
6076 RetBB = &BB;
6077 break;
6078 }
6079 case AMDGPU::S_XOR_B32:
6080 case AMDGPU::S_XOR_B64:
6081 case AMDGPU::S_ADD_I32:
6082 case AMDGPU::S_ADD_U64_PSEUDO:
6083 case AMDGPU::V_ADD_F32_e64:
6084 case AMDGPU::V_ADD_F64_e64:
6085 case AMDGPU::V_ADD_F64_pseudo_e64:
6086 case AMDGPU::S_SUB_I32:
6087 case AMDGPU::S_SUB_U64_PSEUDO:
6088 case AMDGPU::V_SUB_F32_e64: {
6089 const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
6090 const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
6091 Register ExecMask = MRI.createVirtualRegister(WaveMaskRegClass);
6092 Register NumActiveLanes =
6093 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6094
6095 bool IsWave32 = ST.isWave32();
6096 unsigned MovOpc = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
6097 MCRegister ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6098 unsigned BitCountOpc =
6099 IsWave32 ? AMDGPU::S_BCNT1_I32_B32 : AMDGPU::S_BCNT1_I32_B64;
6100
6101 BuildMI(BB, MI, DL, TII->get(MovOpc), ExecMask).addReg(ExecReg);
6102
6103 auto NewAccumulator =
6104 BuildMI(BB, MI, DL, TII->get(BitCountOpc), NumActiveLanes)
6105 .addReg(ExecMask)
6106 .setOperandDead(2); // Dead scc
6107
6108 switch (Opc) {
6109 case AMDGPU::S_XOR_B32:
6110 case AMDGPU::S_XOR_B64: {
6111 // Performing an XOR operation on a uniform value
6112 // depends on the parity of the number of active lanes.
6113 // For even parity, the result will be 0, for odd
6114 // parity the result will be the same as the input value.
6115 Register ParityRegister =
6116 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6117 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_AND_B32), ParityRegister)
6118 .addReg(NewAccumulator->getOperand(0).getReg())
6119 .addImm(1)
6120 .setOperandDead(3); // Dead scc
6121 // Check if Src is a known identity constant.
6122 if (TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6123 // 1 * parity(exec) = parity(exec)
6124 if (Opc == AMDGPU::S_XOR_B32) {
6125 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg)
6126 .addReg(ParityRegister);
6127 } else {
6128 Register DstHi =
6129 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6130 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstHi).addImm(0);
6131 BuildRegSequence(BB, MI, DstReg, ParityRegister, DstHi);
6132 }
6133 break;
6134 }
6135 if (Opc == AMDGPU::S_XOR_B32) {
6136 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6137 .addReg(SrcReg)
6138 .addReg(ParityRegister);
6139 } else {
6140 Register DestSub0 =
6141 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6142 Register DestSub1 =
6143 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6144 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6145 MRI.getRegClass(SrcReg), ST, MRI);
6146 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub0)
6147 .addReg(Op1L)
6148 .addReg(ParityRegister);
6149 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub1)
6150 .addReg(Op1H)
6151 .addReg(ParityRegister);
6152 BuildRegSequence(BB, MI, DstReg, DestSub0, DestSub1);
6153 }
6154 break;
6155 }
6156 case AMDGPU::S_SUB_I32: {
6157 Register NegatedVal = MRI.createVirtualRegister(DstRegClass);
6158 // Take the negation of the source operand.
6159 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedVal)
6160 .addImm(0)
6161 .addReg(SrcReg)
6162 .setOperandDead(3); // Dead scc
6163 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6164 .addReg(NegatedVal)
6165 .addReg(NewAccumulator->getOperand(0).getReg());
6166 break;
6167 }
6168 case AMDGPU::S_ADD_I32: {
6169 // Check if Src is a known identity constant.
6170 if (TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6171 // 1 * bitcount(exec) = bitcount(exec)
6172 BuildMI(BB, MI, DL, TII->get(AMDGPU::COPY), DstReg)
6173 .addReg(NewAccumulator->getOperand(0).getReg());
6174 break;
6175 }
6176 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DstReg)
6177 .addReg(SrcReg)
6178 .addReg(NewAccumulator->getOperand(0).getReg());
6179 break;
6180 }
6181 case AMDGPU::S_ADD_U64_PSEUDO:
6182 case AMDGPU::S_SUB_U64_PSEUDO: {
6183 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6184 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6185 Register Op1H_Op0L_Reg =
6186 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6187 Register Op1L_Op0H_Reg =
6188 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6189 Register CarryReg =
6190 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6191 Register AddReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6192 Register NegatedValLo =
6193 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6194 Register NegatedValHi =
6195 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6196 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6197 MRI.getRegClass(SrcReg), ST, MRI);
6198 // Check if Src is a known identity constant.
6199 if (Opc == AMDGPU::S_ADD_U64_PSEUDO &&
6200 TII->getImmOrMaterializedImm(MRI, SrcReg) == 1) {
6201 // 1 * bitcount(exec) = bitcount(exec)
6202 Register DstHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6203 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstHi).addImm(0);
6204 BuildRegSequence(BB, MI, DstReg,
6205 NewAccumulator->getOperand(0).getReg(), DstHi);
6206 break;
6207 }
6208 if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6209 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedValLo)
6210 .addImm(0)
6211 .addReg(NewAccumulator->getOperand(0).getReg())
6212 .setOperandDead(3); // Dead scc
6213 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ASHR_I32), NegatedValHi)
6214 .addReg(NegatedValLo)
6215 .addImm(31)
6216 .setOperandDead(3); // Dead scc
6217 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), Op1L_Op0H_Reg)
6218 .addReg(Op1L)
6219 .addReg(NegatedValHi);
6220 }
6221 Register LowOpcode = Opc == AMDGPU::S_SUB_U64_PSEUDO
6222 ? NegatedValLo
6223 : NewAccumulator->getOperand(0).getReg();
6224 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), DestSub0)
6225 .addReg(Op1L)
6226 .addReg(LowOpcode);
6227 if (ST.hasScalarMulHiInsts()) {
6228 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_HI_U32), CarryReg)
6229 .addReg(Op1L)
6230 .addReg(LowOpcode);
6231 } else {
6232 Register VCarryReg =
6233 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6234 Register LowOpVGPR =
6235 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6236 BuildMI(BB, MI, DL, TII->get(AMDGPU::COPY), LowOpVGPR)
6237 .addReg(LowOpcode);
6238 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_MUL_HI_U32_e64), VCarryReg)
6239 .addReg(Op1L)
6240 .addReg(LowOpVGPR);
6241 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CarryReg)
6242 .addReg(VCarryReg);
6243 }
6244 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MUL_I32), Op1H_Op0L_Reg)
6245 .addReg(Op1H)
6246 .addReg(LowOpcode);
6247
6248 Register HiVal = Opc == AMDGPU::S_SUB_U64_PSEUDO ? AddReg : DestSub1;
6249 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ADD_U32), HiVal)
6250 .addReg(CarryReg)
6251 .addReg(Op1H_Op0L_Reg)
6252 .setOperandDead(3); // Dead scc
6253
6254 if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6255 BuildMI(BB, MI, DL, TII->get(AMDGPU::S_ADD_U32), DestSub1)
6256 .addReg(HiVal)
6257 .addReg(Op1L_Op0H_Reg)
6258 .setOperandDead(3); // Dead scc
6259 }
6260 BuildRegSequence(BB, MI, DstReg, DestSub0, DestSub1);
6261 break;
6262 }
6263 case AMDGPU::V_ADD_F32_e64:
6264 case AMDGPU::V_ADD_F64_e64:
6265 case AMDGPU::V_ADD_F64_pseudo_e64:
6266 case AMDGPU::V_SUB_F32_e64: {
6267 bool is32BitOpc = is32bitWaveReduceOperation(Opc);
6268 const TargetRegisterClass *VregRC = TII->getRegClass(TII->get(Opc), 0);
6269 Register ActiveLanesVreg = MRI.createVirtualRegister(VregRC);
6270 Register DstVreg = MRI.createVirtualRegister(VregRC);
6271 // Get number of active lanes as a float val.
6272 BuildMI(BB, MI, DL,
6273 TII->get(is32BitOpc ? AMDGPU::V_CVT_F32_I32_e64
6274 : AMDGPU::V_CVT_F64_I32_e64),
6275 ActiveLanesVreg)
6276 .addReg(NewAccumulator->getOperand(0).getReg())
6277 .addImm(0) // clamp
6278 .addImm(0); // output-modifier
6279
6280 // Take negation of input for SUB reduction
6281 unsigned srcMod = (MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32 ||
6282 MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64)
6285 unsigned MulOpc = is32BitOpc ? AMDGPU::V_MUL_F32_e64
6286 : ST.getGeneration() >= AMDGPUSubtarget::GFX12
6287 ? AMDGPU::V_MUL_F64_pseudo_e64
6288 : AMDGPU::V_MUL_F64_e64;
6289 auto DestVregInst = BuildMI(BB, MI, DL, TII->get(MulOpc),
6290 DstVreg)
6291 .addImm(srcMod) // src0 modifier
6292 .addReg(SrcReg)
6293 .addImm(SISrcMods::NONE) // src1 modifier
6294 .addReg(ActiveLanesVreg)
6295 .addImm(SISrcMods::NONE) // clamp
6296 .addImm(SISrcMods::NONE); // output-mod
6297 if (is32BitOpc) {
6298 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
6299 .addReg(DstVreg);
6300 } else {
6301 Register LaneValueLoReg =
6302 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6303 Register LaneValueHiReg =
6304 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6305 auto [Op1L, Op1H] =
6306 ExtractSubRegs(MI, DestVregInst->getOperand(0), VregRC, ST, MRI);
6307 // lane value input should be in an sgpr
6308 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6309 LaneValueLoReg)
6310 .addReg(Op1L);
6311 BuildMI(BB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6312 LaneValueHiReg)
6313 .addReg(Op1H);
6314 NewAccumulator =
6315 BuildRegSequence(BB, MI, DstReg, LaneValueLoReg, LaneValueHiReg);
6316 }
6317 }
6318 }
6319 RetBB = &BB;
6320 }
6321 }
6322 } else {
6324 Register SrcReg = MI.getOperand(1).getReg();
6325 bool is32BitOpc = is32bitWaveReduceOperation(Opc);
6327 bool NeedsMovDPP = !is32BitOpc;
6328 // Create virtual registers required for lowering.
6329 const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
6330 const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
6331 const TargetRegisterClass *SrcRegClass = MRI.getRegClass(SrcReg);
6332 bool IsWave32 = ST.isWave32();
6333 unsigned MovOpcForExec = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
6334 unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6335 if (Stratergy == WAVE_REDUCE_STRATEGY::ITERATIVE ||
6336 !ST.hasDPP()) { // If target doesn't support DPP operations, default to
6337 // iterative stratergy
6338
6339 // To reduce the VGPR using iterative approach, we need to iterate
6340 // over all the active lanes. Lowering consists of ComputeLoop,
6341 // which iterate over only active lanes. We use copy of EXEC register
6342 // as induction variable and every active lane modifies it using bitset0
6343 // so that we will get the next active lane for next iteration.
6344
6345 // Create Control flow for loop
6346 // Split MI's Machine Basic block into For loop
6347 auto [ComputeLoop, ComputeEnd] = splitBlockForLoop(MI, BB, true);
6348
6349 Register LoopIterator = MRI.createVirtualRegister(WaveMaskRegClass);
6350 Register IdentityValReg = MRI.createVirtualRegister(DstRegClass);
6351 Register AccumulatorReg = MRI.createVirtualRegister(DstRegClass);
6352 Register ActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
6353 Register NewActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
6354 Register FF1Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6355 Register LaneValueReg = MRI.createVirtualRegister(DstRegClass);
6356
6357 // Create initial values of induction variable from Exec, Accumulator and
6358 // insert branch instr to newly created ComputeBlock
6359 BuildMI(BB, I, DL, TII->get(MovOpcForExec), LoopIterator).addReg(ExecReg);
6360 uint64_t IdentityValue =
6361 MI.getOpcode() == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64
6362 ? 0x0 // +0.0 for double sub reduction
6364 BuildMI(BB, I, DL,
6365 TII->get(is32BitOpc ? AMDGPU::S_MOV_B32
6366 : AMDGPU::S_MOV_B64_IMM_PSEUDO),
6367 IdentityValReg)
6368 .addImm(IdentityValue);
6369 // clang-format off
6370 BuildMI(BB, I, DL, TII->get(AMDGPU::S_BRANCH))
6371 .addMBB(ComputeLoop);
6372 // clang-format on
6373
6374 // Start constructing ComputeLoop
6375 I = ComputeLoop->begin();
6376 auto Accumulator =
6377 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), AccumulatorReg)
6378 .addReg(IdentityValReg)
6379 .addMBB(&BB);
6380 auto ActiveBits =
6381 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), ActiveBitsReg)
6382 .addReg(LoopIterator)
6383 .addMBB(&BB);
6384
6385 I = ComputeLoop->end();
6386 MachineInstr *NewAccumulator;
6387 // Perform the computations
6388 unsigned SFFOpc =
6389 IsWave32 ? AMDGPU::S_FF1_I32_B32 : AMDGPU::S_FF1_I32_B64;
6390 BuildMI(*ComputeLoop, I, DL, TII->get(SFFOpc), FF1Reg)
6391 .addReg(ActiveBitsReg);
6392 if (is32BitOpc) {
6393 Register OpDstReg = DstReg;
6394 bool hasSrc0Modifier = AMDGPU::getNamedOperandIdx(
6395 Opc, AMDGPU::OpName::src0_modifiers) != -1;
6396 bool hasSrc1Modifier = AMDGPU::getNamedOperandIdx(
6397 Opc, AMDGPU::OpName::src1_modifiers) != -1;
6398 bool hasClamp =
6399 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp) != -1;
6400 bool hasOpSel =
6401 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel) != -1;
6402 bool hasOMod =
6403 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod) != -1;
6404 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6405 LaneValueReg)
6406 .addReg(SrcReg)
6407 .addReg(FF1Reg);
6408 if (ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/false)) {
6409 // Get the Lane Value in VGPR to avoid the Constant Bus Restriction
6410 Register LaneValVgpr = MRI.createVirtualRegister(SrcRegClass);
6411 Register VgprResultReg = MRI.createVirtualRegister(SrcRegClass);
6412 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::COPY), LaneValVgpr)
6413 .addReg(LaneValueReg);
6414 OpDstReg = VgprResultReg;
6415 LaneValueReg = LaneValVgpr;
6416 }
6417 auto OpInstr = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), OpDstReg);
6418 if (hasSrc0Modifier)
6419 OpInstr.addImm(SISrcMods::NONE); // src0 modifier
6420 OpInstr.addReg(AccumulatorReg); // src0
6421 if (hasSrc1Modifier)
6422 OpInstr.addImm(SISrcMods::NONE); // src1 modifier
6423 OpInstr.addReg(LaneValueReg); // src1
6424 if (hasClamp)
6425 OpInstr.addImm(0); // clamp
6426 if (hasOpSel)
6427 OpInstr.addImm(0); // opsel
6428 if (hasOMod)
6429 OpInstr.addImm(0); // omod
6430 if (TII->isSALU(Opc))
6431 OpInstr.setOperandDead(3); // Dead scc
6432 if (ST.getInstrInfo()->isVALU(Opc, /*AllowLDSDMA=*/false)) {
6433 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
6434 DstReg)
6435 .addReg(OpDstReg);
6436 }
6437 } else {
6438 Register LaneValueLoReg =
6439 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6440 Register LaneValueHiReg =
6441 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6442 Register LaneValReg =
6443 MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6444 auto [Op1L, Op1H] = ExtractSubRegs(MI, MI.getOperand(1),
6445 MRI.getRegClass(SrcReg), ST, MRI);
6446 // lane value input should be in an sgpr
6447 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6448 LaneValueLoReg)
6449 .addReg(Op1L)
6450 .addReg(FF1Reg);
6451 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::V_READLANE_B32),
6452 LaneValueHiReg)
6453 .addReg(Op1H)
6454 .addReg(FF1Reg);
6455 auto LaneValue = BuildRegSequence(*ComputeLoop, I, LaneValReg,
6456 LaneValueLoReg, LaneValueHiReg);
6457 switch (Opc) {
6458 case AMDGPU::S_OR_B64:
6459 case AMDGPU::S_AND_B64:
6460 case AMDGPU::S_XOR_B64: {
6461 NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
6462 .addReg(Accumulator->getOperand(0).getReg())
6463 .addReg(LaneValue->getOperand(0).getReg())
6464 .setOperandDead(3); // Dead scc
6465 break;
6466 }
6467 case AMDGPU::V_CMP_GT_I64_e64:
6468 case AMDGPU::V_CMP_GT_U64_e64:
6469 case AMDGPU::V_CMP_LT_I64_e64:
6470 case AMDGPU::V_CMP_LT_U64_e64: {
6471 Register LaneMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6472 Register ComparisonResultReg =
6473 MRI.createVirtualRegister(WaveMaskRegClass);
6474 int SrcIdx =
6475 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src);
6476 const TargetRegisterClass *VregClass =
6477 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), SrcIdx));
6478 Register AccumulatorVReg = MRI.createVirtualRegister(VregClass);
6479 auto [SrcReg0Sub0, SrcReg0Sub1] = ExtractSubRegs(
6480 MI, Accumulator->getOperand(0), VregClass, ST, MRI);
6481 BuildRegSequence(*ComputeLoop, I, AccumulatorVReg, SrcReg0Sub0,
6482 SrcReg0Sub1);
6483 BuildMI(*ComputeLoop, I, DL, TII->get(Opc), LaneMaskReg)
6484 .addReg(LaneValue->getOperand(0).getReg())
6485 .addReg(AccumulatorVReg);
6486
6487 unsigned AndOpc = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6488 BuildMI(*ComputeLoop, I, DL, TII->get(AndOpc), ComparisonResultReg)
6489 .addReg(LaneMaskReg)
6490 .addReg(ActiveBitsReg);
6491
6492 NewAccumulator = BuildMI(*ComputeLoop, I, DL,
6493 TII->get(AMDGPU::S_CSELECT_B64), DstReg)
6494 .addReg(LaneValue->getOperand(0).getReg())
6495 .addReg(Accumulator->getOperand(0).getReg());
6496 break;
6497 }
6498 case AMDGPU::V_MIN_F64_e64:
6499 case AMDGPU::V_MIN_NUM_F64_e64:
6500 case AMDGPU::V_MAX_F64_e64:
6501 case AMDGPU::V_MAX_NUM_F64_e64:
6502 case AMDGPU::V_ADD_F64_e64:
6503 case AMDGPU::V_ADD_F64_pseudo_e64: {
6504 int SrcIdx =
6505 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src);
6506 const TargetRegisterClass *VregRC =
6507 TRI->getAllocatableClass(TII->getRegClass(MI.getDesc(), SrcIdx));
6508 Register AccumulatorVReg = MRI.createVirtualRegister(VregRC);
6509 Register DstVreg = MRI.createVirtualRegister(VregRC);
6510 Register LaneValLo =
6511 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6512 Register LaneValHi =
6513 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6514 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::COPY), AccumulatorVReg)
6515 .addReg(Accumulator->getOperand(0).getReg());
6516 unsigned Modifier =
6517 MI.getOpcode() == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64
6520 auto DstVregInst =
6521 BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstVreg)
6522 .addImm(Modifier) // src0 modifiers
6523 .addReg(LaneValue->getOperand(0).getReg())
6524 .addImm(SISrcMods::NONE) // src1 modifiers
6525 .addReg(AccumulatorVReg)
6526 .addImm(SISrcMods::NONE) // clamp
6527 .addImm(SISrcMods::NONE); // omod
6528 auto ReadLaneLo =
6529 BuildMI(*ComputeLoop, I, DL,
6530 TII->get(AMDGPU::V_READFIRSTLANE_B32), LaneValLo);
6531 auto ReadLaneHi =
6532 BuildMI(*ComputeLoop, I, DL,
6533 TII->get(AMDGPU::V_READFIRSTLANE_B32), LaneValHi);
6534 MachineBasicBlock::iterator Iters = *ReadLaneLo;
6535 auto [Op1L, Op1H] = ExtractSubRegs(*Iters, DstVregInst->getOperand(0),
6536 VregRC, ST, MRI);
6537 ReadLaneLo.addReg(Op1L);
6538 ReadLaneHi.addReg(Op1H);
6539 NewAccumulator =
6540 BuildRegSequence(*ComputeLoop, I, DstReg, LaneValLo, LaneValHi);
6541 break;
6542 }
6543 case AMDGPU::S_ADD_U64_PSEUDO:
6544 case AMDGPU::S_SUB_U64_PSEUDO: {
6545 NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
6546 .addReg(Accumulator->getOperand(0).getReg())
6547 .addReg(LaneValue->getOperand(0).getReg())
6548 .setOperandDead(3); // Dead scc
6549 ComputeLoop =
6550 expand64BitScalarArithmetic(*NewAccumulator, ComputeLoop);
6551 break;
6552 }
6553 }
6554 }
6555 // Manipulate the iterator to get the next active lane
6556 unsigned BITSETOpc =
6557 IsWave32 ? AMDGPU::S_BITSET0_B32 : AMDGPU::S_BITSET0_B64;
6558 BuildMI(*ComputeLoop, I, DL, TII->get(BITSETOpc), NewActiveBitsReg)
6559 .addReg(FF1Reg)
6560 .addReg(ActiveBitsReg);
6561
6562 // Add phi nodes
6563 Accumulator.addReg(DstReg).addMBB(ComputeLoop);
6564 ActiveBits.addReg(NewActiveBitsReg).addMBB(ComputeLoop);
6565
6566 // Creating branching
6567 MachineInstrBuilder SetSCCInstr;
6568 if (!ST.hasScalarCompareEq64()) {
6569 // For targets <= gfx7, use an S_OR_B32/B64 instruction to set SCC.
6570 Register LaneMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6571 unsigned CMPOpc = IsWave32 ? AMDGPU::S_OR_B32 : AMDGPU::S_OR_B64;
6572 SetSCCInstr =
6573 BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc), LaneMaskReg);
6574 } else {
6575 unsigned CMPOpc =
6576 IsWave32 ? AMDGPU::S_CMP_LG_U32 : AMDGPU::S_CMP_LG_U64;
6577 SetSCCInstr = BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc));
6578 }
6579 SetSCCInstr.addReg(NewActiveBitsReg);
6580 if (ST.hasScalarCompareEq64())
6581 SetSCCInstr.addImm(0);
6582 else
6583 SetSCCInstr.addReg(NewActiveBitsReg);
6584 BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
6585 .addMBB(ComputeLoop);
6586
6587 RetBB = ComputeEnd;
6588 } else {
6589 assert(ST.hasDPP() && "Sub Target does not support DPP Operations");
6590 MachineBasicBlock *CurrBB = &BB;
6591 Register SrcWithIdentity = MRI.createVirtualRegister(SrcRegClass);
6592 Register IdentityVGPR = MRI.createVirtualRegister(SrcRegClass);
6593 Register IdentitySGPR = MRI.createVirtualRegister(DstRegClass);
6594 Register DPPRowShr1 = MRI.createVirtualRegister(SrcRegClass);
6595 Register DPPRowShr2 = MRI.createVirtualRegister(SrcRegClass);
6596 Register DPPRowShr4 = MRI.createVirtualRegister(SrcRegClass);
6597 Register DPPRowShr8 = MRI.createVirtualRegister(SrcRegClass);
6598 Register RowBcast15 = MRI.createVirtualRegister(SrcRegClass);
6599 Register ReducedValSGPR = MRI.createVirtualRegister(DstRegClass);
6600 Register NegatedReducedVal = MRI.createVirtualRegister(DstRegClass);
6601 Register RowBcast31 = MRI.createVirtualRegister(SrcRegClass);
6602 Register UndefExec = MRI.createVirtualRegister(WaveMaskRegClass);
6603 Register FinalDPPResult;
6604 MachineInstr *SrcWithIdentityInstr;
6605 MachineInstr *LastBcastInstr;
6606 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), UndefExec);
6607
6609 BuildMI(*CurrBB, MI, DL,
6610 TII->get(is32BitOpc ? AMDGPU::S_MOV_B32
6611 : AMDGPU::S_MOV_B64_IMM_PSEUDO),
6612 IdentitySGPR)
6613 .addImm(IdentityValue);
6614 auto IdentityCopyInstr =
6615 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::COPY), IdentityVGPR)
6616 .addReg(IdentitySGPR);
6617 unsigned DPPOpc, ClampOpc;
6618 std::tie(DPPOpc, ClampOpc) = getDPPOpcForWaveReduction(Opc, ST);
6619 auto BuildSetInactiveInstr = [&](Register Dst, Register Src0,
6620 Register Src1) {
6621 return BuildMI(BB, MI, DL, TII->get(AMDGPU::V_SET_INACTIVE_B32),
6622 Dst)
6623 .addImm(0) // src0 modifiers
6624 .addReg(Src0) // src0
6625 .addImm(0) // src1 modifiers
6626 .addReg(Src1) // identity value for inactive lanes
6627 .addReg(UndefExec); // bool i1
6628 };
6629 auto BuildDPPMachineInstr = [&](Register Dst, Register Src,
6630 unsigned DPPCtrl) {
6631 auto DPPInstr =
6632 BuildMI(*CurrBB, MI, DL, TII->get(DPPOpc), Dst).addReg(Src); // old
6633 if (isFPOp && !NeedsMovDPP)
6634 DPPInstr.addImm(SISrcMods::NONE); // src0 modifier
6635 DPPInstr.addReg(Src); // src0
6636 if (isFPOp && !NeedsMovDPP)
6637 DPPInstr.addImm(SISrcMods::NONE); // src1 modifier
6638 if (!NeedsMovDPP)
6639 DPPInstr.addReg(Src); // src1
6640 if (AMDGPU::getNamedOperandIdx(DPPOpc, AMDGPU::OpName::clamp) >= 0)
6641 DPPInstr.addImm(0); // clamp
6642 DPPInstr
6643 .addImm(DPPCtrl) // dpp-ctrl
6644 .addImm(0xf) // row-mask
6645 .addImm(0xf) // bank-mask
6646 .addImm(0); // bound-control
6647 };
6648 auto BuildClampInstr = [&](Register Dst, Register Src0, Register Src1,
6649 bool isAddSub = false,
6650 bool needsCarryIn = false,
6651 Register CarryIn = Register()) {
6652 unsigned InstrOpc = ClampOpc;
6653 Register CarryOutReg = MRI.createVirtualRegister(WaveMaskRegClass);
6654 if (needsCarryIn)
6655 InstrOpc = AMDGPU::V_ADDC_U32_e64;
6656 auto ClampInstr = BuildMI(*CurrBB, MI, DL, TII->get(InstrOpc), Dst);
6657 if (isFPOp)
6658 ClampInstr.addImm(SISrcMods::NONE); // src0 mod
6659 if (isAddSub) {
6660 if (needsCarryIn)
6661 ClampInstr.addReg(CarryOutReg,
6663 RegState::Dead); // killed carry-out reg
6664 else
6665 ClampInstr.addReg(CarryOutReg, RegState::Define); // carry-out reg
6666 }
6667 ClampInstr.addReg(Src0); // src0
6668 if (isFPOp)
6669 ClampInstr.addImm(SISrcMods::NONE); // src1 mod
6670 ClampInstr.addReg(Src1); // src1
6671 if (needsCarryIn)
6672 ClampInstr.addReg(CarryIn); // carry-in reg
6673 if (AMDGPU::getNamedOperandIdx(InstrOpc, AMDGPU::OpName::clamp) >= 0)
6674 ClampInstr.addImm(0); // clamp
6675 if (isFPOp)
6676 ClampInstr.addImm(0); // omod
6677 LastBcastInstr = ClampInstr;
6678 return CarryOutReg;
6679 };
6680 auto BuildPostDPPInstr = [&](Register Src0, Register Src1) {
6681 bool isAddSubOpc =
6682 Opc == AMDGPU::S_ADD_U64_PSEUDO || Opc == AMDGPU::S_SUB_U64_PSEUDO;
6683 bool isBitWiseOpc = Opc == AMDGPU::S_AND_B64 ||
6684 Opc == AMDGPU::S_OR_B64 || Opc == AMDGPU::S_XOR_B64;
6685 Register ReturnReg = MRI.createVirtualRegister(SrcRegClass);
6686 if (isAddSubOpc || isBitWiseOpc) {
6687 Register ResLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6688 Register ResHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6689 MachineOperand Src0Operand =
6690 MachineOperand::CreateReg(Src0, /*isDef=*/false);
6691 MachineOperand Src1Operand =
6692 MachineOperand::CreateReg(Src1, /*isDef=*/false);
6693 auto [Src0Lo, Src0Hi] =
6694 ExtractSubRegs(MI, Src0Operand, SrcRegClass, ST, MRI);
6695 auto [Src1Lo, Src1Hi] =
6696 ExtractSubRegs(MI, Src1Operand, SrcRegClass, ST, MRI);
6697 Register CarryReg = BuildClampInstr(
6698 ResLo, Src0Lo, Src1Lo, isAddSubOpc, /*needsCarryIn*/ false);
6699 BuildClampInstr(ResHi, Src0Hi, Src1Hi, isAddSubOpc,
6700 /*needsCarryIn*/ isAddSubOpc, CarryReg);
6701 BuildRegSequence(*CurrBB, MI, ReturnReg, ResLo, ResHi);
6702 } else {
6703 if (isFPOp) {
6704 BuildMI(*CurrBB, MI, DL, TII->get(Opc), ReturnReg)
6705 .addImm(SISrcMods::NONE) // src0 modifiers
6706 .addReg(Src0)
6707 .addImm(SISrcMods::NONE) // src1 modifiers
6708 .addReg(Src1)
6709 .addImm(SISrcMods::NONE) // clamp
6710 .addImm(SISrcMods::NONE); // omod
6711 } else {
6712 Register CmpMaskReg = MRI.createVirtualRegister(WaveMaskRegClass);
6713 BuildMI(*CurrBB, MI, DL, TII->get(Opc), CmpMaskReg)
6714 .addReg(Src0) // src0
6715 .addReg(Src1); // src1
6716 LastBcastInstr =
6717 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B64_PSEUDO),
6718 ReturnReg)
6719 .addReg(Src1) // src0
6720 .addReg(Src0) // src1
6721 .addReg(CmpMaskReg); // src2
6722 expand64BitV_CNDMASK(*LastBcastInstr, CurrBB);
6723 }
6724 }
6725 return ReturnReg;
6726 };
6727
6728 // Set inactive lanes to the identity value.
6729 if (is32BitOpc) {
6730 SrcWithIdentityInstr =
6731 BuildSetInactiveInstr(SrcWithIdentity, SrcReg, IdentityVGPR);
6732 } else {
6733 Register SrcWithIdentitylo =
6734 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6735 Register SrcWithIdentityhi =
6736 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6737 auto [Reg0Sub0, Reg0Sub1] = ExtractSubRegs(
6738 MI, IdentityCopyInstr->getOperand(0), SrcRegClass, ST, MRI);
6739 auto [SrcReg0Sub0, SrcReg0Sub1] =
6740 ExtractSubRegs(MI, MI.getOperand(1), SrcRegClass, ST, MRI);
6741 MachineInstr *SetInactiveLoInstr =
6742 BuildSetInactiveInstr(SrcWithIdentitylo, SrcReg0Sub0, Reg0Sub0);
6743 MachineInstr *SetInactiveHiInstr =
6744 BuildSetInactiveInstr(SrcWithIdentityhi, SrcReg0Sub1, Reg0Sub1);
6745 SrcWithIdentityInstr =
6746 BuildRegSequence(*CurrBB, MI, SrcWithIdentity,
6747 SetInactiveLoInstr->getOperand(0).getReg(),
6748 SetInactiveHiInstr->getOperand(0).getReg());
6749 }
6750 // DPP reduction
6751 Register SrcWithIdentityReg =
6752 SrcWithIdentityInstr->getOperand(0).getReg();
6753 BuildDPPMachineInstr(DPPRowShr1, SrcWithIdentityReg,
6755 if (NeedsMovDPP)
6756 DPPRowShr1 = BuildPostDPPInstr(SrcWithIdentityReg, DPPRowShr1);
6757
6758 BuildDPPMachineInstr(DPPRowShr2, DPPRowShr1,
6760 if (NeedsMovDPP)
6761 DPPRowShr2 = BuildPostDPPInstr(DPPRowShr1, DPPRowShr2);
6762
6763 BuildDPPMachineInstr(DPPRowShr4, DPPRowShr2,
6765 if (NeedsMovDPP)
6766 DPPRowShr4 = BuildPostDPPInstr(DPPRowShr2, DPPRowShr4);
6767
6768 BuildDPPMachineInstr(DPPRowShr8, DPPRowShr4,
6770 if (NeedsMovDPP)
6771 DPPRowShr8 = BuildPostDPPInstr(DPPRowShr4, DPPRowShr8);
6772
6773 if (ST.hasDPPBroadcasts()) {
6774 BuildDPPMachineInstr(RowBcast15, DPPRowShr8, AMDGPU::DPP::BCAST15);
6775 if (NeedsMovDPP)
6776 RowBcast15 = BuildPostDPPInstr(DPPRowShr8, RowBcast15);
6777 } else {
6778 // magic constant: 0x1E0
6779 // To Set BIT_MODE : bit 15 = 0
6780 // XOR mask : bit [14:10] = 0
6781 // OR mask : bit [9:5] = 15
6782 // AND mask : bit [4:0] = 0
6783 if (is32BitOpc) {
6784 Register SwizzledValue =
6785 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6786 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6787 SwizzledValue)
6788 .addReg(DPPRowShr8) // addr
6789 .addImm(0x1E0) // swizzle offset (i16)
6790 .addImm(0x0); // gds (i1)
6791 BuildClampInstr(RowBcast15, DPPRowShr8, SwizzledValue);
6792 } else {
6793 Register SwizzledValuelo =
6794 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6795 Register SwizzledValuehi =
6796 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6797 Register SwizzledValue64 = MRI.createVirtualRegister(SrcRegClass);
6798 MachineOperand DPPRowShr8Op =
6799 MachineOperand::CreateReg(DPPRowShr8, /*isDef=*/false);
6800 auto [Op1L, Op1H] =
6801 ExtractSubRegs(MI, DPPRowShr8Op, SrcRegClass, ST, MRI);
6802 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6803 SwizzledValuelo)
6804 .addReg(Op1L) // addr
6805 .addImm(0x1E0) // swizzle offset (i16)
6806 .addImm(0x0); // gds (i1)
6807 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_SWIZZLE_B32),
6808 SwizzledValuehi)
6809 .addReg(Op1H) // addr
6810 .addImm(0x1E0) // swizzle offset (i16)
6811 .addImm(0x0); // gds (i1)
6812 BuildRegSequence(*CurrBB, MI, SwizzledValue64, SwizzledValuelo,
6813 SwizzledValuehi);
6814 if (NeedsMovDPP)
6815 RowBcast15 = BuildPostDPPInstr(DPPRowShr8, SwizzledValue64);
6816 else
6817 BuildClampInstr(RowBcast15, DPPRowShr8, SwizzledValue64);
6818 }
6819 }
6820 FinalDPPResult = RowBcast15;
6821 if (!IsWave32) {
6822 if (ST.hasDPPBroadcasts()) {
6823 BuildDPPMachineInstr(RowBcast31, RowBcast15, AMDGPU::DPP::BCAST31);
6824 if (NeedsMovDPP)
6825 RowBcast31 = BuildPostDPPInstr(RowBcast15, RowBcast31);
6826 } else {
6827 Register ShiftedThreadID =
6828 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6829 Register PermuteByteOffset =
6830 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6831 Register PermutedValue = MRI.createVirtualRegister(SrcRegClass);
6832 Register Lane32Offset =
6833 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6834 Register WordSizeConst =
6835 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6836 Register ThreadIDRegLo =
6837 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6838 Register ThreadIDReg =
6839 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6840 // Get the thread ID.
6841 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
6842 ThreadIDRegLo)
6843 .addImm(-1)
6844 .addImm(0);
6845 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
6846 ThreadIDReg)
6847 .addImm(-1)
6848 .addReg(ThreadIDRegLo);
6849 // shift each lane over by 32 positions, so value in 31st lane is
6850 // present in 63rd lane.
6851 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_MOV_B32), Lane32Offset)
6852 .addImm(0x20);
6853 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_ADD_U32_e64),
6854 ShiftedThreadID)
6855 .addReg(ThreadIDReg)
6856 .addReg(Lane32Offset)
6857 .addImm(0); // clamp
6858 // multiply by reg size.
6859 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_MOV_B32), WordSizeConst)
6860 .addImm(0x4);
6861 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_MUL_LO_U32_e64),
6862 PermuteByteOffset)
6863 .addReg(WordSizeConst)
6864 .addReg(ShiftedThreadID);
6865 // Permute the lanes
6866 if (is32BitOpc) {
6867 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6868 PermutedValue)
6869 .addReg(PermuteByteOffset) // addr
6870 .addReg(RowBcast15) // data
6871 .addImm(0); // offset
6872 } else {
6873 Register PermutedValuelo =
6874 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6875 Register PermutedValuehi =
6876 MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6877 MachineOperand RowBcast15Op =
6878 MachineOperand::CreateReg(RowBcast15, /*isDef=*/false);
6879 auto [RowBcast15Lo, RowBcast15Hi] =
6880 ExtractSubRegs(MI, RowBcast15Op, SrcRegClass, ST, MRI);
6881 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6882 PermutedValuelo)
6883 .addReg(PermuteByteOffset) // addr
6884 .addReg(RowBcast15Lo) // swizzle offset (i16)
6885 .addImm(0x0); // gds (i1)
6886 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::DS_PERMUTE_B32),
6887 PermutedValuehi)
6888 .addReg(PermuteByteOffset) // addr
6889 .addReg(RowBcast15Hi) // swizzle offset (i16)
6890 .addImm(0x0); // gds (i1)
6891 BuildRegSequence(*CurrBB, MI, PermutedValue, PermutedValuelo,
6892 PermutedValuehi);
6893 }
6894 if (NeedsMovDPP)
6895 RowBcast31 = BuildPostDPPInstr(RowBcast15, PermutedValue);
6896 else
6897 BuildClampInstr(RowBcast31, RowBcast15, PermutedValue);
6898 }
6899 FinalDPPResult = RowBcast31;
6900 }
6901 if (MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32 ||
6902 MIOpc == AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64) {
6903 Register NegatedValVGPR = MRI.createVirtualRegister(SrcRegClass);
6904 // Opc for f32 reduction is V_SUB_F32.
6905 // For f64, there is no equivalent V_SUB_F64 opcode, so use
6906 // V_ADD_F64/V_ADD_F64_pseudo, and negate the second operand.
6907 BuildMI(*CurrBB, MI, DL, TII->get(Opc),
6908 NegatedValVGPR)
6909 .addImm(SISrcMods::NONE) // src0 mods
6910 .addReg(IdentityVGPR) // src0
6911 .addImm(is32BitOpc ? SISrcMods::NONE : SISrcMods::NEG) // src1 mods
6912 .addReg(IsWave32 ? RowBcast15 : RowBcast31) // src1
6913 .addImm(SISrcMods::NONE) // clamp
6914 .addImm(SISrcMods::NONE); // omod
6915 FinalDPPResult = NegatedValVGPR;
6916 }
6917 // The final reduced value is in the last lane.
6918 if (is32BitOpc) {
6919 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6920 ReducedValSGPR)
6921 .addReg(FinalDPPResult)
6922 .addImm(ST.getWavefrontSize() - 1);
6923 } else {
6924 Register LaneValueLoReg =
6925 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6926 Register LaneValueHiReg =
6927 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6928 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
6929 MachineOperand FinalDPPResultOperand =
6930 MachineOperand::CreateReg(FinalDPPResult, /*isDef=*/false);
6931 auto [Op1L, Op1H] =
6932 ExtractSubRegs(MI, FinalDPPResultOperand, SrcRC, ST, MRI);
6933 // lane value input should be in an sgpr
6934 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6935 LaneValueLoReg)
6936 .addReg(Op1L)
6937 .addImm(ST.getWavefrontSize() - 1);
6938 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::V_READLANE_B32),
6939 LaneValueHiReg)
6940 .addReg(Op1H)
6941 .addImm(ST.getWavefrontSize() - 1);
6942 BuildRegSequence(*CurrBB, MI, ReducedValSGPR, LaneValueLoReg,
6943 LaneValueHiReg);
6944 }
6945 if (Opc == AMDGPU::S_SUB_I32) {
6946 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::S_SUB_I32), NegatedReducedVal)
6947 .addImm(0)
6948 .addReg(ReducedValSGPR)
6949 .setOperandDead(3); // Dead scc
6950 } else if (Opc == AMDGPU::S_SUB_U64_PSEUDO) {
6951 auto NegatedValInstr =
6952 BuildMI(*CurrBB, MI, DL, TII->get(Opc), NegatedReducedVal)
6953 .addImm(0)
6954 .addReg(ReducedValSGPR)
6955 .setOperandDead(3); // Dead scc
6956 CurrBB = expand64BitScalarArithmetic(*NegatedValInstr, CurrBB);
6957 }
6958 // Mark the final result as a whole-wave-mode calculation.
6959 BuildMI(*CurrBB, MI, DL, TII->get(AMDGPU::STRICT_WWM), DstReg)
6960 .addReg(Opc == AMDGPU::S_SUB_I32 || Opc == AMDGPU::S_SUB_U64_PSEUDO
6961 ? NegatedReducedVal
6962 : ReducedValSGPR);
6963 RetBB = CurrBB;
6964 }
6965 }
6966 MI.eraseFromParent();
6967 return RetBB;
6968}
6969
6972 MachineBasicBlock *BB) const {
6973 MachineFunction *MF = BB->getParent();
6975 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
6977 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
6979 const DebugLoc &DL = MI.getDebugLoc();
6980
6981 switch (MI.getOpcode()) {
6982 case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U32:
6983 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_U32);
6984 case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U64:
6985 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_LT_U64_e64);
6986 case AMDGPU::WAVE_REDUCE_MIN_PSEUDO_I32:
6987 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_I32);
6988 case AMDGPU::WAVE_REDUCE_MIN_PSEUDO_I64:
6989 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_LT_I64_e64);
6990 case AMDGPU::WAVE_REDUCE_FMIN_PSEUDO_F32:
6991 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_MIN_F32_e64);
6992 case AMDGPU::WAVE_REDUCE_FMIN_PSEUDO_F64:
6993 return lowerWaveReduce(MI, *BB, *getSubtarget(),
6994 ST.getGeneration() >= AMDGPUSubtarget::GFX12
6995 ? AMDGPU::V_MIN_NUM_F64_e64
6996 : AMDGPU::V_MIN_F64_e64);
6997 case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U32:
6998 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_U32);
6999 case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U64:
7000 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_GT_U64_e64);
7001 case AMDGPU::WAVE_REDUCE_MAX_PSEUDO_I32:
7002 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_I32);
7003 case AMDGPU::WAVE_REDUCE_MAX_PSEUDO_I64:
7004 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_CMP_GT_I64_e64);
7005 case AMDGPU::WAVE_REDUCE_FMAX_PSEUDO_F32:
7006 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_MAX_F32_e64);
7007 case AMDGPU::WAVE_REDUCE_FMAX_PSEUDO_F64:
7008 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7009 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7010 ? AMDGPU::V_MAX_NUM_F64_e64
7011 : AMDGPU::V_MAX_F64_e64);
7012 case AMDGPU::WAVE_REDUCE_ADD_PSEUDO_I32:
7013 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_ADD_I32);
7014 case AMDGPU::WAVE_REDUCE_ADD_PSEUDO_U64:
7015 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_ADD_U64_PSEUDO);
7016 case AMDGPU::WAVE_REDUCE_FADD_PSEUDO_F32:
7017 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_ADD_F32_e64);
7018 case AMDGPU::WAVE_REDUCE_FADD_PSEUDO_F64:
7019 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7020 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7021 ? AMDGPU::V_ADD_F64_pseudo_e64
7022 : AMDGPU::V_ADD_F64_e64);
7023 case AMDGPU::WAVE_REDUCE_SUB_PSEUDO_I32:
7024 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_SUB_I32);
7025 case AMDGPU::WAVE_REDUCE_SUB_PSEUDO_U64:
7026 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_SUB_U64_PSEUDO);
7027 case AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F32:
7028 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::V_SUB_F32_e64);
7029 case AMDGPU::WAVE_REDUCE_FSUB_PSEUDO_F64:
7030 // There is no S/V_SUB_F64 opcode. Double type subtraction is expanded as
7031 // fadd + neg, by setting the NEG bit in the instruction.
7032 return lowerWaveReduce(MI, *BB, *getSubtarget(),
7033 ST.getGeneration() >= AMDGPUSubtarget::GFX12
7034 ? AMDGPU::V_ADD_F64_pseudo_e64
7035 : AMDGPU::V_ADD_F64_e64);
7036 case AMDGPU::WAVE_REDUCE_AND_PSEUDO_B32:
7037 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_AND_B32);
7038 case AMDGPU::WAVE_REDUCE_AND_PSEUDO_B64:
7039 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_AND_B64);
7040 case AMDGPU::WAVE_REDUCE_OR_PSEUDO_B32:
7041 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_OR_B32);
7042 case AMDGPU::WAVE_REDUCE_OR_PSEUDO_B64:
7043 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_OR_B64);
7044 case AMDGPU::WAVE_REDUCE_XOR_PSEUDO_B32:
7045 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_XOR_B32);
7046 case AMDGPU::WAVE_REDUCE_XOR_PSEUDO_B64:
7047 return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_XOR_B64);
7048 case AMDGPU::S_UADDO_PSEUDO:
7049 case AMDGPU::S_USUBO_PSEUDO: {
7050 MachineOperand &Dest0 = MI.getOperand(0);
7051 MachineOperand &Dest1 = MI.getOperand(1);
7052 MachineOperand &Src0 = MI.getOperand(2);
7053 MachineOperand &Src1 = MI.getOperand(3);
7054
7055 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
7056 ? AMDGPU::S_ADD_U32
7057 : AMDGPU::S_SUB_U32;
7058 // clang-format off
7059 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg())
7060 .add(Src0)
7061 .add(Src1);
7062 // clang-format on
7063
7064 unsigned SelOpc =
7065 Subtarget->isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
7066 BuildMI(*BB, MI, DL, TII->get(SelOpc), Dest1.getReg()).addImm(-1).addImm(0);
7067
7068 MI.eraseFromParent();
7069 return BB;
7070 }
7071 case AMDGPU::S_ADD_U64_PSEUDO:
7072 case AMDGPU::S_SUB_U64_PSEUDO: {
7073 return expand64BitScalarArithmetic(MI, BB);
7074 }
7075 case AMDGPU::V_ADD_U64_PSEUDO:
7076 case AMDGPU::V_SUB_U64_PSEUDO: {
7077 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
7078
7079 MachineOperand &Dest = MI.getOperand(0);
7080 MachineOperand &Src0 = MI.getOperand(1);
7081 MachineOperand &Src1 = MI.getOperand(2);
7082
7083 if (ST.hasAddSubU64Insts()) {
7084 auto I = BuildMI(*BB, MI, DL,
7085 TII->get(IsAdd ? AMDGPU::V_ADD_U64_e64
7086 : AMDGPU::V_SUB_U64_e64),
7087 Dest.getReg())
7088 .add(Src0)
7089 .add(Src1)
7090 .addImm(0); // clamp
7091 TII->legalizeOperands(*I);
7092 MI.eraseFromParent();
7093 return BB;
7094 }
7095
7096 if (IsAdd && ST.hasLshlAddU64Inst()) {
7097 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
7098 Dest.getReg())
7099 .add(Src0)
7100 .addImm(0)
7101 .add(Src1);
7102 TII->legalizeOperands(*Add);
7103 MI.eraseFromParent();
7104 return BB;
7105 }
7106
7107 const auto *CarryRC = TRI->getWaveMaskRegClass();
7108
7109 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7110 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7111
7112 Register CarryReg = MRI.createVirtualRegister(CarryRC);
7113 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
7114
7115 const TargetRegisterClass *Src0RC = Src0.isReg()
7116 ? MRI.getRegClass(Src0.getReg())
7117 : &AMDGPU::VReg_64RegClass;
7118 const TargetRegisterClass *Src1RC = Src1.isReg()
7119 ? MRI.getRegClass(Src1.getReg())
7120 : &AMDGPU::VReg_64RegClass;
7121
7122 const TargetRegisterClass *Src0SubRC =
7123 TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
7124 const TargetRegisterClass *Src1SubRC =
7125 TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
7126
7127 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
7128 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
7129 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
7130 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
7131
7132 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
7133 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
7134 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
7135 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
7136
7137 unsigned LoOpc =
7138 IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
7139 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
7140 .addReg(CarryReg, RegState::Define)
7141 .add(SrcReg0Sub0)
7142 .add(SrcReg1Sub0)
7143 .addImm(0); // clamp bit
7144
7145 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
7146 MachineInstr *HiHalf =
7147 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
7148 .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
7149 .add(SrcReg0Sub1)
7150 .add(SrcReg1Sub1)
7151 .addReg(CarryReg)
7152 .addImm(0); // clamp bit
7153
7154 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
7155 .addReg(DestSub0)
7156 .addImm(AMDGPU::sub0)
7157 .addReg(DestSub1)
7158 .addImm(AMDGPU::sub1);
7159 TII->legalizeOperands(*LoHalf);
7160 TII->legalizeOperands(*HiHalf);
7161 MI.eraseFromParent();
7162 return BB;
7163 }
7164 case AMDGPU::S_ADD_CO_PSEUDO:
7165 case AMDGPU::S_SUB_CO_PSEUDO: {
7166 // This pseudo has a chance to be selected
7167 // only from uniform add/subcarry node. All the VGPR operands
7168 // therefore assumed to be splat vectors.
7170 MachineOperand &Dest = MI.getOperand(0);
7171 MachineOperand &CarryDest = MI.getOperand(1);
7172 MachineOperand &Src0 = MI.getOperand(2);
7173 MachineOperand &Src1 = MI.getOperand(3);
7174 MachineOperand &Src2 = MI.getOperand(4);
7175 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
7176 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7177 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
7178 .addReg(Src0.getReg());
7179 Src0.setReg(RegOp0);
7180 }
7181 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
7182 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7183 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
7184 .addReg(Src1.getReg());
7185 Src1.setReg(RegOp1);
7186 }
7187 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7188 if (TRI->isVectorRegister(MRI, Src2.getReg())) {
7189 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
7190 .addReg(Src2.getReg());
7191 Src2.setReg(RegOp2);
7192 }
7193
7194 if (ST.isWave64()) {
7195 if (ST.hasScalarCompareEq64()) {
7196 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
7197 .addReg(Src2.getReg())
7198 .addImm(0);
7199 } else {
7200 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
7201 const TargetRegisterClass *SubRC =
7202 TRI->getSubRegisterClass(Src2RC, AMDGPU::sub0);
7203 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
7204 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
7205 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
7206 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
7207 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7208
7209 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
7210 .add(Src2Sub0)
7211 .add(Src2Sub1);
7212
7213 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
7214 .addReg(Src2_32)
7215 .addImm(0);
7216 }
7217 } else {
7218 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
7219 .addReg(Src2.getReg())
7220 .addImm(0);
7221 }
7222
7223 unsigned Opc = MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO
7224 ? AMDGPU::S_ADDC_U32
7225 : AMDGPU::S_SUBB_U32;
7226
7227 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
7228
7229 unsigned SelOpc =
7230 ST.isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
7231
7232 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
7233 .addImm(-1)
7234 .addImm(0);
7235
7236 MI.eraseFromParent();
7237 return BB;
7238 }
7239 case AMDGPU::SI_INIT_M0: {
7240 MachineOperand &M0Init = MI.getOperand(0);
7241 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
7242 TII->get(M0Init.isReg() ? AMDGPU::COPY : AMDGPU::S_MOV_B32),
7243 AMDGPU::M0)
7244 .add(M0Init);
7245 MI.eraseFromParent();
7246 return BB;
7247 }
7248 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM: {
7249 // Set SCC to true, in case the barrier instruction gets converted to a NOP.
7250 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
7251 TII->get(AMDGPU::S_CMP_EQ_U32))
7252 .addImm(0)
7253 .addImm(0);
7254 return BB;
7255 }
7256 case AMDGPU::GET_GROUPSTATICSIZE: {
7257 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
7258 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
7259 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
7260 .add(MI.getOperand(0))
7261 .addImm(MFI->getLDSSize());
7262 MI.eraseFromParent();
7263 return BB;
7264 }
7265 case AMDGPU::GET_SHADERCYCLESHILO: {
7266 assert(MF->getSubtarget<GCNSubtarget>().hasShaderCyclesHiLoRegisters());
7267 // The algorithm is:
7268 //
7269 // hi1 = getreg(SHADER_CYCLES_HI)
7270 // lo1 = getreg(SHADER_CYCLES_LO)
7271 // hi2 = getreg(SHADER_CYCLES_HI)
7272 //
7273 // If hi1 == hi2 then there was no overflow and the result is hi2:lo1.
7274 // Otherwise there was overflow and the result is hi2:0. In both cases the
7275 // result should represent the actual time at some point during the sequence
7276 // of three getregs.
7277 using namespace AMDGPU::Hwreg;
7278 Register RegHi1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7279 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi1)
7280 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES_HI, 0, 32));
7281 Register RegLo1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7282 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegLo1)
7283 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES, 0, 32));
7284 Register RegHi2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7285 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi2)
7286 .addImm(HwregEncoding::encode(ID_SHADER_CYCLES_HI, 0, 32));
7287 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
7288 .addReg(RegHi1)
7289 .addReg(RegHi2);
7290 Register RegLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
7291 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B32), RegLo)
7292 .addReg(RegLo1)
7293 .addImm(0);
7294 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE))
7295 .add(MI.getOperand(0))
7296 .addReg(RegLo)
7297 .addImm(AMDGPU::sub0)
7298 .addReg(RegHi2)
7299 .addImm(AMDGPU::sub1);
7300 MI.eraseFromParent();
7301 return BB;
7302 }
7303 case AMDGPU::SI_INDIRECT_SRC_V1:
7304 case AMDGPU::SI_INDIRECT_SRC_V2:
7305 case AMDGPU::SI_INDIRECT_SRC_V3:
7306 case AMDGPU::SI_INDIRECT_SRC_V4:
7307 case AMDGPU::SI_INDIRECT_SRC_V5:
7308 case AMDGPU::SI_INDIRECT_SRC_V6:
7309 case AMDGPU::SI_INDIRECT_SRC_V7:
7310 case AMDGPU::SI_INDIRECT_SRC_V8:
7311 case AMDGPU::SI_INDIRECT_SRC_V9:
7312 case AMDGPU::SI_INDIRECT_SRC_V10:
7313 case AMDGPU::SI_INDIRECT_SRC_V11:
7314 case AMDGPU::SI_INDIRECT_SRC_V12:
7315 case AMDGPU::SI_INDIRECT_SRC_V16:
7316 case AMDGPU::SI_INDIRECT_SRC_V32:
7317 return emitIndirectSrc(MI, *BB, *getSubtarget());
7318 case AMDGPU::SI_INDIRECT_DST_V1:
7319 case AMDGPU::SI_INDIRECT_DST_V2:
7320 case AMDGPU::SI_INDIRECT_DST_V3:
7321 case AMDGPU::SI_INDIRECT_DST_V4:
7322 case AMDGPU::SI_INDIRECT_DST_V5:
7323 case AMDGPU::SI_INDIRECT_DST_V6:
7324 case AMDGPU::SI_INDIRECT_DST_V7:
7325 case AMDGPU::SI_INDIRECT_DST_V8:
7326 case AMDGPU::SI_INDIRECT_DST_V9:
7327 case AMDGPU::SI_INDIRECT_DST_V10:
7328 case AMDGPU::SI_INDIRECT_DST_V11:
7329 case AMDGPU::SI_INDIRECT_DST_V12:
7330 case AMDGPU::SI_INDIRECT_DST_V16:
7331 case AMDGPU::SI_INDIRECT_DST_V32:
7332 return emitIndirectDst(MI, *BB, *getSubtarget());
7333 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7334 case AMDGPU::SI_KILL_I1_PSEUDO:
7335 return splitKillBlock(MI, BB);
7336 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
7338 return BB;
7339 }
7340 case AMDGPU::SI_BR_UNDEF: {
7341 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
7342 .add(MI.getOperand(0));
7343 Br->getOperand(1).setIsUndef(); // read undef SCC
7344 MI.eraseFromParent();
7345 return BB;
7346 }
7347 case AMDGPU::ADJCALLSTACKUP:
7348 case AMDGPU::ADJCALLSTACKDOWN: {
7350 MachineInstrBuilder MIB(*MF, &MI);
7351 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
7352 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
7353 return BB;
7354 }
7355 case AMDGPU::SI_CALL_ISEL: {
7356 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
7357
7359 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL))
7360 .addDef(ReturnAddrReg, RegState::Dead);
7361
7362 for (const MachineOperand &MO : MI.operands())
7363 MIB.add(MO);
7364
7365 MIB.cloneMemRefs(MI);
7366 MIB.setMIFlags(MI.getFlags());
7367 MI.eraseFromParent();
7368 return BB;
7369 }
7370 case AMDGPU::V_ADDC_U32_e32:
7371 case AMDGPU::V_SUBB_U32_e32:
7372 case AMDGPU::V_SUBBREV_U32_e32:
7373 // These instructions have an implicit use of vcc which counts towards the
7374 // constant bus limit.
7375 TII->legalizeOperands(MI);
7376 return BB;
7377 case AMDGPU::DS_GWS_INIT:
7378 case AMDGPU::DS_GWS_SEMA_BR:
7379 case AMDGPU::DS_GWS_BARRIER:
7380 case AMDGPU::DS_GWS_SEMA_V:
7381 case AMDGPU::DS_GWS_SEMA_P:
7382 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
7383 // A s_waitcnt 0 is required to be the instruction immediately following.
7384 if (getSubtarget()->hasGWSAutoReplay()) {
7386 return BB;
7387 }
7388
7389 return emitGWSMemViolTestLoop(MI, BB);
7390 case AMDGPU::S_SETREG_B32: {
7391 // Try to optimize cases that only set the denormal mode or rounding mode.
7392 //
7393 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
7394 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
7395 // instead.
7396 //
7397 // FIXME: This could be predicates on the immediate, but tablegen doesn't
7398 // allow you to have a no side effect instruction in the output of a
7399 // sideeffecting pattern.
7400 auto [ID, Offset, Width] =
7401 AMDGPU::Hwreg::HwregEncoding::decode(MI.getOperand(1).getImm());
7402 if (ID != AMDGPU::Hwreg::ID_MODE)
7403 return BB;
7404
7405 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
7406 const unsigned SetMask = WidthMask << Offset;
7407
7408 if (getSubtarget()->hasDenormModeInst()) {
7409 unsigned SetDenormOp = 0;
7410 unsigned SetRoundOp = 0;
7411
7412 // The dedicated instructions can only set the whole denorm or round mode
7413 // at once, not a subset of bits in either.
7414 if (SetMask ==
7416 // If this fully sets both the round and denorm mode, emit the two
7417 // dedicated instructions for these.
7418 SetRoundOp = AMDGPU::S_ROUND_MODE;
7419 SetDenormOp = AMDGPU::S_DENORM_MODE;
7420 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
7421 SetRoundOp = AMDGPU::S_ROUND_MODE;
7422 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
7423 SetDenormOp = AMDGPU::S_DENORM_MODE;
7424 }
7425
7426 if (SetRoundOp || SetDenormOp) {
7427 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
7428 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
7429 unsigned ImmVal = Def->getOperand(1).getImm();
7430 if (SetRoundOp) {
7431 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
7432 .addImm(ImmVal & 0xf);
7433
7434 // If we also have the denorm mode, get just the denorm mode bits.
7435 ImmVal >>= 4;
7436 }
7437
7438 if (SetDenormOp) {
7439 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
7440 .addImm(ImmVal & 0xf);
7441 }
7442
7443 MI.eraseFromParent();
7444 return BB;
7445 }
7446 }
7447 }
7448
7449 // If only FP bits are touched, used the no side effects pseudo.
7450 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
7451 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
7452 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
7453
7454 return BB;
7455 }
7456 case AMDGPU::S_INVERSE_BALLOT_U32:
7457 case AMDGPU::S_INVERSE_BALLOT_U64:
7458 // These opcodes only exist to let SIFixSGPRCopies insert a readfirstlane if
7459 // necessary. After that they are equivalent to a COPY.
7460 MI.setDesc(TII->get(AMDGPU::COPY));
7461 return BB;
7462 case AMDGPU::ENDPGM_TRAP: {
7463 if (BB->succ_empty() && std::next(MI.getIterator()) == BB->end()) {
7464 MI.setDesc(TII->get(AMDGPU::S_ENDPGM));
7465 MI.addOperand(MachineOperand::CreateImm(0));
7466 return BB;
7467 }
7468
7469 // We need a block split to make the real endpgm a terminator. We also don't
7470 // want to break phis in successor blocks, so we can't just delete to the
7471 // end of the block.
7472
7473 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
7475 MF->push_back(TrapBB);
7476 // clang-format off
7477 BuildMI(*TrapBB, TrapBB->end(), DL, TII->get(AMDGPU::S_ENDPGM))
7478 .addImm(0);
7479 BuildMI(*BB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
7480 .addMBB(TrapBB);
7481 // clang-format on
7482
7483 BB->addSuccessor(TrapBB);
7484 MI.eraseFromParent();
7485 return SplitBB;
7486 }
7487 case AMDGPU::SIMULATED_TRAP: {
7488 assert(Subtarget->hasPrivEnabledTrap2NopBug());
7489 MachineBasicBlock *SplitBB =
7490 TII->insertSimulatedTrap(MRI, *BB, MI, MI.getDebugLoc());
7491 MI.eraseFromParent();
7492 return SplitBB;
7493 }
7494 case AMDGPU::SI_TCRETURN_GFX_WholeWave:
7495 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN: {
7497
7498 // During ISel, it's difficult to propagate the original EXEC mask to use as
7499 // an input to SI_WHOLE_WAVE_FUNC_RETURN. Set it up here instead.
7500 MachineInstr *Setup = TII->getWholeWaveFunctionSetup(*BB->getParent());
7501 assert(Setup && "Couldn't find SI_SETUP_WHOLE_WAVE_FUNC");
7502 Register OriginalExec = Setup->getOperand(0).getReg();
7503 MI.getOperand(0).setReg(OriginalExec);
7504 return BB;
7505 }
7506 case AMDGPU::V_DOT2_F32_F16:
7507 case AMDGPU::V_DOT2_F32_BF16: {
7508 // Hint RA to assign dst and src2 the same physical register.
7509 // For targets without VOP2, but with VOPD, variant of the instruction this
7510 // is one of the conditions to attempt converting VOP3P to VOPD.
7511 MRI.setSimpleHint(MI.getOperand(0).getReg(), MI.getOperand(6).getReg());
7512 return BB;
7513 }
7514 case AMDGPU::SCHED_BARRIER:
7515 case AMDGPU::SCHED_GROUP_BARRIER:
7516 MI.getOperand(0).setImm(MI.getOperand(0).getImm() &
7517 static_cast<unsigned>(AMDGPU::SchedGroupMask::ALL));
7518 return BB;
7519 default:
7520 if (TII->isImage(MI) || TII->isMUBUF(MI)) {
7521 if (!MI.mayStore())
7523 return BB;
7524 }
7526 }
7527}
7528
7530 // This currently forces unfolding various combinations of fsub into fma with
7531 // free fneg'd operands. As long as we have fast FMA (controlled by
7532 // isFMAFasterThanFMulAndFAdd), we should perform these.
7533
7534 // When fma is quarter rate, for f64 where add / sub are at best half rate,
7535 // most of these combines appear to be cycle neutral but save on instruction
7536 // count / code size.
7537 return true;
7538}
7539
7541
7543 EVT VT) const {
7544 if (!VT.isVector()) {
7545 return MVT::i1;
7546 }
7547 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
7548}
7549
7551 // TODO: Should i16 be used always if legal? For now it would force VALU
7552 // shifts.
7553 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
7554}
7555
7557 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
7558 ? Ty.changeElementSize(16)
7559 : Ty.changeElementSize(32);
7560}
7561
7562// Answering this is somewhat tricky and depends on the specific device which
7563// have different rates for fma or all f64 operations.
7564//
7565// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
7566// regardless of which device (although the number of cycles differs between
7567// devices), so it is always profitable for f64.
7568//
7569// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
7570// only on full rate devices. Normally, we should prefer selecting v_mad_f32
7571// which we can always do even without fused FP ops since it returns the same
7572// result as the separate operations and since it is always full
7573// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
7574// however does not support denormals, so we do report fma as faster if we have
7575// a fast fma device and require denormals.
7576//
7578 DenormalFPEnv FPEnv) const {
7579 VT = VT.getScalarType();
7580 if (!VT.isSimple())
7581 return false;
7582
7583 switch (VT.getSimpleVT().SimpleTy) {
7584 case MVT::f32: {
7585 // If mad is not available this depends only on if f32 fma is full rate.
7586 if (!Subtarget->hasMadMacF32Insts())
7587 return Subtarget->hasFastFMAF32();
7588
7589 // Otherwise f32 mad is always full rate and returns the same result as
7590 // the separate operations so should be preferred over fma.
7591 // However does not support denormals.
7593 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
7594
7595 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
7596 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
7597 }
7598 case MVT::f64:
7599 return true;
7600 case MVT::f16:
7601 case MVT::bf16:
7602 return Subtarget->has16BitInsts() &&
7604 default:
7605 break;
7606 }
7607
7608 return false;
7609}
7610
7615
7617 Type *Ty) const {
7619 getValueType(F.getDataLayout(), Ty, /*AllowUnknown=*/true),
7620 F.getDenormalFPEnv());
7621}
7622
7624 LLT Ty) const {
7625 switch (Ty.getScalarSizeInBits()) {
7626 case 16:
7627 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
7628 case 32:
7629 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
7630 case 64:
7631 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
7632 default:
7633 break;
7634 }
7635
7636 return false;
7637}
7638
7640 // TODO: Check future ftz flag
7641 // v_mad_f32/v_mac_f32 do not support denormals.
7642 if (VT == MVT::f32)
7643 return Subtarget->hasMadMacF32Insts() &&
7645 if (VT == MVT::f16)
7646 return Subtarget->hasMadF16() &&
7648
7649 return false;
7650}
7651
7653 if (!Ty.isScalar())
7654 return false;
7655
7656 DenormalFPEnv FPEnv = getDenormalFPEnv(*MI.getMF());
7657 if (Ty.getScalarSizeInBits() == 16)
7658 return isFMADLegal(MVT::f16, FPEnv);
7659 if (Ty.getScalarSizeInBits() == 32)
7660 return isFMADLegal(MVT::f32, FPEnv);
7661
7662 return false;
7663}
7664
7666 const SDNode *N) const {
7667 return isFMADLegal(N->getValueType(0),
7669}
7670
7672 return isFMADLegal(getValueType(F.getDataLayout(), Ty->getScalarType(),
7673 /*AllowUnknown=*/true),
7674 F.getDenormalFPEnv());
7675}
7676
7677//===----------------------------------------------------------------------===//
7678// Custom DAG Lowering Operations
7679//===----------------------------------------------------------------------===//
7680
7681// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
7682// wider vector type is legal.
7684 SelectionDAG &DAG) const {
7685 unsigned Opc = Op.getOpcode();
7686 EVT VT = Op.getValueType();
7688
7689 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
7690 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
7691
7692 SDLoc SL(Op);
7693
7694 // Forward any trailing scalar operands unchanged to both halves.
7695 SmallVector<SDValue, 2> LoOps = {Lo};
7696 SmallVector<SDValue, 2> HiOps = {Hi};
7697 auto TrailingOps = drop_begin(Op->ops());
7698 LoOps.append(TrailingOps.begin(), TrailingOps.end());
7699 HiOps.append(TrailingOps.begin(), TrailingOps.end());
7700
7701 SDValue OpLo = DAG.getNode(Opc, SL, LoVT, LoOps, Op->getFlags());
7702 SDValue OpHi = DAG.getNode(Opc, SL, HiVT, HiOps, Op->getFlags());
7703
7704 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7705}
7706
7707// Enable lowering of ROTR for vxi32 types. This is a workaround for a
7708// regression whereby extra unnecessary instructions were added to codegen
7709// for rotr operations, casued by legalising v2i32 or. This resulted in extra
7710// instructions to extract the result from the vector.
7712 [[maybe_unused]] EVT VT = Op.getValueType();
7713
7714 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v8i32 ||
7715 VT == MVT::v16i32) &&
7716 "Unexpected ValueType.");
7717
7718 return DAG.UnrollVectorOp(Op.getNode());
7719}
7720
7721// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
7722// wider vector type is legal.
7724 SelectionDAG &DAG) const {
7725 unsigned Opc = Op.getOpcode();
7726 EVT VT = Op.getValueType();
7728
7729 auto [Lo0, Hi0] = DAG.SplitVectorOperand(Op.getNode(), 0);
7730 auto [Lo1, Hi1] = DAG.SplitVectorOperand(Op.getNode(), 1);
7731
7732 SDLoc SL(Op);
7733
7734 SDValue OpLo =
7735 DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Op->getFlags());
7736 SDValue OpHi =
7737 DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Op->getFlags());
7738
7739 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7740}
7741
7743 SelectionDAG &DAG) const {
7744 unsigned Opc = Op.getOpcode();
7745 EVT VT = Op.getValueType();
7747
7748 SDValue Op0 = Op.getOperand(0);
7749 SDValue Lo0, Hi0;
7750 if (Op0.getValueType().isVector())
7751 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
7752 else
7753 Lo0 = Hi0 = DAG.getFreeze(Op0);
7754
7755 auto [Lo1, Hi1] = DAG.SplitVectorOperand(Op.getNode(), 1);
7756 auto [Lo2, Hi2] = DAG.SplitVectorOperand(Op.getNode(), 2);
7757
7758 SDLoc SL(Op);
7759 auto ResVT = DAG.GetSplitDestVTs(VT);
7760
7761 SDValue OpLo =
7762 DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, Op->getFlags());
7763 SDValue OpHi =
7764 DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, Op->getFlags());
7765
7766 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
7767}
7768
7770 switch (Op.getOpcode()) {
7771 default:
7773 case ISD::BRCOND:
7774 return LowerBRCOND(Op, DAG);
7775 case ISD::RETURNADDR:
7776 return LowerRETURNADDR(Op, DAG);
7777 case ISD::FrameIndex:
7778 return lowerFrameIndex(Op, DAG);
7779 case ISD::SPONENTRY:
7780 return LowerSPONENTRY(Op, DAG);
7781 case ISD::LOAD: {
7782 SDValue Result = LowerLOAD(Op, DAG);
7783 assert((!Result.getNode() || Result.getNode()->getNumValues() == 2) &&
7784 "Load should return a value and a chain");
7785 return Result;
7786 }
7787 case ISD::FSQRT: {
7788 EVT VT = Op.getValueType();
7789 if (VT == MVT::f32)
7790 return lowerFSQRTF32(Op, DAG);
7791 if (VT == MVT::f64)
7792 return lowerFSQRTF64(Op, DAG);
7793 return SDValue();
7794 }
7795 case ISD::FSIN:
7796 case ISD::FCOS:
7797 return LowerTrig(Op, DAG);
7798 case ISD::SELECT:
7799 return LowerSELECT(Op, DAG);
7800 case ISD::FDIV:
7801 return LowerFDIV(Op, DAG);
7802 case ISD::FFREXP:
7803 return LowerFFREXP(Op, DAG);
7805 return LowerATOMIC_CMP_SWAP(Op, DAG);
7806 case ISD::STORE:
7807 return LowerSTORE(Op, DAG);
7808 case ISD::GlobalAddress: {
7811 return LowerGlobalAddress(MFI, Op, DAG);
7812 }
7813 case ISD::BlockAddress:
7814 return LowerBlockAddress(Op, DAG);
7816 return LowerExternalSymbol(Op, DAG);
7818 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7820 return LowerCONVERT_FROM_ARBITRARY_FP(Op, DAG);
7822 return LowerCONVERT_TO_ARBITRARY_FP(Op, DAG);
7824 return LowerINTRINSIC_W_CHAIN(Op, DAG);
7826 return LowerINTRINSIC_VOID(Op, DAG);
7827 case ISD::ADDRSPACECAST:
7828 return lowerADDRSPACECAST(Op, DAG);
7830 return lowerINSERT_SUBVECTOR(Op, DAG);
7832 return lowerINSERT_VECTOR_ELT(Op, DAG);
7834 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7836 return lowerVECTOR_SHUFFLE(Op, DAG);
7838 return lowerSCALAR_TO_VECTOR(Op, DAG);
7839 case ISD::BUILD_VECTOR:
7840 return lowerBUILD_VECTOR(Op, DAG);
7841 case ISD::FP_ROUND:
7843 return lowerFP_ROUND(Op, DAG);
7844 case ISD::TRAP:
7845 return lowerTRAP(Op, DAG);
7846 case ISD::DEBUGTRAP:
7847 return lowerDEBUGTRAP(Op, DAG);
7848 case ISD::ABS:
7849 case ISD::FABS:
7850 case ISD::FNEG:
7851 case ISD::FCANONICALIZE:
7852 case ISD::BSWAP:
7853 return splitUnaryVectorOp(Op, DAG);
7856 if (Op.getValueType().isVector() && Op.getValueType() != MVT::v2i16 &&
7857 Op.getOperand(0).getValueType().getScalarType() == MVT::f32)
7858 return splitUnaryVectorOp(Op, DAG);
7859 return LowerFP_TO_INT_SAT(Op, DAG);
7860 case ISD::FSUB:
7861 if (Op.getValueType() == MVT::bf16) {
7862 // Custom expansion:
7863 // fsub bf16 %a, %b -> fadd v2bf16(widen %a), fneg v2bf16(widen %b)
7864 // Then extract back to bf16.
7865 //
7866 // We create fneg on v2bf16 (not bf16) so the instruction selector can
7867 // fold the negation into the packed add's neg_lo/neg_hi modifiers,
7868 // generating a single v_pk_add_bf16 instruction. If we negate bf16 first,
7869 // it becomes a separate v_xor instruction before widening.
7870 SDLoc DL(Op);
7871 SDValue Op0 = Op.getOperand(0);
7872 SDValue Op1 = Op.getOperand(1);
7873
7874 // Widen both operands to v2bf16
7875 SDValue Vec0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2bf16, Op0);
7876 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2bf16, Op1);
7877
7878 // Create FNEG v2bf16 for the second operand
7879 SDValue NegVec1 = DAG.getNode(ISD::FNEG, DL, MVT::v2bf16, Vec1);
7880
7881 // Perform FADD v2bf16
7882 SDValue Result = DAG.getNode(ISD::FADD, DL, MVT::v2bf16, Vec0, NegVec1);
7883
7884 // Extract element 0 back to bf16
7885 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::bf16, Result,
7886 DAG.getConstant(0, DL, MVT::i32));
7887 }
7888 return SDValue();
7889 case ISD::FMINNUM:
7890 case ISD::FMAXNUM:
7891 return lowerFMINNUM_FMAXNUM(Op, DAG);
7892 case ISD::FMINIMUMNUM:
7893 case ISD::FMAXIMUMNUM:
7894 return lowerFMINIMUMNUM_FMAXIMUMNUM(Op, DAG);
7895 case ISD::FLDEXP:
7896 case ISD::STRICT_FLDEXP:
7897 return lowerFLDEXP(Op, DAG);
7898 case ISD::FMA:
7899 return splitTernaryVectorOp(Op, DAG);
7900 case ISD::FP_TO_SINT:
7901 case ISD::FP_TO_UINT:
7902 if (Subtarget->hasVCvtPkIU16F32() && Op.getValueType() == MVT::i16 &&
7903 Op.getOperand(0).getValueType() == MVT::f32) {
7904 // Make f32->i16 legal so we can select V_CVT_PK_[IU]16_F32.
7905 return Op;
7906 }
7907 return LowerFP_TO_INT(Op, DAG);
7908 case ISD::SHL:
7909 case ISD::SRA:
7910 case ISD::SRL:
7911 case ISD::ADD:
7912 case ISD::SUB:
7913 case ISD::SMIN:
7914 case ISD::SMAX:
7915 case ISD::UMIN:
7916 case ISD::UMAX:
7917 case ISD::FMINNUM_IEEE:
7918 case ISD::FMAXNUM_IEEE:
7919 case ISD::FMINIMUM:
7920 case ISD::FMAXIMUM:
7921 case ISD::UADDSAT:
7922 case ISD::USUBSAT:
7923 case ISD::SADDSAT:
7924 case ISD::SSUBSAT:
7925 case ISD::FADD:
7926 case ISD::FMUL:
7927 return splitBinaryVectorOp(Op, DAG);
7928 case ISD::FCOPYSIGN:
7929 return lowerFCOPYSIGN(Op, DAG);
7930 case ISD::MUL:
7931 return lowerMUL(Op, DAG);
7932 case ISD::SMULO:
7933 case ISD::UMULO:
7934 return lowerXMULO(Op, DAG);
7935 case ISD::SMUL_LOHI:
7936 case ISD::UMUL_LOHI:
7937 return lowerXMUL_LOHI(Op, DAG);
7939 return LowerDYNAMIC_STACKALLOC(Op, DAG);
7940 case ISD::STACKSAVE:
7941 return LowerSTACKSAVE(Op, DAG);
7942 case ISD::GET_ROUNDING:
7943 return lowerGET_ROUNDING(Op, DAG);
7944 case ISD::SET_ROUNDING:
7945 return lowerSET_ROUNDING(Op, DAG);
7946 case ISD::PREFETCH:
7947 return lowerPREFETCH(Op, DAG);
7948 case ISD::FP_EXTEND:
7950 return lowerFP_EXTEND(Op, DAG);
7951 case ISD::GET_FPENV:
7952 return lowerGET_FPENV(Op, DAG);
7953 case ISD::SET_FPENV:
7954 return lowerSET_FPENV(Op, DAG);
7955 case ISD::ROTR:
7956 return lowerROTR(Op, DAG);
7957 case ISD::INLINEASM:
7958 return LowerINLINEASM(Op, DAG);
7959 }
7960 return SDValue();
7961}
7962
7963// TFE results are dword granular: value dwords followed by one status dword.
7964static std::pair<SDValue, SDValue>
7966 LLVMContext &C = *DAG.getContext();
7967 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
7969 DAG.getVectorIdxConstant(NumValueDWords, DL));
7970 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
7971 SDValue ValueDWords =
7972 NumValueDWords == 1
7973 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op, ZeroIdx)
7975 EVT::getVectorVT(C, MVT::i32, NumValueDWords), Op,
7976 ZeroIdx);
7977 if (!VT.isVector() && VT.getSizeInBits() < 32)
7978 ValueDWords =
7979 DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), ValueDWords);
7980 return {DAG.getNode(ISD::BITCAST, DL, VT, ValueDWords), Status};
7981}
7982
7983// Used for D16: Casts the result of an instruction into the right vector,
7984// packs values if loads return unpacked values.
7986 const SDLoc &DL, SelectionDAG &DAG,
7987 bool Unpacked) {
7988 if (!LoadVT.isVector())
7989 return Result;
7990
7991 // Cast back to the original packed type or to a larger type that is a
7992 // multiple of 32 bit for D16. Widening the return type is a required for
7993 // legalization.
7994 EVT FittingLoadVT = LoadVT;
7995 if ((LoadVT.getVectorNumElements() % 2) == 1) {
7996 FittingLoadVT =
7998 LoadVT.getVectorNumElements() + 1);
7999 }
8000
8001 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
8002 // Truncate to v2i16/v4i16.
8003 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
8004
8005 // Workaround legalizer not scalarizing truncate after vector op
8006 // legalization but not creating intermediate vector trunc.
8008 DAG.ExtractVectorElements(Result, Elts);
8009 for (SDValue &Elt : Elts)
8010 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
8011
8012 // Pad illegal v1i16/v3fi6 to v4i16
8013 if ((LoadVT.getVectorNumElements() % 2) == 1)
8014 Elts.push_back(DAG.getPOISON(MVT::i16));
8015
8016 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
8017
8018 // Bitcast to original type (v2f16/v4f16).
8019 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
8020 }
8021
8022 // Cast back to the original packed type.
8023 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
8024}
8025
8026SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, MemSDNode *M,
8027 SelectionDAG &DAG,
8029 bool IsIntrinsic) const {
8030 SDLoc DL(M);
8031
8032 bool IsTFE = M->getNumValues() == 3;
8033 bool Unpacked = Subtarget->hasUnpackedD16VMem();
8034 EVT LoadVT = M->getValueType(0);
8035
8036 EVT EquivLoadVT = LoadVT;
8037 if (LoadVT.isVector()) {
8038 if (Unpacked) {
8039 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8040 LoadVT.getVectorNumElements());
8041 } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
8042 // Widen v3f16 to legal type
8043 EquivLoadVT =
8045 LoadVT.getVectorNumElements() + 1);
8046 }
8047 }
8048
8049 if (IsTFE) {
8050 unsigned NumValueDWords = divideCeil(EquivLoadVT.getSizeInBits(), 32);
8051 EVT LoadDWordsVT =
8052 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumValueDWords + 1);
8053 SDVTList VTList = DAG.getVTList(LoadDWordsVT, MVT::Other);
8055 Opcode, DL, VTList, Ops, M->getMemoryVT(), M->getMemOperand());
8056 auto [Value, Status] = splitTFEValueAndStatus(Load, EquivLoadVT, DL, DAG);
8057 SDValue Adjusted =
8058 adjustLoadValueTypeImpl(Value, LoadVT, DL, DAG, Unpacked);
8059 return DAG.getMergeValues({Adjusted, Status, Load.getValue(1)}, DL);
8060 }
8061
8062 // Change from v4f16/v2f16 to EquivLoadVT.
8063 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
8064
8066 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, VTList, Ops,
8067 M->getMemoryVT(), M->getMemOperand());
8068
8069 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
8070
8071 return DAG.getMergeValues({Adjusted, Load.getValue(1)}, DL);
8072}
8073
8074SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
8075 SelectionDAG &DAG,
8076 ArrayRef<SDValue> Ops) const {
8077 SDLoc DL(M);
8078 EVT LoadVT = M->getValueType(0);
8079 EVT EltType = LoadVT.getScalarType();
8080 EVT IntVT = LoadVT.changeTypeToInteger();
8081
8082 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8083
8084 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
8085 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
8087 "unsupported sub-dword format buffer load", DL.getDebugLoc()));
8088 return DAG.getMergeValues({DAG.getPOISON(LoadVT), M->getOperand(0)}, DL);
8089 }
8090
8091 assert(M->getNumValues() == 2 || M->getNumValues() == 3);
8092 bool IsTFE = M->getNumValues() == 3;
8093
8094 if (IsD16 && IsTFE && !Subtarget->hasBufferTFEFormatD16()) {
8095 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
8097 "TFE D16 format buffer load is not supported on this GPU",
8098 DL.getDebugLoc()));
8099 return DAG.getErrorMergeValues({M->value_begin(), M->value_end()},
8100 M->getOperand(0), DL);
8101 }
8102
8103 unsigned Opc = IsD16 ? (IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_D16_TFE
8104 : AMDGPUISD::BUFFER_LOAD_FORMAT_D16)
8105 : IsFormat ? (IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_TFE
8106 : AMDGPUISD::BUFFER_LOAD_FORMAT)
8107 : IsTFE ? AMDGPUISD::BUFFER_LOAD_TFE
8108 : AMDGPUISD::BUFFER_LOAD;
8109
8110 if (IsD16)
8111 return adjustLoadValueType(Opc, M, DAG, Ops);
8112
8113 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
8114 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
8115 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M->getMemOperand(),
8116 IsTFE);
8117
8118 if (isTypeLegal(LoadVT)) {
8119 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
8120 M->getMemOperand(), DAG);
8121 }
8122
8123 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
8124 SDVTList VTList = IsTFE ? DAG.getVTList(CastVT, MVT::i32, MVT::Other)
8125 : DAG.getVTList(CastVT, MVT::Other);
8126 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
8127 M->getMemOperand(), DAG);
8128 SDValue Data = DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode);
8129 if (IsTFE)
8130 return DAG.getMergeValues({Data, MemNode.getValue(1), MemNode.getValue(2)},
8131 DL);
8132 return DAG.getMergeValues({Data, MemNode.getValue(1)}, DL);
8133}
8134
8136 SelectionDAG &DAG) {
8137 EVT VT = N->getValueType(0);
8138 SDValue Src = N->getOperand(1);
8139 SDLoc SL(N);
8140
8141 if (Src.getOpcode() == ISD::SETCC) {
8142 SDValue Op0 = Src.getOperand(0);
8143 SDValue Op1 = Src.getOperand(1);
8144 // Need to expand bfloat to float for comparison (setcc).
8145 if (Op0.getValueType() == MVT::bf16) {
8146 Op0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op0);
8147 Op1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op1);
8148 }
8149 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
8150 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Op0, Op1, Src.getOperand(2));
8151 }
8152 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
8153 // (ballot 0) -> 0
8154 if (Arg->isZero())
8155 return DAG.getConstant(0, SL, VT);
8156
8157 // (ballot 1) -> EXEC/EXEC_LO
8158 if (Arg->isOne()) {
8159 Register Exec;
8160 if (VT.getScalarSizeInBits() == 32)
8161 Exec = AMDGPU::EXEC_LO;
8162 else if (VT.getScalarSizeInBits() == 64)
8163 Exec = AMDGPU::EXEC;
8164 else
8165 return SDValue();
8166
8167 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
8168 }
8169 }
8170
8171 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
8172 // ISD::SETNE)
8173 return DAG.getNode(
8174 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
8175 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
8176}
8177
8179 Intrinsic::ID IntrinsicID) {
8180 bool Signed = IntrinsicID == Intrinsic::amdgcn_sbfe;
8181 SDLoc DL(Op);
8182 EVT VT = Op.getValueType();
8183 SDValue Src = Op.getOperand(1);
8184 SDValue Offset = Op.getOperand(2);
8185 SDValue Width = Op.getOperand(3);
8186
8187 if (VT != MVT::i32) {
8190 Twine(Intrinsic::getBaseName(IntrinsicID)) + " only supports i32",
8191 DL.getDebugLoc()));
8192 return DAG.getPOISON(VT);
8193 }
8194
8195 return DAG.getNode(Signed ? AMDGPUISD::BFE_I32 : AMDGPUISD::BFE_U32, DL, VT,
8196 Src, Offset, Width);
8197}
8198
8200 EVT VT);
8201
8203 SelectionDAG &DAG) {
8204 EVT VT = N->getValueType(0);
8205 unsigned ValSize = VT.getSizeInBits();
8206 unsigned IID = N->getConstantOperandVal(0);
8207 bool IsPermLane16 = IID == Intrinsic::amdgcn_permlane16 ||
8208 IID == Intrinsic::amdgcn_permlanex16;
8209 bool IsSetInactive = IID == Intrinsic::amdgcn_set_inactive ||
8210 IID == Intrinsic::amdgcn_set_inactive_chain_arg;
8211 bool IsPermlaneShuffle = IID == Intrinsic::amdgcn_permlane_bcast ||
8212 IID == Intrinsic::amdgcn_permlane_up ||
8213 IID == Intrinsic::amdgcn_permlane_down ||
8214 IID == Intrinsic::amdgcn_permlane_xor;
8215 SDLoc SL(N);
8216 MVT IntVT = MVT::getIntegerVT(ValSize);
8217 const GCNSubtarget *ST = TLI.getSubtarget();
8218
8219 unsigned SplitSize = 32;
8220 if (IID == Intrinsic::amdgcn_update_dpp && (ValSize % 64 == 0) &&
8221 ST->hasDPALU_DPP() &&
8222 AMDGPU::isLegalDPALU_DPPControl(*ST, N->getConstantOperandVal(3)))
8223 SplitSize = 64;
8224
8225 auto createLaneOp = [&DAG, &SL, N, IID](SDValue Src0, SDValue Src1,
8226 SDValue Src2, MVT ValT) -> SDValue {
8228 switch (IID) {
8229 case Intrinsic::amdgcn_permlane16:
8230 case Intrinsic::amdgcn_permlanex16:
8231 case Intrinsic::amdgcn_update_dpp:
8232 Operands.push_back(N->getOperand(6));
8233 Operands.push_back(N->getOperand(5));
8234 Operands.push_back(N->getOperand(4));
8235 [[fallthrough]];
8236 case Intrinsic::amdgcn_writelane:
8237 case Intrinsic::amdgcn_permlane_bcast:
8238 case Intrinsic::amdgcn_permlane_up:
8239 case Intrinsic::amdgcn_permlane_down:
8240 case Intrinsic::amdgcn_permlane_xor:
8241 Operands.push_back(Src2);
8242 [[fallthrough]];
8243 case Intrinsic::amdgcn_readlane:
8244 case Intrinsic::amdgcn_set_inactive:
8245 case Intrinsic::amdgcn_set_inactive_chain_arg:
8246 case Intrinsic::amdgcn_mov_dpp8:
8247 Operands.push_back(Src1);
8248 [[fallthrough]];
8249 case Intrinsic::amdgcn_readfirstlane:
8250 case Intrinsic::amdgcn_permlane64:
8251 Operands.push_back(Src0);
8252 break;
8253 default:
8254 llvm_unreachable("unhandled lane op");
8255 }
8256
8257 Operands.push_back(DAG.getTargetConstant(IID, SL, MVT::i32));
8258 std::reverse(Operands.begin(), Operands.end());
8259
8260 if (SDNode *GL = N->getGluedNode()) {
8261 assert(GL->getOpcode() == ISD::CONVERGENCECTRL_GLUE);
8262 GL = GL->getOperand(0).getNode();
8263 Operands.push_back(DAG.getNode(ISD::CONVERGENCECTRL_GLUE, SL, MVT::Glue,
8264 SDValue(GL, 0)));
8265 }
8266
8267 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, ValT, Operands);
8268 };
8269
8270 SDValue Src0 = N->getOperand(1);
8271 SDValue Src1, Src2;
8272 if (IID == Intrinsic::amdgcn_readlane || IID == Intrinsic::amdgcn_writelane ||
8273 IID == Intrinsic::amdgcn_mov_dpp8 ||
8274 IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16 ||
8275 IsPermlaneShuffle) {
8276 Src1 = N->getOperand(2);
8277 if (IID == Intrinsic::amdgcn_writelane ||
8278 IID == Intrinsic::amdgcn_update_dpp || IsPermLane16 ||
8279 IsPermlaneShuffle)
8280 Src2 = N->getOperand(3);
8281 }
8282
8283 if (ValSize == SplitSize) {
8284 // Already legal
8285 return SDValue();
8286 }
8287
8288 if (ValSize < 32) {
8289 bool IsFloat = VT.isFloatingPoint();
8290 Src0 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src0) : Src0,
8291 SL, MVT::i32);
8292
8293 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16) {
8294 Src1 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src1) : Src1,
8295 SL, MVT::i32);
8296 }
8297
8298 if (IID == Intrinsic::amdgcn_writelane) {
8299 Src2 = DAG.getAnyExtOrTrunc(IsFloat ? DAG.getBitcast(IntVT, Src2) : Src2,
8300 SL, MVT::i32);
8301 }
8302
8303 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, MVT::i32);
8304 SDValue Trunc = DAG.getAnyExtOrTrunc(LaneOp, SL, IntVT);
8305 return IsFloat ? DAG.getBitcast(VT, Trunc) : Trunc;
8306 }
8307
8308 if (ValSize % SplitSize != 0)
8309 return SDValue();
8310
8311 auto unrollLaneOp = [&DAG, &SL](SDNode *N) -> SDValue {
8312 EVT VT = N->getValueType(0);
8313 unsigned NE = VT.getVectorNumElements();
8314 EVT EltVT = VT.getVectorElementType();
8316 unsigned NumOperands = N->getNumOperands();
8317 SmallVector<SDValue, 4> Operands(NumOperands);
8318 SDNode *GL = N->getGluedNode();
8319
8320 // only handle convergencectrl_glue
8322
8323 for (unsigned i = 0; i != NE; ++i) {
8324 for (unsigned j = 0, e = GL ? NumOperands - 1 : NumOperands; j != e;
8325 ++j) {
8326 SDValue Operand = N->getOperand(j);
8327 EVT OperandVT = Operand.getValueType();
8328 if (OperandVT.isVector()) {
8329 // A vector operand; extract a single element.
8330 EVT OperandEltVT = OperandVT.getVectorElementType();
8331 Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, OperandEltVT,
8332 Operand, DAG.getVectorIdxConstant(i, SL));
8333 } else {
8334 // A scalar operand; just use it as is.
8335 Operands[j] = Operand;
8336 }
8337 }
8338
8339 if (GL)
8340 Operands[NumOperands - 1] =
8341 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, SL, MVT::Glue,
8342 SDValue(GL->getOperand(0).getNode(), 0));
8343
8344 Scalars.push_back(DAG.getNode(N->getOpcode(), SL, EltVT, Operands));
8345 }
8346
8347 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NE);
8348 return DAG.getBuildVector(VecVT, SL, Scalars);
8349 };
8350
8351 if (VT.isVector()) {
8352 switch (MVT::SimpleValueType EltTy =
8354 case MVT::i32:
8355 case MVT::f32:
8356 if (SplitSize == 32) {
8357 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, VT.getSimpleVT());
8358 return unrollLaneOp(LaneOp.getNode());
8359 }
8360 [[fallthrough]];
8361 case MVT::i16:
8362 case MVT::f16:
8363 case MVT::bf16: {
8364 unsigned SubVecNumElt =
8365 SplitSize / VT.getVectorElementType().getSizeInBits();
8366 MVT SubVecVT = MVT::getVectorVT(EltTy, SubVecNumElt);
8368 SDValue Src0SubVec, Src1SubVec, Src2SubVec;
8369 for (unsigned i = 0, EltIdx = 0; i < ValSize / SplitSize; i++) {
8370 Src0SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src0,
8371 DAG.getConstant(EltIdx, SL, MVT::i32));
8372
8373 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive ||
8374 IsPermLane16) {
8375 Src1SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src1,
8376 DAG.getConstant(EltIdx, SL, MVT::i32));
8377
8378 Pieces.push_back(
8379 createLaneOp(Src0SubVec, Src1SubVec, Src2, SubVecVT));
8380 } else if (IID == Intrinsic::amdgcn_writelane) {
8381 Src2SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, SubVecVT, Src2,
8382 DAG.getConstant(EltIdx, SL, MVT::i32));
8383 Pieces.push_back(
8384 createLaneOp(Src0SubVec, Src1, Src2SubVec, SubVecVT));
8385 } else {
8386 Pieces.push_back(createLaneOp(Src0SubVec, Src1, Src2, SubVecVT));
8387 }
8388
8389 EltIdx += SubVecNumElt;
8390 }
8391 return DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, Pieces);
8392 }
8393 default:
8394 // Handle all other cases by bitcasting to i32 vectors
8395 break;
8396 }
8397 }
8398
8399 MVT VecVT =
8400 MVT::getVectorVT(MVT::getIntegerVT(SplitSize), ValSize / SplitSize);
8401 Src0 = DAG.getBitcast(VecVT, Src0);
8402
8403 if (IID == Intrinsic::amdgcn_update_dpp || IsSetInactive || IsPermLane16)
8404 Src1 = DAG.getBitcast(VecVT, Src1);
8405
8406 if (IID == Intrinsic::amdgcn_writelane)
8407 Src2 = DAG.getBitcast(VecVT, Src2);
8408
8409 SDValue LaneOp = createLaneOp(Src0, Src1, Src2, VecVT);
8410 SDValue UnrolledLaneOp = unrollLaneOp(LaneOp.getNode());
8411 return DAG.getBitcast(VT, UnrolledLaneOp);
8412}
8413
8415 SelectionDAG &DAG) {
8416 EVT VT = N->getValueType(0);
8417
8418 if (VT.getSizeInBits() != 32)
8419 return SDValue();
8420
8421 SDLoc SL(N);
8422
8423 SDValue Value = N->getOperand(1);
8424 SDValue Index = N->getOperand(2);
8425
8426 // ds_bpermute requires index to be multiplied by 4
8427 SDValue ShiftAmount = DAG.getShiftAmountConstant(2, MVT::i32, SL);
8428 SDValue ShiftedIndex =
8429 DAG.getNode(ISD::SHL, SL, Index.getValueType(), Index, ShiftAmount);
8430
8431 // Intrinsics will require i32 to operate on
8432 SDValue ValueI32 = DAG.getBitcast(MVT::i32, Value);
8433
8434 auto MakeIntrinsic = [&DAG, &SL](unsigned IID, MVT RetVT,
8435 SmallVector<SDValue> IntrinArgs) -> SDValue {
8437 Operands[0] = DAG.getTargetConstant(IID, SL, MVT::i32);
8438 Operands.append(IntrinArgs);
8439 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, RetVT, Operands);
8440 };
8441
8442 // If we can bpermute across the whole wave, then just do that
8443 if (TLI.getSubtarget()->supportsWaveWideBPermute()) {
8444 SDValue BPermute = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute, MVT::i32,
8445 {ShiftedIndex, ValueI32});
8446 return DAG.getBitcast(VT, BPermute);
8447 }
8448
8449 assert(TLI.getSubtarget()->isWave64());
8450
8451 // Otherwise, we need to make use of whole wave mode
8452 SDValue PoisonVal = DAG.getPOISON(ValueI32->getValueType(0));
8453
8454 // Set inactive lanes to poison
8455 SDValue WWMValue = MakeIntrinsic(Intrinsic::amdgcn_set_inactive, MVT::i32,
8456 {ValueI32, PoisonVal});
8457 SDValue WWMIndex = MakeIntrinsic(Intrinsic::amdgcn_set_inactive, MVT::i32,
8458 {ShiftedIndex, PoisonVal});
8459
8460 SDValue Swapped =
8461 MakeIntrinsic(Intrinsic::amdgcn_permlane64, MVT::i32, {WWMValue});
8462
8463 // Get permutation of each half, then we'll select which one to use
8464 SDValue BPermSameHalf = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute, MVT::i32,
8465 {WWMIndex, WWMValue});
8466 SDValue BPermOtherHalf = MakeIntrinsic(Intrinsic::amdgcn_ds_bpermute,
8467 MVT::i32, {WWMIndex, Swapped});
8468 SDValue BPermOtherHalfWWM =
8469 MakeIntrinsic(Intrinsic::amdgcn_wwm, MVT::i32, {BPermOtherHalf});
8470
8471 // Select which side to take the permute from
8472 SDValue ThreadIDMask = DAG.getAllOnesConstant(SL, MVT::i32);
8473 // We can get away with only using mbcnt_lo here since we're only
8474 // trying to detect which side of 32 each lane is on, and mbcnt_lo
8475 // returns 32 for lanes 32-63.
8476 SDValue ThreadID =
8477 MakeIntrinsic(Intrinsic::amdgcn_mbcnt_lo, MVT::i32,
8478 {ThreadIDMask, DAG.getTargetConstant(0, SL, MVT::i32)});
8479
8480 SDValue SameOrOtherHalf =
8481 DAG.getNode(ISD::AND, SL, MVT::i32,
8482 DAG.getNode(ISD::XOR, SL, MVT::i32, ThreadID, Index),
8483 DAG.getTargetConstant(32, SL, MVT::i32));
8484 SDValue UseSameHalf =
8485 DAG.getSetCC(SL, MVT::i1, SameOrOtherHalf,
8486 DAG.getConstant(0, SL, MVT::i32), ISD::SETEQ);
8487 SDValue Result = DAG.getSelect(SL, MVT::i32, UseSameHalf, BPermSameHalf,
8488 BPermOtherHalfWWM);
8489 return DAG.getBitcast(VT, Result);
8490}
8491
8494 SelectionDAG &DAG) const {
8495 switch (N->getOpcode()) {
8497 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
8498 Results.push_back(Res);
8499 return;
8500 }
8502 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
8503 Results.push_back(Res);
8504 return;
8505 }
8507 if (SDValue Res = LowerCONVERT_TO_ARBITRARY_FP(SDValue(N, 0), DAG))
8508 Results.push_back(Res);
8509 return;
8510 }
8512 unsigned IID = N->getConstantOperandVal(0);
8513 switch (IID) {
8514 case Intrinsic::amdgcn_wave_reduce_min:
8515 case Intrinsic::amdgcn_wave_reduce_umin:
8516 case Intrinsic::amdgcn_wave_reduce_max:
8517 case Intrinsic::amdgcn_wave_reduce_umax:
8518 case Intrinsic::amdgcn_wave_reduce_add:
8519 case Intrinsic::amdgcn_wave_reduce_sub:
8520 case Intrinsic::amdgcn_wave_reduce_and:
8521 case Intrinsic::amdgcn_wave_reduce_or:
8522 case Intrinsic::amdgcn_wave_reduce_xor: {
8523 EVT VT = N->getValueType(0);
8524 if (isTypeLegal(VT))
8525 return;
8526 SDLoc SL(N);
8527 bool NeedsSignExt = IID == Intrinsic::amdgcn_wave_reduce_min ||
8528 IID == Intrinsic::amdgcn_wave_reduce_max ||
8529 IID == Intrinsic::amdgcn_wave_reduce_add ||
8530 IID == Intrinsic::amdgcn_wave_reduce_sub;
8531 unsigned ExtOpc = NeedsSignExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8532 SDValue ExtSrc = DAG.getNode(ExtOpc, SL, MVT::i32, N->getOperand(1));
8533 SDValue Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
8534 N->getOperand(0), ExtSrc, N->getOperand(2));
8535 Results.push_back(DAG.getNode(ISD::TRUNCATE, SL, VT, Result));
8536 return;
8537 }
8538 case Intrinsic::amdgcn_make_buffer_rsrc:
8539 Results.push_back(lowerPointerAsRsrcIntrin(N, DAG));
8540 return;
8541 case Intrinsic::amdgcn_cvt_pkrtz: {
8542 SDValue Src0 = N->getOperand(1);
8543 SDValue Src1 = N->getOperand(2);
8544 SDLoc SL(N);
8545 SDValue Cvt =
8546 DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, Src0, Src1);
8547 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
8548 return;
8549 }
8550 case Intrinsic::amdgcn_cvt_pknorm_i16:
8551 case Intrinsic::amdgcn_cvt_pknorm_u16:
8552 case Intrinsic::amdgcn_cvt_pk_i16:
8553 case Intrinsic::amdgcn_cvt_pk_u16: {
8554 SDValue Src0 = N->getOperand(1);
8555 SDValue Src1 = N->getOperand(2);
8556 SDLoc SL(N);
8557 unsigned Opcode;
8558
8559 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
8560 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
8561 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
8562 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
8563 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
8564 Opcode = AMDGPUISD::CVT_PK_I16_I32;
8565 else
8566 Opcode = AMDGPUISD::CVT_PK_U16_U32;
8567
8568 EVT VT = N->getValueType(0);
8569 if (isTypeLegal(VT))
8570 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
8571 else {
8572 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
8573 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
8574 }
8575 return;
8576 }
8577 case Intrinsic::amdgcn_s_buffer_load: {
8578 SDValue Op = SDValue(N, 0);
8579 EVT VT = Op.getValueType();
8580 Results.push_back(lowerSBuffer(VT, VT, SDLoc(Op), DAG.getEntryNode(),
8581 Op.getOperand(1), Op.getOperand(2),
8582 Op.getOperand(3), DAG));
8583 return;
8584 }
8585 case Intrinsic::amdgcn_dead: {
8586 for (unsigned I = 0, E = N->getNumValues(); I < E; ++I)
8587 Results.push_back(DAG.getPOISON(N->getValueType(I)));
8588 return;
8589 }
8590 }
8591 break;
8592 }
8594 if (N->getConstantOperandVal(1) != Intrinsic::amdgcn_ptr_s_buffer_load &&
8595 N->getValueType(0).isSimple() &&
8596 SBufferLoadDiagnosticVTs[N->getSimpleValueType(0).SimpleTy])
8597 break;
8598 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
8599 if (Res.getOpcode() == ISD::MERGE_VALUES) {
8600 // FIXME: Hacky
8601 for (unsigned I = 0; I < Res.getNumOperands(); I++) {
8602 Results.push_back(Res.getOperand(I));
8603 }
8604 } else {
8605 for (unsigned I = 0; I < N->getNumValues(); ++I)
8606 Results.push_back(Res.getValue(I));
8607 }
8608 return;
8609 }
8610
8611 break;
8612 }
8613 case ISD::SELECT: {
8614 SDLoc SL(N);
8615 EVT VT = N->getValueType(0);
8616 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
8617 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
8618 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
8619
8620 EVT SelectVT = NewVT;
8621 if (NewVT.bitsLT(MVT::i32)) {
8622 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
8623 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
8624 SelectVT = MVT::i32;
8625 }
8626
8627 SDValue NewSelect =
8628 DAG.getNode(ISD::SELECT, SL, SelectVT, N->getOperand(0), LHS, RHS);
8629
8630 if (NewVT != SelectVT)
8631 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
8632 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
8633 return;
8634 }
8635 case ISD::FNEG: {
8636 if (N->getValueType(0) != MVT::v2f16)
8637 break;
8638
8639 SDLoc SL(N);
8640 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
8641
8642 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, BC,
8643 DAG.getConstant(0x80008000, SL, MVT::i32));
8644 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
8645 return;
8646 }
8647 case ISD::FABS: {
8648 if (N->getValueType(0) != MVT::v2f16)
8649 break;
8650
8651 SDLoc SL(N);
8652 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
8653
8654 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, BC,
8655 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
8656 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
8657 return;
8658 }
8659 case ISD::FSQRT: {
8660 if (N->getValueType(0) != MVT::f16)
8661 break;
8662 Results.push_back(lowerFSQRTF16(SDValue(N, 0), DAG));
8663 break;
8664 }
8665 default:
8667 break;
8668 }
8669}
8670
8671/// Helper function for LowerBRCOND
8672static SDNode *findUser(SDValue Value, unsigned Opcode) {
8673
8674 for (SDUse &U : Value->uses()) {
8675 if (U.get() != Value)
8676 continue;
8677
8678 if (U.getUser()->getOpcode() == Opcode)
8679 return U.getUser();
8680 }
8681 return nullptr;
8682}
8683
8684unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
8685 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8686 switch (Intr->getConstantOperandVal(1)) {
8687 case Intrinsic::amdgcn_if:
8688 return AMDGPUISD::IF;
8689 case Intrinsic::amdgcn_else:
8690 return AMDGPUISD::ELSE;
8691 case Intrinsic::amdgcn_loop:
8692 return AMDGPUISD::LOOP;
8693 case Intrinsic::amdgcn_end_cf:
8694 llvm_unreachable("should not occur");
8695 default:
8696 return 0;
8697 }
8698 }
8699
8700 // break, if_break, else_break are all only used as inputs to loop, not
8701 // directly as branch conditions.
8702 return 0;
8703}
8704
8711
8713 if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS())
8714 return false;
8715
8716 // FIXME: Either avoid relying on address space here or change the default
8717 // address space for functions to avoid the explicit check.
8718 return (GV->getValueType()->isFunctionTy() ||
8721}
8722
8724 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
8725}
8726
8728 if (!GV->hasExternalLinkage())
8729 return true;
8730
8731 // With object linking, external LDS declarations need relocations so the
8732 // linker can assign their offsets.
8734 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
8735 if (GVar->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
8736 GVar->getAddressSpace() == AMDGPUAS::BARRIER) {
8737 assert(GVar->isDeclaration() &&
8738 "AS 3 & 13 GVs should be declaration here "
8739 "when object linking is enabled");
8740 return false;
8741 }
8742 }
8743 }
8744
8745 const auto OS = getTargetMachine().getTargetTriple().getOS();
8746 return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
8747}
8748
8749/// This transforms the control flow intrinsics to get the branch destination as
8750/// last parameter, also switches branch target with BR if the need arise
8751SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, SelectionDAG &DAG) const {
8752 SDLoc DL(BRCOND);
8753
8754 SDNode *Intr = BRCOND.getOperand(1).getNode();
8755 SDValue Target = BRCOND.getOperand(2);
8756 SDNode *BR = nullptr;
8757 SDNode *SetCC = nullptr;
8758
8759 switch (Intr->getOpcode()) {
8760 case ISD::SETCC: {
8761 // As long as we negate the condition everything is fine
8762 SetCC = Intr;
8763 Intr = SetCC->getOperand(0).getNode();
8764 break;
8765 }
8766 case ISD::XOR: {
8767 // Similar to SETCC, if we have (xor c, -1), we will be fine.
8768 SDValue LHS = Intr->getOperand(0);
8769 SDValue RHS = Intr->getOperand(1);
8770 if (auto *C = dyn_cast<ConstantSDNode>(RHS); C && C->getZExtValue()) {
8771 Intr = LHS.getNode();
8772 break;
8773 }
8774 [[fallthrough]];
8775 }
8776 default: {
8777 // Get the target from BR if we don't negate the condition
8778 BR = findUser(BRCOND, ISD::BR);
8779 assert(BR && "brcond missing unconditional branch user");
8780 Target = BR->getOperand(1);
8781 }
8782 }
8783
8784 unsigned CFNode = isCFIntrinsic(Intr);
8785 if (CFNode == 0) {
8786 // This is a uniform branch so we don't need to legalize.
8787 return BRCOND;
8788 }
8789
8790 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
8792
8793 assert(!SetCC || (SetCC->getConstantOperandVal(1) == 1 &&
8794 SetCC->getOperandCondCode(2) == ISD::SETNE));
8795
8796 // operands of the new intrinsic call
8798 if (HaveChain)
8799 Ops.push_back(BRCOND.getOperand(0));
8800
8801 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
8802 Ops.push_back(Target);
8803
8804 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
8805
8806 // build the new intrinsic call
8807 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
8808
8809 if (!HaveChain) {
8810 SDValue Ops[] = {SDValue(Result, 0), BRCOND.getOperand(0)};
8811
8813 }
8814
8815 if (BR) {
8816 // Give the branch instruction our target
8817 SDValue Ops[] = {BR->getOperand(0), BRCOND.getOperand(2)};
8818 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
8819 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
8820 }
8821
8822 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
8823
8824 // Copy the intrinsic results to registers
8825 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
8826 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
8827 if (!CopyToReg)
8828 continue;
8829
8830 Chain = DAG.getCopyToReg(Chain, DL, CopyToReg->getOperand(1),
8831 SDValue(Result, i - 1), SDValue());
8832
8833 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
8834 }
8835
8836 // Remove the old intrinsic from the chain
8837 DAG.ReplaceAllUsesOfValueWith(SDValue(Intr, Intr->getNumValues() - 1),
8838 Intr->getOperand(0));
8839
8840 return Chain;
8841}
8842
8843SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
8844 MVT VT = Op.getSimpleValueType();
8845 SDLoc DL(Op);
8846 // Checking the depth
8847 if (Op.getConstantOperandVal(0) != 0)
8848 return DAG.getConstant(0, DL, VT);
8849
8851 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8852 // Check for kernel and shader functions
8853 if (Info->isEntryFunction())
8854 return DAG.getConstant(0, DL, VT);
8855
8856 MachineFrameInfo &MFI = MF.getFrameInfo();
8857 // There is a call to @llvm.returnaddress in this function
8858 MFI.setReturnAddressIsTaken(true);
8859
8860 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
8861 // Get the return address reg and mark it as an implicit live-in
8862 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF),
8863 getRegClassFor(VT, Op.getNode()->isDivergent()));
8864
8865 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
8866}
8867
8868SDValue SITargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
8870 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8871
8872 // For functions that set up their own stack, select the GET_STACK_BASE
8873 // pseudo.
8874 if (MFI->isBottomOfStack())
8875 return Op;
8876
8877 // For everything else, create a dummy stack object.
8878 int FI = MF.getFrameInfo().CreateFixedObject(1, 0, /*IsImmutable=*/false);
8879 return DAG.getFrameIndex(FI, Op.getValueType());
8880}
8881
8882SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, SDValue Op,
8883 const SDLoc &DL, EVT VT) const {
8884 return Op.getValueType().bitsLE(VT)
8885 ? DAG.getNode(ISD::FP_EXTEND, DL, VT, Op)
8886 : DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
8887 DAG.getTargetConstant(0, DL, MVT::i32));
8888}
8889
8890SDValue SITargetLowering::splitFP_ROUNDVectorOp(SDValue Op,
8891 SelectionDAG &DAG) const {
8892 EVT DstVT = Op.getValueType();
8893 unsigned NumElts = DstVT.getVectorNumElements();
8894 assert(NumElts > 2 && isPowerOf2_32(NumElts));
8895
8896 auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
8897
8898 SDLoc DL(Op);
8899 unsigned Opc = Op.getOpcode();
8900 SDValue Flags = Op.getOperand(1);
8901 EVT HalfDstVT =
8902 EVT::getVectorVT(*DAG.getContext(), DstVT.getScalarType(), NumElts / 2);
8903 SDValue OpLo = DAG.getNode(Opc, DL, HalfDstVT, Lo, Flags);
8904 SDValue OpHi = DAG.getNode(Opc, DL, HalfDstVT, Hi, Flags);
8905
8906 return DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, OpLo, OpHi);
8907}
8908
8909SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
8910 bool IsStrict = Op->isStrictFPOpcode();
8911 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8912 EVT SrcVT = Src.getValueType();
8913 EVT DstVT = Op.getValueType();
8914
8915 if (DstVT.isVectorOf(MVT::f16)) {
8916 assert(Subtarget->hasCvtPkF16F32Inst() && "support v_cvt_pk_f16_f32");
8917 if (SrcVT.getScalarType() != MVT::f32)
8918 return SDValue();
8919 return SrcVT == MVT::v2f32 ? Op : splitFP_ROUNDVectorOp(Op, DAG);
8920 }
8921
8922 if (SrcVT.getScalarType() != MVT::f64)
8923 return Op;
8924
8925 SDLoc DL(Op);
8926 if (DstVT == MVT::f16) {
8927 // TODO: Handle strictfp
8928 if (Op.getOpcode() != ISD::FP_ROUND)
8929 return Op;
8930
8931 if (!Subtarget->has16BitInsts()) {
8932 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
8933 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
8934 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
8935 }
8936 if (Op->getFlags().hasApproximateFuncs()) {
8937 SDValue Flags = Op.getOperand(1);
8938 SDValue Src32 = DAG.getNode(ISD::FP_ROUND, DL, MVT::f32, Src, Flags);
8939 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Src32, Flags);
8940 }
8941 SDValue FpToFp16 = LowerF64ToF16Safe(Src, DL, DAG);
8942 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
8943 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
8944 }
8945
8946 assert(DstVT.getScalarType() == MVT::bf16 &&
8947 "custom lower FP_ROUND for f16 or bf16");
8948 assert(Subtarget->hasBF16ConversionInsts() && "f32 -> bf16 is legal");
8949
8950 // Round-inexact-to-odd f64 to f32, then do the final rounding using the
8951 // hardware f32 -> bf16 instruction.
8952 EVT F32VT = SrcVT.changeElementType(*DAG.getContext(), MVT::f32);
8953 SDValue Rod = expandRoundInexactToOdd(F32VT, Src, DL, DAG);
8954 if (IsStrict) {
8955 return DAG.getNode(
8956 ISD::STRICT_FP_ROUND, DL, {DstVT, MVT::Other},
8957 {Op.getOperand(0), Rod, DAG.getTargetConstant(0, DL, MVT::i32)});
8958 }
8959 return DAG.getNode(ISD::FP_ROUND, DL, DstVT, Rod,
8960 DAG.getTargetConstant(0, DL, MVT::i32));
8961}
8962
8963SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
8964 SelectionDAG &DAG) const {
8965 EVT VT = Op.getValueType();
8966 const MachineFunction &MF = DAG.getMachineFunction();
8967 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8968 bool IsIEEEMode = Info->getMode().IEEE;
8969
8970 // FIXME: Assert during selection that this is only selected for
8971 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
8972 // mode functions, but this happens to be OK since it's only done in cases
8973 // where there is known no sNaN.
8974 if (IsIEEEMode && !Subtarget->hasIEEEMinimumMaximumInsts())
8975 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
8976
8977 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
8978 VT == MVT::v32f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16 ||
8979 VT == MVT::v16bf16 || VT == MVT::v32bf16 || VT == MVT::v4f64 ||
8980 VT == MVT::v8f64 || VT == MVT::v16f64 || VT == MVT::v32f64)
8981 return splitBinaryVectorOp(Op, DAG);
8982 return Op;
8983}
8984
8985SDValue
8986SITargetLowering::lowerFMINIMUMNUM_FMAXIMUMNUM(SDValue Op,
8987 SelectionDAG &DAG) const {
8988 EVT VT = Op.getValueType();
8989 const MachineFunction &MF = DAG.getMachineFunction();
8990 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8991 bool IsIEEEMode = Info->getMode().IEEE;
8992
8993 if (IsIEEEMode && !Subtarget->hasIEEEMinimumMaximumInsts())
8994 return expandFMINIMUMNUM_FMAXIMUMNUM(Op.getNode(), DAG);
8995
8996 if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
8997 VT == MVT::v32f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16 ||
8998 VT == MVT::v16bf16 || VT == MVT::v32bf16 || VT == MVT::v4f64 ||
8999 VT == MVT::v8f64 || VT == MVT::v16f64 || VT == MVT::v32f64)
9000 return splitBinaryVectorOp(Op, DAG);
9001 return Op;
9002}
9003
9004SDValue SITargetLowering::lowerFLDEXP(SDValue Op, SelectionDAG &DAG) const {
9005 bool IsStrict = Op.getOpcode() == ISD::STRICT_FLDEXP;
9006 EVT VT = Op.getValueType();
9007 assert(VT == MVT::f16);
9008
9009 SDValue Exp = Op.getOperand(IsStrict ? 2 : 1);
9010 EVT ExpVT = Exp.getValueType();
9011 if (ExpVT == MVT::i16)
9012 return Op;
9013
9014 SDLoc DL(Op);
9015
9016 // Correct the exponent type for f16 to i16.
9017 // Clamp the range of the exponent to the instruction's range.
9018
9019 // TODO: This should be a generic narrowing legalization, and can easily be
9020 // for GlobalISel.
9021
9022 SDValue MinExp = DAG.getSignedConstant(minIntN(16), DL, ExpVT);
9023 SDValue ClampMin = DAG.getNode(ISD::SMAX, DL, ExpVT, Exp, MinExp);
9024
9025 SDValue MaxExp = DAG.getSignedConstant(maxIntN(16), DL, ExpVT);
9026 SDValue Clamp = DAG.getNode(ISD::SMIN, DL, ExpVT, ClampMin, MaxExp);
9027
9028 SDValue TruncExp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Clamp);
9029
9030 if (IsStrict) {
9031 return DAG.getNode(ISD::STRICT_FLDEXP, DL, {VT, MVT::Other},
9032 {Op.getOperand(0), Op.getOperand(1), TruncExp});
9033 }
9034
9035 return DAG.getNode(ISD::FLDEXP, DL, VT, Op.getOperand(0), TruncExp);
9036}
9037
9039 switch (Op->getOpcode()) {
9040 case ISD::ABS:
9041 case ISD::SRA:
9042 case ISD::SMIN:
9043 case ISD::SMAX:
9044 return ISD::SIGN_EXTEND;
9045 case ISD::SRL:
9046 case ISD::UMIN:
9047 case ISD::UMAX:
9048 case ISD::USUBSAT:
9049 case ISD::UADDSAT:
9050 return ISD::ZERO_EXTEND;
9051 case ISD::ADD:
9052 case ISD::SUB:
9053 case ISD::AND:
9054 case ISD::OR:
9055 case ISD::XOR:
9056 case ISD::SHL:
9057 case ISD::SELECT:
9058 case ISD::MUL:
9059 // operation result won't be influenced by garbage high bits.
9060 // TODO: are all of those cases correct, and are there more?
9061 return ISD::ANY_EXTEND;
9062 case ISD::SETCC: {
9063 ISD::CondCode CC = Op.getOperandCondCode(2);
9065 }
9066 default:
9067 llvm_unreachable("unexpected opcode!");
9068 }
9069}
9070
9071SDValue
9072SITargetLowering::promoteUniformUnaryOpToI32(SDValue Op,
9073 DAGCombinerInfo &DCI) const {
9074 EVT OpTy = Op.getValueType();
9075 SelectionDAG &DAG = DCI.DAG;
9076 EVT ExtTy = OpTy.changeElementType(*DAG.getContext(), MVT::i32);
9077
9078 if (isNarrowingProfitable(Op.getNode(), ExtTy, OpTy))
9079 return SDValue();
9080
9081 SDLoc DL(Op);
9082 SDValue Input = Op.getOperand(0);
9083 const unsigned ExtOp = getExtOpcodeForPromotedOp(Op);
9084 Input = DAG.getNode(ExtOp, DL, ExtTy, Input);
9085
9086 SDValue NewVal = DAG.getNode(Op.getOpcode(), DL, ExtTy, Input);
9087
9088 return DAG.getNode(ISD::TRUNCATE, DL, OpTy, NewVal);
9089}
9090
9091SDValue SITargetLowering::promoteUniformOpToI32(SDValue Op,
9092 DAGCombinerInfo &DCI) const {
9093 const unsigned Opc = Op.getOpcode();
9094 assert(Opc == ISD::ADD || Opc == ISD::SUB || Opc == ISD::SHL ||
9095 Opc == ISD::SRL || Opc == ISD::SRA || Opc == ISD::AND ||
9096 Opc == ISD::OR || Opc == ISD::XOR || Opc == ISD::MUL ||
9097 Opc == ISD::SETCC || Opc == ISD::SELECT || Opc == ISD::SMIN ||
9098 Opc == ISD::SMAX || Opc == ISD::UMIN || Opc == ISD::UMAX ||
9099 Opc == ISD::USUBSAT || Opc == ISD::UADDSAT);
9100
9101 EVT OpTy = (Opc != ISD::SETCC) ? Op.getValueType()
9102 : Op->getOperand(0).getValueType();
9103 auto &DAG = DCI.DAG;
9104 auto ExtTy = OpTy.changeElementType(*DAG.getContext(), MVT::i32);
9105
9106 if (DCI.isBeforeLegalizeOps() ||
9107 isNarrowingProfitable(Op.getNode(), ExtTy, OpTy))
9108 return SDValue();
9109
9110 SDLoc DL(Op);
9111 SDValue LHS;
9112 SDValue RHS;
9113 if (Opc == ISD::SELECT) {
9114 LHS = Op->getOperand(1);
9115 RHS = Op->getOperand(2);
9116 } else {
9117 LHS = Op->getOperand(0);
9118 RHS = Op->getOperand(1);
9119 }
9120
9121 const unsigned ExtOp = getExtOpcodeForPromotedOp(Op);
9122 LHS = DAG.getNode(ExtOp, DL, ExtTy, {LHS});
9123
9124 // Special case: for shifts, the RHS always needs a zext.
9125 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
9126 RHS = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtTy, {RHS});
9127 else
9128 RHS = DAG.getNode(ExtOp, DL, ExtTy, {RHS});
9129
9130 // setcc always return i1/i1 vec so no need to truncate after.
9131 if (Opc == ISD::SETCC) {
9132 ISD::CondCode CC = Op.getOperandCondCode(2);
9133 return DAG.getSetCC(DL, Op.getValueType(), LHS, RHS, CC);
9134 }
9135
9136 // For other ops, we extend the operation's return type as well so we need to
9137 // truncate back to the original type.
9138 SDValue NewVal;
9139 if (Opc == ISD::SELECT)
9140 NewVal = DAG.getNode(ISD::SELECT, DL, ExtTy, {Op->getOperand(0), LHS, RHS});
9141 else if (Opc == ISD::UADDSAT) {
9142 SDValue Sum = DAG.getNode(ISD::ADD, DL, ExtTy, LHS, RHS);
9143 SDValue MaxVal = DAG.getConstant(
9144 APInt::getMaxValue(OpTy.getScalarSizeInBits()).zext(32), DL, ExtTy);
9145 NewVal = DAG.getNode(ISD::UMIN, DL, ExtTy, Sum, MaxVal);
9146 } else
9147 NewVal = DAG.getNode(Opc, DL, ExtTy, {LHS, RHS});
9148
9149 return DAG.getZExtOrTrunc(NewVal, DL, OpTy);
9150}
9151
9152SDValue SITargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9153 SDValue Mag = Op.getOperand(0);
9154 EVT MagVT = Mag.getValueType();
9155
9156 if (MagVT.getVectorNumElements() > 2)
9157 return splitBinaryVectorOp(Op, DAG);
9158
9159 SDValue Sign = Op.getOperand(1);
9160 EVT SignVT = Sign.getValueType();
9161
9162 if (MagVT == SignVT)
9163 return Op;
9164
9165 // fcopysign v2f16:mag, v2f32:sign ->
9166 // fcopysign v2f16:mag,
9167 // bitcast (trunc (srl (bitcast sign to v2i32), 16) to v2i16)
9168
9169 SDLoc SL(Op);
9170 SDValue SignAsInt32 = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Sign);
9171 SDValue ShiftAmt = DAG.getShiftAmountConstant(16, MVT::v2i32, SL);
9172 SDValue SignShifted =
9173 DAG.getNode(ISD::SRL, SL, MVT::v2i32, SignAsInt32, ShiftAmt);
9174 SDValue SignAsInt16 = DAG.getNode(ISD::TRUNCATE, SL, MVT::v2i16, SignShifted);
9175
9176 SDValue SignAsHalf16 = DAG.getNode(ISD::BITCAST, SL, MagVT, SignAsInt16);
9177
9178 return DAG.getNode(ISD::FCOPYSIGN, SL, MagVT, Mag, SignAsHalf16);
9179}
9180
9181// Custom lowering for vector multiplications and s_mul_u64.
9182SDValue SITargetLowering::lowerMUL(SDValue Op, SelectionDAG &DAG) const {
9183 EVT VT = Op.getValueType();
9184
9185 // Split vector operands.
9186 if (VT.isVector())
9187 return splitBinaryVectorOp(Op, DAG);
9188
9189 assert(VT == MVT::i64 && "The following code is a special for s_mul_u64");
9190
9191 // There are four ways to lower s_mul_u64:
9192 //
9193 // 1. If all the operands are uniform, then we lower it as it is.
9194 //
9195 // 2. If the operands are divergent, then we have to split s_mul_u64 in 32-bit
9196 // multiplications because there is not a vector equivalent of s_mul_u64.
9197 //
9198 // 3. If the cost model decides that it is more efficient to use vector
9199 // registers, then we have to split s_mul_u64 in 32-bit multiplications.
9200 // This happens in splitScalarSMULU64() in SIInstrInfo.cpp .
9201 //
9202 // 4. If the cost model decides to use vector registers and both of the
9203 // operands are zero-extended/sign-extended from 32-bits, then we split the
9204 // s_mul_u64 in two 32-bit multiplications. The problem is that it is not
9205 // possible to check if the operands are zero-extended or sign-extended in
9206 // SIInstrInfo.cpp. For this reason, here, we replace s_mul_u64 with
9207 // s_mul_u64_u32_pseudo if both operands are zero-extended and we replace
9208 // s_mul_u64 with s_mul_i64_i32_pseudo if both operands are sign-extended.
9209 // If the cost model decides that we have to use vector registers, then
9210 // splitScalarSMulPseudo() (in SIInstrInfo.cpp) split s_mul_u64_u32/
9211 // s_mul_i64_i32_pseudo in two vector multiplications. If the cost model
9212 // decides that we should use scalar registers, then s_mul_u64_u32_pseudo/
9213 // s_mul_i64_i32_pseudo is lowered as s_mul_u64 in expandPostRAPseudo() in
9214 // SIInstrInfo.cpp .
9215
9216 if (Op->isDivergent())
9217 return SDValue();
9218
9219 SDValue Op0 = Op.getOperand(0);
9220 SDValue Op1 = Op.getOperand(1);
9221 // If all the operands are zero-enteted to 32-bits, then we replace s_mul_u64
9222 // with s_mul_u64_u32_pseudo. If all the operands are sign-extended to
9223 // 32-bits, then we replace s_mul_u64 with s_mul_i64_i32_pseudo.
9224 KnownBits Op0KnownBits = DAG.computeKnownBits(Op0);
9225 unsigned Op0LeadingZeros = Op0KnownBits.countMinLeadingZeros();
9226 KnownBits Op1KnownBits = DAG.computeKnownBits(Op1);
9227 unsigned Op1LeadingZeros = Op1KnownBits.countMinLeadingZeros();
9228 SDLoc SL(Op);
9229 if (Op0LeadingZeros >= 32 && Op1LeadingZeros >= 32)
9230 return SDValue(
9231 DAG.getMachineNode(AMDGPU::S_MUL_U64_U32_PSEUDO, SL, VT, Op0, Op1), 0);
9232 unsigned Op0SignBits = DAG.ComputeNumSignBits(Op0);
9233 unsigned Op1SignBits = DAG.ComputeNumSignBits(Op1);
9234 if (Op0SignBits >= 33 && Op1SignBits >= 33)
9235 return SDValue(
9236 DAG.getMachineNode(AMDGPU::S_MUL_I64_I32_PSEUDO, SL, VT, Op0, Op1), 0);
9237 // If all the operands are uniform, then we lower s_mul_u64 as it is.
9238 return Op;
9239}
9240
9241SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
9242 EVT VT = Op.getValueType();
9243 SDLoc SL(Op);
9244 SDValue LHS = Op.getOperand(0);
9245 SDValue RHS = Op.getOperand(1);
9246 bool isSigned = Op.getOpcode() == ISD::SMULO;
9247
9248 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
9249 const APInt &C = RHSC->getAPIntValue();
9250 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
9251 if (C.isPowerOf2()) {
9252 // smulo(x, signed_min) is same as umulo(x, signed_min).
9253 bool UseArithShift = isSigned && !C.isMinSignedValue();
9254 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
9255 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
9256 SDValue Overflow =
9257 DAG.getSetCC(SL, MVT::i1,
9258 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, SL, VT,
9259 Result, ShiftAmt),
9260 LHS, ISD::SETNE);
9261 return DAG.getMergeValues({Result, Overflow}, SL);
9262 }
9263 }
9264
9265 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
9266 SDValue Top =
9267 DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, SL, VT, LHS, RHS);
9268
9270 ? DAG.getNode(ISD::SRA, SL, VT, Result,
9271 DAG.getConstant(VT.getScalarSizeInBits() - 1,
9272 SL, MVT::i32))
9273 : DAG.getConstant(0, SL, VT);
9274 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
9275
9276 return DAG.getMergeValues({Result, Overflow}, SL);
9277}
9278
9279SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
9280 if (Op->isDivergent()) {
9281 // Select to V_MAD_[IU]64_[IU]32.
9282 return Op;
9283 }
9284 if (Subtarget->hasSMulHi()) {
9285 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
9286 return SDValue();
9287 }
9288 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
9289 // calculate the high part, so we might as well do the whole thing with
9290 // V_MAD_[IU]64_[IU]32.
9291 return Op;
9292}
9293
9294SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
9295 if (!Subtarget->hasTrapHandler() ||
9296 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
9297 return lowerTrapEndpgm(Op, DAG);
9298
9299 return Subtarget->supportsGetDoorbellID() ? lowerTrapHsa(Op, DAG)
9300 : lowerTrapHsaQueuePtr(Op, DAG);
9301}
9302
9303SDValue SITargetLowering::lowerTrapEndpgm(SDValue Op, SelectionDAG &DAG) const {
9304 SDLoc SL(Op);
9305 SDValue Chain = Op.getOperand(0);
9306 return DAG.getNode(AMDGPUISD::ENDPGM_TRAP, SL, MVT::Other, Chain);
9307}
9308
9309SDValue
9310SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
9311 const SDLoc &DL, Align Alignment,
9312 ImplicitParameter Param) const {
9315 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
9316 MachinePointerInfo PtrInfo =
9318 return DAG.getLoad(
9319 VT, DL, DAG.getEntryNode(), Ptr, PtrInfo.getWithOffset(Offset), Alignment,
9321}
9322
9323SDValue SITargetLowering::lowerTrapHsaQueuePtr(SDValue Op,
9324 SelectionDAG &DAG) const {
9325 SDLoc SL(Op);
9326 SDValue Chain = Op.getOperand(0);
9327
9328 SDValue QueuePtr;
9329 // For code object version 5, QueuePtr is passed through implicit kernarg.
9330 const Module *M = DAG.getMachineFunction().getFunction().getParent();
9332 QueuePtr =
9333 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
9334 } else {
9336 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9337 Register UserSGPR = Info->getQueuePtrUserSGPR();
9338
9339 if (UserSGPR == AMDGPU::NoRegister) {
9340 // We probably are in a function incorrectly marked with
9341 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
9342 // trap, so just use a null pointer.
9343 QueuePtr = DAG.getConstant(0, SL, MVT::i64);
9344 } else {
9345 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
9346 MVT::i64);
9347 }
9348 }
9349
9350 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
9351 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, QueuePtr, SDValue());
9352
9354 SDValue Ops[] = {ToReg, DAG.getTargetConstant(TrapID, SL, MVT::i16), SGPR01,
9355 ToReg.getValue(1)};
9356 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9357}
9358
9359SDValue SITargetLowering::lowerTrapHsa(SDValue Op, SelectionDAG &DAG) const {
9360 SDLoc SL(Op);
9361 SDValue Chain = Op.getOperand(0);
9362
9363 // We need to simulate the 's_trap 2' instruction on targets that run in
9364 // PRIV=1 (where it is treated as a nop).
9365 if (Subtarget->hasPrivEnabledTrap2NopBug())
9366 return DAG.getNode(AMDGPUISD::SIMULATED_TRAP, SL, MVT::Other, Chain);
9367
9369 SDValue Ops[] = {Chain, DAG.getTargetConstant(TrapID, SL, MVT::i16)};
9370 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9371}
9372
9373SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
9374 SDLoc SL(Op);
9375 SDValue Chain = Op.getOperand(0);
9377
9378 if (!Subtarget->hasTrapHandler() ||
9379 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
9380 LLVMContext &Ctx = MF.getFunction().getContext();
9381 Ctx.diagnose(DiagnosticInfoUnsupported(MF.getFunction(),
9382 "debugtrap handler not supported",
9383 Op.getDebugLoc(), DS_Warning));
9384 return Chain;
9385 }
9386
9387 uint64_t TrapID =
9389 SDValue Ops[] = {Chain, DAG.getTargetConstant(TrapID, SL, MVT::i16)};
9390 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
9391}
9392
9393/// When a divergent value (in VGPR) is passed to an inline asm with an SGPR
9394/// constraint ('s'), we need to insert v_readfirstlane to move the value from
9395/// VGPR to SGPR. This is done by modifying the CopyToReg nodes in the glue
9396/// chain that feed into the INLINEASM node.
9397SDValue SITargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
9398 unsigned NumOps = Op.getNumOperands();
9399
9400 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
9401 SmallSet<Register, 8> SGPRInputRegs;
9402
9403 unsigned NumVals = 0;
9404 for (unsigned I = InlineAsm::Op_FirstOperand; I < NumOps - 1;
9405 I += 1 + NumVals) {
9406 const InlineAsm::Flag Flags(Op.getConstantOperandVal(I));
9407 NumVals = Flags.getNumOperandRegisters();
9408
9409 unsigned RCID;
9410 bool IsSGPRInput = Flags.getKind() == InlineAsm::Kind::RegUse &&
9411 NumVals > 0 && Flags.hasRegClassConstraint(RCID) &&
9412 TRI->isSGPRClass(TRI->getRegClass(RCID));
9413
9414 for (unsigned J = 0; J < NumVals; ++J) {
9415 SDValue Val = Op.getOperand(I + 1 + J);
9416 if (const RegisterSDNode *RegNode =
9418 Register Reg = RegNode->getReg();
9419 if (IsSGPRInput || (Reg.isPhysical() && TRI->isSGPRPhysReg(Reg)))
9420 SGPRInputRegs.insert(Reg);
9421 }
9422 }
9423 }
9424
9425 if (SGPRInputRegs.empty())
9426 return Op;
9427
9428 // Walk the glue chain and insert readfirstlane for divergent SGPR inputs.
9429 SDLoc DL(Op);
9430 SDNode *N = Op.getOperand(NumOps - 1).getNode();
9431
9432 while (N && N->getOpcode() == ISD::CopyToReg) {
9433 Register Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
9434 SDValue SrcVal = N->getOperand(2);
9435
9436 // Insert readfirstlane if copying a divergent value to an SGPR input.
9437 if (SrcVal->isDivergent() && SGPRInputRegs.count(Reg)) {
9438 SDValue ReadFirstLaneID =
9439 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
9440 SDValue ReadFirstLane =
9442 ReadFirstLaneID, SrcVal);
9443
9444 SmallVector<SDValue, 4> Ops = {N->getOperand(0), N->getOperand(1),
9445 ReadFirstLane};
9446 if (N->getNumOperands() > 3)
9447 Ops.push_back(N->getOperand(3)); // Glue input
9448
9449 DAG.UpdateNodeOperands(N, Ops);
9450 }
9451
9452 // Follow glue chain to next CopyToReg.
9453 SDNode *Next = nullptr;
9454 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I) {
9455 if (N->getOperand(I).getValueType() == MVT::Glue) {
9456 Next = N->getOperand(I).getNode();
9457 break;
9458 }
9459 }
9460 N = Next;
9461 }
9462
9463 return Op;
9464}
9465
9466SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
9467 SelectionDAG &DAG) const {
9468 unsigned BaseAS = AS;
9469 unsigned SANum = AMDGPU::getSyntheticApertureNumber(AS);
9471 BaseAS = AMDGPUAS::LOCAL_ADDRESS;
9472
9473 SDValue Aperture = getBaseSegmentAperture(BaseAS, DL, DAG);
9474
9475 if (SANum != AMDGPU::SyntheticAperture::None) {
9476 SDValue Tag = DAG.getConstant(SANum, DL, MVT::i32);
9477 return DAG.getNode(ISD::OR, DL, MVT::i32, Aperture, Tag);
9478 }
9479
9480 return Aperture;
9481}
9482
9483SDValue SITargetLowering::getBaseSegmentAperture(unsigned AS, const SDLoc &DL,
9484 SelectionDAG &DAG) const {
9485 const bool IsLDS = (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::BARRIER);
9486
9487 if (Subtarget->hasApertureRegs()) {
9488 const unsigned ApertureRegNo =
9489 IsLDS ? AMDGPU::SRC_SHARED_BASE : AMDGPU::SRC_PRIVATE_BASE;
9490 assert((ApertureRegNo != AMDGPU::SRC_PRIVATE_BASE ||
9491 !Subtarget->hasGloballyAddressableScratch()) &&
9492 "Cannot use src_private_base with globally addressable scratch!");
9493 // Note: this feature (register) is broken. When used as a 32-bit operand,
9494 // it returns a wrong value (all zeroes?). The real value is in the upper 32
9495 // bits.
9496 //
9497 // To work around the issue, emit a 64 bit copy from this register
9498 // then extract the high bits. Note that this shouldn't even result in a
9499 // shift being emitted and simply become a pair of registers (e.g.):
9500 // s_mov_b64 s[6:7], src_shared_base
9501 // v_mov_b32_e32 v1, s7
9502 SDValue Copy =
9503 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ApertureRegNo, MVT::v2i32);
9504 return DAG.getExtractVectorElt(DL, MVT::i32, Copy, 1);
9505 }
9506
9507 // For code object version 5, private_base and shared_base are passed through
9508 // implicit kernargs.
9509 const Module *M = DAG.getMachineFunction().getFunction().getParent();
9512 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
9513 }
9514
9516 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9517 Register UserSGPR = Info->getQueuePtrUserSGPR();
9518 if (UserSGPR == AMDGPU::NoRegister) {
9519 // We probably are in a function incorrectly marked with
9520 // amdgpu-no-queue-ptr. This is undefined.
9521 return DAG.getPOISON(MVT::i32);
9522 }
9523
9524 SDValue QueuePtr =
9525 CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
9526
9527 // Offset into amd_queue_t for group_segment_aperture_base_hi /
9528 // private_segment_aperture_base_hi.
9529 uint32_t StructOffset = IsLDS ? 0x40 : 0x44;
9530
9531 SDValue Ptr =
9532 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::getFixed(StructOffset));
9533
9534 // TODO: Use custom target PseudoSourceValue.
9535 // TODO: We should use the value from the IR intrinsic call, but it might not
9536 // be available and how do we get it?
9537 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
9538 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
9539 commonAlignment(Align(64), StructOffset),
9542}
9543
9544/// Return true if the value is a known valid address, such that a null check is
9545/// not necessary.
9547 const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
9549 return true;
9550
9551 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
9552 return ConstVal->getSExtValue() != AMDGPU::getNullPointerValue(AddrSpace);
9553
9554 // TODO: Search through arithmetic, handle arguments and loads
9555 // marked nonnull.
9556 return false;
9557}
9558
9559SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
9560 SelectionDAG &DAG) const {
9561 SDLoc SL(Op);
9562
9563 const AMDGPUTargetMachine &TM =
9564 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
9565
9566 const auto *ASC = cast<AddrSpaceCastSDNode>(Op);
9567 unsigned SrcAS = ASC->getSrcAddressSpace();
9568 SDValue Src = ASC->getOperand(0);
9569 unsigned DestAS = ASC->getDestAddressSpace();
9570 bool IsNonNull = ASC->getFlags().hasNonNull();
9571
9572 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
9573
9574 // flat -> local/private/barrier/vgpr
9575 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
9576 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
9577 DestAS == AMDGPUAS::PRIVATE_ADDRESS || DestAS == AMDGPUAS::BARRIER ||
9578 DestAS == AMDGPUAS::VGPR) {
9579 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
9580
9581 if (DestAS == AMDGPUAS::PRIVATE_ADDRESS &&
9582 Subtarget->hasGloballyAddressableScratch()) {
9583 // flat -> private with globally addressable scratch: subtract
9584 // src_flat_scratch_base_lo.
9585 SDValue FlatScratchBaseLo(
9586 DAG.getMachineNode(
9587 AMDGPU::S_MOV_B32, SL, MVT::i32,
9588 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_LO, MVT::i32)),
9589 0);
9590 Ptr = DAG.getNode(ISD::SUB, SL, MVT::i32, Ptr, FlatScratchBaseLo);
9591 }
9592
9593 if (IsNonNull || isKnownNonNull(Src, DAG, TM, SrcAS))
9594 return Ptr;
9595
9596 unsigned NullVal = AMDGPU::getNullPointerValue(DestAS);
9597 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
9598 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
9599
9600 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
9601 SegmentNullPtr);
9602 }
9603 }
9604
9605 // local/private/barrier/vgpr -> flat
9606 if (DestAS == AMDGPUAS::FLAT_ADDRESS) {
9607 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
9608 SrcAS == AMDGPUAS::PRIVATE_ADDRESS || SrcAS == AMDGPUAS::BARRIER ||
9609 SrcAS == AMDGPUAS::VGPR) {
9610 SDValue CvtPtr;
9611 if (SrcAS == AMDGPUAS::PRIVATE_ADDRESS &&
9612 Subtarget->hasGloballyAddressableScratch()) {
9613 // For wave32: Addr = (TID[4:0] << 52) + FLAT_SCRATCH_BASE + privateAddr
9614 // For wave64: Addr = (TID[5:0] << 51) + FLAT_SCRATCH_BASE + privateAddr
9615 SDValue AllOnes = DAG.getSignedTargetConstant(-1, SL, MVT::i32);
9616 SDValue ThreadID = DAG.getConstant(0, SL, MVT::i32);
9617 ThreadID = DAG.getNode(
9618 ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
9619 DAG.getTargetConstant(Intrinsic::amdgcn_mbcnt_lo, SL, MVT::i32),
9620 AllOnes, ThreadID);
9621 if (Subtarget->isWave64())
9622 ThreadID = DAG.getNode(
9623 ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32,
9624 DAG.getTargetConstant(Intrinsic::amdgcn_mbcnt_hi, SL, MVT::i32),
9625 AllOnes, ThreadID);
9626 SDValue ShAmt = DAG.getShiftAmountConstant(
9627 57 - 32 - Subtarget->getWavefrontSizeLog2(), MVT::i32, SL);
9628 SDValue SrcHi = DAG.getNode(ISD::SHL, SL, MVT::i32, ThreadID, ShAmt);
9629 CvtPtr = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, SrcHi);
9630 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
9631 // Accessing src_flat_scratch_base_lo as a 64-bit operand gives the full
9632 // 64-bit hi:lo value.
9633 SDValue FlatScratchBase = {
9634 DAG.getMachineNode(
9635 AMDGPU::S_MOV_B64, SL, MVT::i64,
9636 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE, MVT::i64)),
9637 0};
9638 CvtPtr = DAG.getNode(ISD::ADD, SL, MVT::i64, CvtPtr, FlatScratchBase);
9639 } else {
9640 SDValue Aperture = getSegmentAperture(SrcAS, SL, DAG);
9641
9642 CvtPtr = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
9643 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
9644 }
9645
9646 if (IsNonNull || isKnownNonNull(Src, DAG, TM, SrcAS))
9647 return CvtPtr;
9648
9649 unsigned NullVal = AMDGPU::getNullPointerValue(SrcAS);
9650 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
9651
9652 SDValue NonNull =
9653 DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
9654
9655 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
9656 FlatNullPtr);
9657 }
9658 }
9659
9660 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9661 Op.getValueType() == MVT::i64) {
9662 const SIMachineFunctionInfo *Info =
9663 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
9664 if (Info->get32BitAddressHighBits() == 0)
9665 return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, Src);
9666
9667 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
9668 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
9669 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9670 }
9671
9672 if (DestAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9673 Src.getValueType() == MVT::i64)
9674 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
9675
9676 // global <-> flat are no-ops and never emitted.
9677
9678 // Invalid casts are poison.
9679 return DAG.getPOISON(Op->getValueType(0));
9680}
9681
9682// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
9683// the small vector and inserting them into the big vector. That is better than
9684// the default expansion of doing it via a stack slot. Even though the use of
9685// the stack slot would be optimized away afterwards, the stack slot itself
9686// remains.
9687SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
9688 SelectionDAG &DAG) const {
9689 SDValue Vec = Op.getOperand(0);
9690 SDValue Ins = Op.getOperand(1);
9691 SDValue Idx = Op.getOperand(2);
9692 EVT VecVT = Vec.getValueType();
9693 EVT InsVT = Ins.getValueType();
9694 EVT EltVT = VecVT.getVectorElementType();
9695 unsigned InsNumElts = InsVT.getVectorNumElements();
9696 unsigned IdxVal = Idx->getAsZExtVal();
9697 SDLoc SL(Op);
9698
9699 if (EltVT.getScalarSizeInBits() == 16 && IdxVal % 2 == 0) {
9700 // Insert 32-bit registers at a time.
9701 assert(InsNumElts % 2 == 0 && "expect legal vector types");
9702
9703 unsigned VecNumElts = VecVT.getVectorNumElements();
9704 EVT NewVecVT =
9705 EVT::getVectorVT(*DAG.getContext(), MVT::i32, VecNumElts / 2);
9706 EVT NewInsVT = InsNumElts == 2 ? MVT::i32
9708 MVT::i32, InsNumElts / 2);
9709
9710 Vec = DAG.getNode(ISD::BITCAST, SL, NewVecVT, Vec);
9711 Ins = DAG.getNode(ISD::BITCAST, SL, NewInsVT, Ins);
9712
9713 for (unsigned I = 0; I != InsNumElts / 2; ++I) {
9714 SDValue Elt;
9715 if (InsNumElts == 2) {
9716 Elt = Ins;
9717 } else {
9718 Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Ins,
9719 DAG.getConstant(I, SL, MVT::i32));
9720 }
9721 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NewVecVT, Vec, Elt,
9722 DAG.getConstant(IdxVal / 2 + I, SL, MVT::i32));
9723 }
9724
9725 return DAG.getNode(ISD::BITCAST, SL, VecVT, Vec);
9726 }
9727
9728 for (unsigned I = 0; I != InsNumElts; ++I) {
9729 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
9730 DAG.getConstant(I, SL, MVT::i32));
9731 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
9732 DAG.getConstant(IdxVal + I, SL, MVT::i32));
9733 }
9734 return Vec;
9735}
9736
9737SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
9738 SelectionDAG &DAG) const {
9739 SDValue Vec = Op.getOperand(0);
9740 SDValue InsVal = Op.getOperand(1);
9741 SDValue Idx = Op.getOperand(2);
9742 EVT VecVT = Vec.getValueType();
9743 EVT EltVT = VecVT.getVectorElementType();
9744 unsigned VecSize = VecVT.getSizeInBits();
9745 unsigned EltSize = EltVT.getSizeInBits();
9746 SDLoc SL(Op);
9747
9748 // Specially handle the case of v4i16 with static indexing.
9749 unsigned NumElts = VecVT.getVectorNumElements();
9750 auto *KIdx = dyn_cast<ConstantSDNode>(Idx);
9751 if (NumElts == 4 && EltSize == 16 && KIdx) {
9752 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
9753
9754 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
9755 DAG.getConstant(0, SL, MVT::i32));
9756 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
9757 DAG.getConstant(1, SL, MVT::i32));
9758
9759 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
9760 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
9761
9762 unsigned Idx = KIdx->getZExtValue();
9763 bool InsertLo = Idx < 2;
9764 SDValue InsHalf = DAG.getNode(
9765 ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, InsertLo ? LoVec : HiVec,
9766 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
9767 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
9768
9769 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
9770
9771 SDValue Concat =
9772 InsertLo ? DAG.getBuildVector(MVT::v2i32, SL, {InsHalf, HiHalf})
9773 : DAG.getBuildVector(MVT::v2i32, SL, {LoHalf, InsHalf});
9774
9775 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
9776 }
9777
9778 // Static indexing does not lower to stack access, and hence there is no need
9779 // for special custom lowering to avoid stack access.
9780 if (isa<ConstantSDNode>(Idx))
9781 return SDValue();
9782
9783 // Avoid stack access for dynamic indexing by custom lowering to
9784 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
9785 // Vectors wider than 64 bits do this on each 64-bit piece.
9786 assert(isPowerOf2_32(EltSize));
9787 unsigned PieceSize = std::min(VecSize, 64u);
9788 unsigned NumPieces = VecSize / PieceSize;
9789 unsigned EltsPerPiece = PieceSize / EltSize;
9790 MVT IntVT = MVT::getIntegerVT(PieceSize);
9791 EVT PieceVT = EVT::getVectorVT(*DAG.getContext(), EltVT, EltsPerPiece);
9792
9793 // Convert vector index to bit-index within its piece and get the required
9794 // bit mask. Using the index within the piece keeps the shift below 64.
9795 SDValue PieceIdx = Idx;
9796 if (NumPieces > 1)
9797 PieceIdx = DAG.getNode(ISD::AND, SL, MVT::i32, Idx,
9798 DAG.getConstant(EltsPerPiece - 1, SL, MVT::i32));
9799 const auto EltMask = maskTrailingOnes<uint64_t>(EltSize);
9800 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
9801 SDValue ScaledIdx =
9802 DAG.getNode(ISD::SHL, SL, MVT::i32, PieceIdx, ScaleFactor);
9803 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
9804 DAG.getConstant(EltMask, SL, IntVT), ScaledIdx);
9805
9806 // 1. Create a congruent vector with the target value in each element.
9807 SDValue ExtVal =
9808 DAG.getBitcast(IntVT, DAG.getSplatBuildVector(PieceVT, SL, InsVal));
9809
9810 auto InsertIntoPiece = [&](SDValue Piece, SDValue Mask) {
9811 // 2. Mask off all other indices except the required index within (1).
9812 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, Mask, ExtVal);
9813
9814 // 3. Mask off the required index within the target vector.
9815 SDValue RHS =
9816 DAG.getNode(ISD::AND, SL, IntVT, DAG.getNOT(SL, Mask, IntVT), Piece);
9817
9818 // 4. Get (2) and (3) ORed into the target vector.
9819 return DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS, SDNodeFlags::Disjoint);
9820 };
9821
9822 if (NumPieces == 1)
9823 return DAG.getBitcast(VecVT,
9824 InsertIntoPiece(DAG.getBitcast(IntVT, Vec), BFM));
9825
9826 // 5. Apply (2)-(4) to each 64-bit piece, with the mask cleared in every
9827 // piece except the one that holds the index, and rebuild the vector.
9828 MVT PiecesVT = MVT::getVectorVT(IntVT, NumPieces);
9829 SDValue BCVec = DAG.getBitcast(PiecesVT, Vec);
9830 SDValue PieceNo =
9831 DAG.getNode(ISD::SRL, SL, MVT::i32, Idx,
9832 DAG.getConstant(Log2_32(EltsPerPiece), SL, MVT::i32));
9833 SDValue Zero = DAG.getConstant(0, SL, IntVT);
9835 Pieces.reserve(NumPieces);
9836 for (unsigned I = 0; I != NumPieces; ++I) {
9837 SDValue CurPieceNo = DAG.getConstant(I, SL, MVT::i32);
9838 SDValue Piece =
9839 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, IntVT, BCVec, CurPieceNo);
9840 SDValue Mask =
9841 DAG.getSelectCC(SL, PieceNo, CurPieceNo, BFM, Zero, ISD::SETEQ);
9842 Pieces.push_back(InsertIntoPiece(Piece, Mask));
9843 }
9844
9845 return DAG.getBitcast(VecVT, DAG.getBuildVector(PiecesVT, SL, Pieces));
9846}
9847
9848SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
9849 SelectionDAG &DAG) const {
9850 SDLoc SL(Op);
9851
9852 EVT ResultVT = Op.getValueType();
9853 SDValue Vec = Op.getOperand(0);
9854 SDValue Idx = Op.getOperand(1);
9855 EVT VecVT = Vec.getValueType();
9856 unsigned VecSize = VecVT.getSizeInBits();
9857 EVT EltVT = VecVT.getVectorElementType();
9858
9859 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
9860
9861 // Make sure we do any optimizations that will make it easier to fold
9862 // source modifiers before obscuring it with bit operations.
9863
9864 // XXX - Why doesn't this get called when vector_shuffle is expanded?
9865 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
9866 return Combined;
9867
9868 if (VecSize == 128 || VecSize == 256 || VecSize == 512) {
9869 SDValue Lo, Hi;
9870 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VecVT);
9871
9872 if (VecSize == 128) {
9873 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
9874 Lo = DAG.getBitcast(LoVT,
9875 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9876 DAG.getConstant(0, SL, MVT::i32)));
9877 Hi = DAG.getBitcast(HiVT,
9878 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9879 DAG.getConstant(1, SL, MVT::i32)));
9880 } else if (VecSize == 256) {
9881 SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
9882 SDValue Parts[4];
9883 for (unsigned P = 0; P < 4; ++P) {
9884 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9885 DAG.getConstant(P, SL, MVT::i32));
9886 }
9887
9888 Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
9889 Parts[0], Parts[1]));
9890 Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
9891 Parts[2], Parts[3]));
9892 } else {
9893 assert(VecSize == 512);
9894
9895 SDValue V2 = DAG.getBitcast(MVT::v8i64, Vec);
9896 SDValue Parts[8];
9897 for (unsigned P = 0; P < 8; ++P) {
9898 Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
9899 DAG.getConstant(P, SL, MVT::i32));
9900 }
9901
9902 Lo = DAG.getBitcast(LoVT,
9903 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
9904 Parts[0], Parts[1], Parts[2], Parts[3]));
9905 Hi = DAG.getBitcast(HiVT,
9906 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
9907 Parts[4], Parts[5], Parts[6], Parts[7]));
9908 }
9909
9910 EVT IdxVT = Idx.getValueType();
9911 unsigned NElem = VecVT.getVectorNumElements();
9912 assert(isPowerOf2_32(NElem));
9913 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
9914 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
9915 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
9916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
9917 }
9918
9919 assert(VecSize <= 64);
9920
9921 MVT IntVT = MVT::getIntegerVT(VecSize);
9922
9923 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
9924 SDValue VecBC = peekThroughBitcasts(Vec);
9925 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9926 SDValue Src = VecBC.getOperand(0);
9927 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
9928 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
9929 }
9930
9931 unsigned EltSize = EltVT.getSizeInBits();
9932 assert(isPowerOf2_32(EltSize));
9933
9934 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
9935
9936 // Convert vector index to bit-index (* EltSize)
9937 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
9938
9939 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
9940 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
9941
9942 if (ResultVT == MVT::f16 || ResultVT == MVT::bf16) {
9943 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
9944 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
9945 }
9946
9947 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
9948}
9949
9950static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
9951 assert(Elt % 2 == 0);
9952 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
9953}
9954
9955static bool elementPairIsOddToEven(ArrayRef<int> Mask, int Elt) {
9956 assert(Elt % 2 == 0);
9957 return Mask[Elt] >= 0 && Mask[Elt + 1] >= 0 && (Mask[Elt] & 1) &&
9958 !(Mask[Elt + 1] & 1);
9959}
9960
9961SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
9962 SelectionDAG &DAG) const {
9963 SDLoc SL(Op);
9964 EVT ResultVT = Op.getValueType();
9965 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
9966 MVT EltVT = ResultVT.getVectorElementType().getSimpleVT();
9967 const int NewSrcNumElts = 2;
9968 MVT PackVT = MVT::getVectorVT(EltVT, NewSrcNumElts);
9969 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
9970
9971 // Break up the shuffle into registers sized pieces.
9972 //
9973 // We're trying to form sub-shuffles that the register allocation pipeline
9974 // won't be able to figure out, like how to use v_pk_mov_b32 to do a register
9975 // blend or 16-bit op_sel. It should be able to figure out how to reassemble a
9976 // pair of copies into a consecutive register copy, so use the ordinary
9977 // extract_vector_elt lowering unless we can use the shuffle.
9978 //
9979 // TODO: This is a bit of hack, and we should probably always use
9980 // extract_subvector for the largest possible subvector we can (or at least
9981 // use it for PackVT aligned pieces). However we have worse support for
9982 // combines on them don't directly treat extract_subvector / insert_subvector
9983 // as legal. The DAG scheduler also ends up doing a worse job with the
9984 // extract_subvectors.
9985 const bool ShouldUseConsecutiveExtract = EltVT.getSizeInBits() == 16;
9986
9987 // vector_shuffle <0,1,6,7> lhs, rhs
9988 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
9989 //
9990 // vector_shuffle <6,7,2,3> lhs, rhs
9991 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
9992 //
9993 // vector_shuffle <6,7,0,1> lhs, rhs
9994 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
9995
9996 // Avoid scalarizing when both halves are reading from consecutive elements.
9997
9998 // If we're treating 2 element shuffles as legal, also create odd-to-even
9999 // shuffles of neighboring pairs.
10000 //
10001 // vector_shuffle <3,2,7,6> lhs, rhs
10002 // -> concat_vectors vector_shuffle <1, 0> (extract_subvector lhs, 0)
10003 // vector_shuffle <1, 0> (extract_subvector rhs, 2)
10004
10006 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
10007 if (ShouldUseConsecutiveExtract &&
10009 const int Idx = SVN->getMaskElt(I);
10010 int VecIdx = Idx < SrcNumElts ? 0 : 1;
10011 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
10012 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT,
10013 SVN->getOperand(VecIdx),
10014 DAG.getConstant(EltIdx, SL, MVT::i32));
10015 Pieces.push_back(SubVec);
10016 } else if (elementPairIsOddToEven(SVN->getMask(), I) &&
10018 int Idx0 = SVN->getMaskElt(I);
10019 int Idx1 = SVN->getMaskElt(I + 1);
10020
10021 SDValue SrcOp0 = SVN->getOperand(0);
10022 SDValue SrcOp1 = SrcOp0;
10023 if (Idx0 >= SrcNumElts) {
10024 SrcOp0 = SVN->getOperand(1);
10025 Idx0 -= SrcNumElts;
10026 }
10027
10028 if (Idx1 >= SrcNumElts) {
10029 SrcOp1 = SVN->getOperand(1);
10030 Idx1 -= SrcNumElts;
10031 }
10032
10033 int AlignedIdx0 = Idx0 & ~(NewSrcNumElts - 1);
10034 int AlignedIdx1 = Idx1 & ~(NewSrcNumElts - 1);
10035
10036 // Extract nearest even aligned piece.
10037 SDValue SubVec0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT, SrcOp0,
10038 DAG.getConstant(AlignedIdx0, SL, MVT::i32));
10039 SDValue SubVec1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, PackVT, SrcOp1,
10040 DAG.getConstant(AlignedIdx1, SL, MVT::i32));
10041
10042 int NewMaskIdx0 = Idx0 - AlignedIdx0;
10043 int NewMaskIdx1 = Idx1 - AlignedIdx1;
10044
10045 SDValue Result0 = SubVec0;
10046 SDValue Result1 = SubVec0;
10047
10048 if (SubVec0 != SubVec1) {
10049 NewMaskIdx1 += NewSrcNumElts;
10050 Result1 = SubVec1;
10051 } else {
10052 Result1 = DAG.getPOISON(PackVT);
10053 }
10054
10055 SDValue Shuf = DAG.getVectorShuffle(PackVT, SL, Result0, Result1,
10056 {NewMaskIdx0, NewMaskIdx1});
10057 Pieces.push_back(Shuf);
10058 } else {
10059 const int Idx0 = SVN->getMaskElt(I);
10060 const int Idx1 = SVN->getMaskElt(I + 1);
10061 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
10062 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
10063 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
10064 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
10065
10066 SDValue Vec0 = SVN->getOperand(VecIdx0);
10067 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec0,
10068 DAG.getSignedConstant(EltIdx0, SL, MVT::i32));
10069
10070 SDValue Vec1 = SVN->getOperand(VecIdx1);
10071 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec1,
10072 DAG.getSignedConstant(EltIdx1, SL, MVT::i32));
10073 Pieces.push_back(DAG.getBuildVector(PackVT, SL, {Elt0, Elt1}));
10074 }
10075 }
10076
10077 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
10078}
10079
10080SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
10081 SelectionDAG &DAG) const {
10082 SDValue SVal = Op.getOperand(0);
10083 EVT ResultVT = Op.getValueType();
10084 EVT SValVT = SVal.getValueType();
10085 SDValue UndefVal = DAG.getPOISON(SValVT);
10086 SDLoc SL(Op);
10087
10089 VElts.push_back(SVal);
10090 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
10091 VElts.push_back(UndefVal);
10092
10093 return DAG.getBuildVector(ResultVT, SL, VElts);
10094}
10095
10096SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
10097 SelectionDAG &DAG) const {
10098 SDLoc SL(Op);
10099 EVT VT = Op.getValueType();
10100
10101 if (VT == MVT::v2f16 || VT == MVT::v2i16 || VT == MVT::v2bf16) {
10102 assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
10103
10104 SDValue Lo = Op.getOperand(0);
10105 SDValue Hi = Op.getOperand(1);
10106
10107 // Avoid adding defined bits with the zero_extend.
10108 if (Hi.isUndef()) {
10109 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
10110 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
10111 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
10112 }
10113
10114 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
10115 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
10116
10117 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
10118 DAG.getConstant(16, SL, MVT::i32));
10119 if (Lo.isUndef())
10120 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
10121
10122 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
10123 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
10124
10125 SDValue Or =
10126 DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi, SDNodeFlags::Disjoint);
10127 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
10128 }
10129
10130 // Split into 2-element chunks.
10131 const unsigned NumParts = VT.getVectorNumElements() / 2;
10132 EVT PartVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
10133 MVT PartIntVT = MVT::getIntegerVT(PartVT.getSizeInBits());
10134
10136 for (unsigned P = 0; P < NumParts; ++P) {
10137 SDValue Vec = DAG.getBuildVector(
10138 PartVT, SL, {Op.getOperand(P * 2), Op.getOperand(P * 2 + 1)});
10139 Casts.push_back(DAG.getNode(ISD::BITCAST, SL, PartIntVT, Vec));
10140 }
10141
10142 SDValue Blend =
10143 DAG.getBuildVector(MVT::getVectorVT(PartIntVT, NumParts), SL, Casts);
10144 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
10145}
10146
10148 const GlobalAddressSDNode *GA) const {
10149 // Named barriers have fixed, non-relocated LDS addresses, so a constant
10150 // offset into an array of them can be folded into the address.
10152 const auto *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
10153 return GV && AMDGPU::isNamedBarrier(*GV);
10154 }
10155
10156 // OSes that use ELF REL relocations (instead of RELA) can only store a
10157 // 32-bit addend in the instruction, so it is not safe to allow offset folding
10158 // which can create arbitrary 64-bit addends. (This is only a problem for
10159 // R_AMDGPU_*32_HI relocations since other relocation types are unaffected by
10160 // the high 32 bits of the addend.)
10161 //
10162 // This should be kept in sync with how HasRelocationAddend is initialized in
10163 // the constructor of ELFAMDGPUAsmBackend.
10164 if (!Subtarget->isAmdHsaOS())
10165 return false;
10166
10167 // We can fold offsets for anything that doesn't require a GOT relocation.
10168 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
10172}
10173
10174static SDValue
10176 const SDLoc &DL, int64_t Offset, EVT PtrVT,
10177 unsigned GAFlags = SIInstrInfo::MO_NONE) {
10178 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
10179 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
10180 // lowered to the following code sequence:
10181 //
10182 // For constant address space:
10183 // s_getpc_b64 s[0:1]
10184 // s_add_u32 s0, s0, $symbol
10185 // s_addc_u32 s1, s1, 0
10186 //
10187 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
10188 // a fixup or relocation is emitted to replace $symbol with a literal
10189 // constant, which is a pc-relative offset from the encoding of the $symbol
10190 // operand to the global variable.
10191 //
10192 // For global address space:
10193 // s_getpc_b64 s[0:1]
10194 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
10195 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
10196 //
10197 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
10198 // fixups or relocations are emitted to replace $symbol@*@lo and
10199 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
10200 // which is a 64-bit pc-relative offset from the encoding of the $symbol
10201 // operand to the global variable.
10202 if (((const GCNSubtarget &)DAG.getSubtarget()).has64BitLiterals()) {
10203 assert(GAFlags != SIInstrInfo::MO_NONE);
10204
10205 SDValue Ptr =
10206 DAG.getTargetGlobalAddress(GV, DL, MVT::i64, Offset, GAFlags + 2);
10207 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET64, DL, PtrVT, Ptr);
10208 }
10209
10210 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags);
10211 SDValue PtrHi;
10212 if (GAFlags == SIInstrInfo::MO_NONE)
10213 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
10214 else
10215 PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags + 1);
10216 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
10217}
10218
10219SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunctionInfo *MFI,
10220 SDValue Op,
10221 SelectionDAG &DAG) const {
10222 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
10223 SDLoc DL(GSD);
10224 EVT PtrVT = Op.getValueType();
10225
10226 const GlobalValue *GV = GSD->getGlobal();
10227 const unsigned AS = GSD->getAddressSpace();
10228 if (((AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::BARRIER) &&
10231 if (AS == AMDGPUAS::LOCAL_ADDRESS && GV->hasExternalLinkage()) {
10232 const GlobalVariable &GVar = *cast<GlobalVariable>(GV);
10233 // HIP uses an unsized array `extern __shared__ T s[]` or similar
10234 // zero-sized type in other languages to declare the dynamic shared
10235 // memory which size is not known at the compile time. They will be
10236 // allocated by the runtime and placed directly after the static
10237 // allocated ones. They all share the same offset.
10238 if (GVar.getGlobalSize(GVar.getDataLayout()) == 0) {
10239 assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
10240 // Adjust alignment for that dynamic shared memory array.
10242 MFI->setDynLDSAlign(F, GVar);
10243 MFI->setUsesDynamicLDS(true);
10244 return SDValue(
10245 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
10246 }
10247 }
10249 }
10250
10251 if (AS == AMDGPUAS::BARRIER) {
10252 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
10254 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0);
10255 }
10256
10257 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
10258 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
10260 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
10261 }
10262
10263 if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS()) {
10264 if (Subtarget->has64BitLiterals()) {
10266 GV, DL, MVT::i64, GSD->getOffset(), SIInstrInfo::MO_ABS64);
10267 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Addr),
10268 0);
10269 }
10270
10271 SDValue AddrLo = DAG.getTargetGlobalAddress(
10272 GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_LO);
10273 AddrLo = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrLo), 0};
10274
10275 SDValue AddrHi = DAG.getTargetGlobalAddress(
10276 GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_HI);
10277 AddrHi = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrHi), 0};
10278
10279 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, AddrLo, AddrHi);
10280 }
10281
10282 if (shouldEmitFixup(GV))
10283 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
10284
10285 if (shouldEmitPCReloc(GV))
10286 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
10288
10289 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
10291 PointerType *PtrTy =
10293 const DataLayout &DataLayout = DAG.getDataLayout();
10294 Align Alignment = DataLayout.getABITypeAlign(PtrTy);
10295 MachinePointerInfo PtrInfo =
10297
10298 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
10301}
10302
10303// An alloca in the VGPR ("as memory") address space has no registers to live
10304// in, so its stack offset must not be taken for a register address. Every
10305// other frame index keeps its default lowering.
10306SDValue SITargetLowering::lowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
10308 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
10309 const AllocaInst *Alloca = MF.getFrameInfo().getObjectAllocation(FI);
10310 if (!Alloca || Alloca->getAddressSpace() != AMDGPUAS::VGPR)
10311 return SDValue();
10312
10313 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10314 MF.getFunction(),
10315 "unsupported alloca in VGPR 'as memory' address space (13)",
10316 Alloca->getDebugLoc()));
10317 return DAG.getPOISON(MVT::i32);
10318}
10319
10320SDValue SITargetLowering::LowerExternalSymbol(SDValue Op,
10321 SelectionDAG &DAG) const {
10322 // TODO: Handle this. It should be mostly the same as LowerGlobalAddress.
10323 const Function &Fn = DAG.getMachineFunction().getFunction();
10324 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10325 Fn, "unsupported external symbol", Op.getDebugLoc()));
10326 return DAG.getPOISON(Op.getValueType());
10327}
10328
10330 const SDLoc &DL, SDValue V) const {
10331 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
10332 // the destination register.
10333 //
10334 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
10335 // so we will end up with redundant moves to m0.
10336 //
10337 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
10338
10339 // A Null SDValue creates a glue result.
10340 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
10341 V, Chain);
10342 return SDValue(M0, 0);
10343}
10344
10345SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, SDValue Op,
10346 MVT VT,
10347 unsigned Offset) const {
10348 SDLoc SL(Op);
10349 SDValue Param = lowerKernargMemParameter(
10350 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
10351 // The local size values will have the hi 16-bits as zero.
10352 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
10353 DAG.getValueType(VT));
10354}
10355
10357 EVT VT) {
10360 "non-hsa intrinsic with hsa target", DL.getDebugLoc()));
10361 return DAG.getPOISON(VT);
10362}
10363
10365 EVT VT) {
10368 "intrinsic not supported on subtarget", DL.getDebugLoc()));
10369 return DAG.getPOISON(VT);
10370}
10371
10373 ArrayRef<SDValue> Elts) {
10374 assert(!Elts.empty());
10375 MVT Type;
10376 unsigned NumElts = Elts.size();
10377
10378 if (NumElts <= 12) {
10379 Type = MVT::getVectorVT(MVT::f32, NumElts);
10380 } else {
10381 assert(Elts.size() <= 16);
10382 Type = MVT::v16f32;
10383 NumElts = 16;
10384 }
10385
10386 SmallVector<SDValue, 16> VecElts(NumElts);
10387 for (unsigned i = 0; i < Elts.size(); ++i) {
10388 SDValue Elt = Elts[i];
10389 if (Elt.getValueType() != MVT::f32)
10390 Elt = DAG.getBitcast(MVT::f32, Elt);
10391 VecElts[i] = Elt;
10392 }
10393 for (unsigned i = Elts.size(); i < NumElts; ++i)
10394 VecElts[i] = DAG.getPOISON(MVT::f32);
10395
10396 if (NumElts == 1)
10397 return VecElts[0];
10398 return DAG.getBuildVector(Type, DL, VecElts);
10399}
10400
10401static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
10402 SDValue Src, int ExtraElts) {
10403 EVT SrcVT = Src.getValueType();
10404
10406
10407 if (SrcVT.isVector())
10408 DAG.ExtractVectorElements(Src, Elts);
10409 else
10410 Elts.push_back(Src);
10411
10412 SDValue Undef = DAG.getPOISON(SrcVT.getScalarType());
10413 while (ExtraElts--)
10414 Elts.push_back(Undef);
10415
10416 return DAG.getBuildVector(CastVT, DL, Elts);
10417}
10418
10419// Re-construct the required return value for a image load intrinsic.
10420// This is more complicated due to the optional use TexFailCtrl which means the
10421// required return type is an aggregate
10423 ArrayRef<EVT> ResultTypes, bool IsTexFail,
10424 bool Unpacked, bool IsD16, int DMaskPop,
10425 int NumVDataDwords, bool IsAtomicPacked16Bit,
10426 const SDLoc &DL) {
10427 // Determine the required return type. This is the same regardless of
10428 // IsTexFail flag
10429 EVT ReqRetVT = ResultTypes[0];
10430 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
10431 int NumDataDwords = ((IsD16 && !Unpacked) || IsAtomicPacked16Bit)
10432 ? (ReqRetNumElts + 1) / 2
10433 : ReqRetNumElts;
10434
10435 int MaskPopDwords = (!IsD16 || Unpacked) ? DMaskPop : (DMaskPop + 1) / 2;
10436
10437 MVT DataDwordVT =
10438 NumDataDwords == 1 ? MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
10439
10440 MVT MaskPopVT =
10441 MaskPopDwords == 1 ? MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
10442
10443 SDValue Data(Result, 0);
10444 SDValue TexFail;
10445
10446 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
10447 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
10448 if (MaskPopVT.isVector()) {
10449 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
10450 SDValue(Result, 0), ZeroIdx);
10451 } else {
10452 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
10453 SDValue(Result, 0), ZeroIdx);
10454 }
10455 }
10456
10457 if (DataDwordVT.isVector() && !IsAtomicPacked16Bit)
10458 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
10459 NumDataDwords - MaskPopDwords);
10460
10461 if (IsD16)
10462 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
10463
10464 EVT LegalReqRetVT = ReqRetVT;
10465 if (!ReqRetVT.isVector()) {
10466 if (!Data.getValueType().isInteger())
10467 Data = DAG.getNode(ISD::BITCAST, DL,
10468 Data.getValueType().changeTypeToInteger(), Data);
10469 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
10470 } else {
10471 // We need to widen the return vector to a legal type
10472 if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
10473 ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
10474 LegalReqRetVT =
10476 ReqRetVT.getVectorNumElements() + 1);
10477 }
10478 }
10479 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
10480
10481 if (IsTexFail) {
10482 TexFail =
10483 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
10484 DAG.getConstant(MaskPopDwords, DL, MVT::i32));
10485
10486 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
10487 }
10488
10489 if (Result->getNumValues() == 1)
10490 return Data;
10491
10492 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
10493}
10494
10495static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
10496 SDValue *LWE, bool &IsTexFail) {
10497 auto *TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
10498
10499 uint64_t Value = TexFailCtrlConst->getZExtValue();
10500 if (Value) {
10501 IsTexFail = true;
10502 }
10503
10504 SDLoc DL(TexFailCtrlConst);
10505 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
10506 Value &= ~(uint64_t)0x1;
10507 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
10508 Value &= ~(uint64_t)0x2;
10509
10510 return Value == 0;
10511}
10512
10514 MVT PackVectorVT,
10515 SmallVectorImpl<SDValue> &PackedAddrs,
10516 unsigned DimIdx, unsigned EndIdx,
10517 unsigned NumGradients) {
10518 SDLoc DL(Op);
10519 for (unsigned I = DimIdx; I < EndIdx; I++) {
10520 SDValue Addr = Op.getOperand(I);
10521
10522 // Gradients are packed with undef for each coordinate.
10523 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
10524 // 1D: undef,dx/dh; undef,dx/dv
10525 // 2D: dy/dh,dx/dh; dy/dv,dx/dv
10526 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
10527 if (((I + 1) >= EndIdx) ||
10528 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
10529 I == DimIdx + NumGradients - 1))) {
10530 if (Addr.getValueType() != MVT::i16)
10531 Addr = DAG.getBitcast(MVT::i16, Addr);
10532 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
10533 } else {
10534 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
10535 I++;
10536 }
10537 Addr = DAG.getBitcast(MVT::f32, Addr);
10538 PackedAddrs.push_back(Addr);
10539 }
10540}
10541
10542/// Emit a DiagnosticInfoUnsupported for an unsupported image intrinsic and
10543/// return poison values of \p ResultTypes, preserving the chain if present.
10545 ArrayRef<EVT> ResultTypes,
10546 const SDLoc &DL, const Twine &Msg) {
10548 DAG.getMachineFunction().getFunction(), Msg, DL.getDebugLoc()));
10549 return DAG.getErrorMergeValues(ResultTypes, Op.getOperand(0), DL);
10550}
10551
10552SDValue SITargetLowering::lowerImage(SDValue Op,
10554 SelectionDAG &DAG, bool WithChain) const {
10555 SDLoc DL(Op);
10557 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
10558 unsigned IntrOpcode = Intr->BaseOpcode;
10559 // For image atomic: use no-return opcode if result is unused.
10560 if (Intr->AtomicNoRetBaseOpcode != Intr->BaseOpcode &&
10561 !Op.getNode()->hasAnyUseOfValue(0))
10562 IntrOpcode = Intr->AtomicNoRetBaseOpcode;
10563 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
10565 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
10566 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
10567 bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
10568 bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
10569 bool IsGFX13 = AMDGPU::isGFX13(*Subtarget);
10570
10571 SmallVector<EVT, 3> ResultTypes(Op->values());
10572 SmallVector<EVT, 3> OrigResultTypes(Op->values());
10573 if (BaseOpcode->NoReturn && BaseOpcode->Atomic)
10574 ResultTypes.erase(&ResultTypes[0]);
10575
10576 bool IsD16 = false;
10577 bool IsG16 = false;
10578 bool IsA16 = false;
10579 SDValue VData;
10580 int NumVDataDwords = 0;
10581 bool AdjustRetType = false;
10582 bool IsAtomicPacked16Bit = false;
10583
10584 // Offset of intrinsic arguments
10585 const unsigned ArgOffset = WithChain ? 2 : 1;
10586
10587 unsigned DMask;
10588 unsigned DMaskLanes = 0;
10589
10590 if (BaseOpcode->Atomic) {
10591 VData = Op.getOperand(2);
10592
10593 IsAtomicPacked16Bit =
10594 (IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16 ||
10595 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_F16_NORTN ||
10596 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16 ||
10597 IntrOpcode == AMDGPU::IMAGE_ATOMIC_PK_ADD_BF16_NORTN);
10598
10599 if (!IsAtomicPacked16Bit && VData.getValueSizeInBits() != 32 &&
10600 VData.getValueSizeInBits() != 64) {
10601 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10602 "unsupported image atomic data type");
10603 }
10604
10605 bool Is64Bit = VData.getValueSizeInBits() == 64;
10606 if (BaseOpcode->AtomicX2) {
10607 SDValue VData2 = Op.getOperand(3);
10608 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
10609 {VData, VData2});
10610 if (Is64Bit)
10611 VData = DAG.getBitcast(MVT::v4i32, VData);
10612
10613 if (!BaseOpcode->NoReturn)
10614 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
10615
10616 DMask = Is64Bit ? 0xf : 0x3;
10617 NumVDataDwords = Is64Bit ? 4 : 2;
10618 } else {
10619 DMask = Is64Bit ? 0x3 : 0x1;
10620 NumVDataDwords = Is64Bit ? 2 : 1;
10621 }
10622 } else {
10623 DMask = Op->getConstantOperandVal(ArgOffset + Intr->DMaskIndex);
10624 DMaskLanes = BaseOpcode->Gather4 ? 4 : llvm::popcount(DMask);
10625
10626 if (BaseOpcode->Store) {
10627 VData = Op.getOperand(2);
10628
10629 MVT StoreVT = VData.getSimpleValueType();
10630 MVT StoreScalarVT = StoreVT.getScalarType();
10631 if (StoreScalarVT != MVT::f16 && StoreScalarVT.getSizeInBits() != 32 &&
10632 StoreScalarVT.getSizeInBits() != 64) {
10633 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10634 "unsupported image store data type");
10635 }
10636 if (StoreScalarVT == MVT::f16) {
10637 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
10638 return Op; // D16 is unsupported for this instruction
10639
10640 IsD16 = true;
10641 VData = handleD16VData(VData, DAG, true);
10642 }
10643
10644 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
10645 } else if (!BaseOpcode->NoReturn) {
10646 // Work out the num dwords based on the dmask popcount and underlying type
10647 // and whether packing is supported.
10648 MVT LoadVT = ResultTypes[0].getSimpleVT();
10649 MVT LoadScalarVT = LoadVT.getScalarType();
10650 if (LoadScalarVT != MVT::f16 && LoadScalarVT.getSizeInBits() != 32 &&
10651 LoadScalarVT.getSizeInBits() != 64) {
10652 return diagnoseUnsupportedImage(DAG, Op, OrigResultTypes, DL,
10653 "unsupported image load data type");
10654 }
10655 if (LoadScalarVT == MVT::f16) {
10656 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
10657 return Op; // D16 is unsupported for this instruction
10658
10659 IsD16 = true;
10660 }
10661
10662 // Confirm that the return type is large enough for the dmask specified
10663 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
10664 (!LoadVT.isVector() && DMaskLanes > 1))
10665 return Op;
10666
10667 // The sq block of gfx8 and gfx9 do not estimate register use correctly
10668 // for d16 image_gather4, image_gather4_l, and image_gather4_lz
10669 // instructions.
10670 if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
10671 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
10672 NumVDataDwords = (DMaskLanes + 1) / 2;
10673 else
10674 NumVDataDwords = DMaskLanes;
10675
10676 AdjustRetType = true;
10677 }
10678 }
10679
10680 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
10682
10683 // Check for 16 bit addresses or derivatives and pack if true.
10684 MVT VAddrVT =
10685 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
10686 MVT VAddrScalarVT = VAddrVT.getScalarType();
10687 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
10688 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
10689
10690 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
10691 VAddrScalarVT = VAddrVT.getScalarType();
10692 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
10693 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
10694
10695 // Push back extra arguments.
10696 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
10697 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
10698 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
10699 // Special handling of bias when A16 is on. Bias is of type half but
10700 // occupies full 32-bit.
10701 SDValue Bias = DAG.getBuildVector(
10702 MVT::v2f16, DL,
10703 {Op.getOperand(ArgOffset + I), DAG.getPOISON(MVT::f16)});
10704 VAddrs.push_back(Bias);
10705 } else {
10706 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
10707 "Bias needs to be converted to 16 bit in A16 mode");
10708 VAddrs.push_back(Op.getOperand(ArgOffset + I));
10709 }
10710 }
10711
10712 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
10713 // 16 bit gradients are supported, but are tied to the A16 control
10714 // so both gradients and addresses must be 16 bit
10715 LLVM_DEBUG(
10716 dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
10717 "require 16 bit args for both gradients and addresses");
10718 return Op;
10719 }
10720
10721 if (IsA16) {
10722 if (!ST->hasA16()) {
10723 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
10724 "support 16 bit addresses\n");
10725 return Op;
10726 }
10727 }
10728
10729 // We've dealt with incorrect input so we know that if IsA16, IsG16
10730 // are set then we have to compress/pack operands (either address,
10731 // gradient or both)
10732 // In the case where a16 and gradients are tied (no G16 support) then we
10733 // have already verified that both IsA16 and IsG16 are true
10734 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
10735 // Activate g16
10736 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
10738 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
10739 }
10740
10741 // Add gradients (packed or unpacked)
10742 if (IsG16) {
10743 // Pack the gradients
10744 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
10745 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
10746 ArgOffset + Intr->GradientStart,
10747 ArgOffset + Intr->CoordStart, Intr->NumGradients);
10748 } else {
10749 for (unsigned I = ArgOffset + Intr->GradientStart;
10750 I < ArgOffset + Intr->CoordStart; I++)
10751 VAddrs.push_back(Op.getOperand(I));
10752 }
10753
10754 // Add addresses (packed or unpacked)
10755 if (IsA16) {
10756 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
10757 ArgOffset + Intr->CoordStart, VAddrEnd,
10758 0 /* No gradients */);
10759 } else {
10760 // Add uncompressed address
10761 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
10762 VAddrs.push_back(Op.getOperand(I));
10763 }
10764
10765 // If the register allocator cannot place the address registers contiguously
10766 // without introducing moves, then using the non-sequential address encoding
10767 // is always preferable, since it saves VALU instructions and is usually a
10768 // wash in terms of code size or even better.
10769 //
10770 // However, we currently have no way of hinting to the register allocator that
10771 // MIMG addresses should be placed contiguously when it is possible to do so,
10772 // so force non-NSA for the common 2-address case as a heuristic.
10773 //
10774 // SIShrinkInstructions will convert NSA encodings to non-NSA after register
10775 // allocation when possible.
10776 //
10777 // Partial NSA is allowed on GFX11+ where the final register is a contiguous
10778 // set of the remaining addresses.
10779 const unsigned NSAMaxSize = ST->getNSAMaxSize(BaseOpcode->Sampler);
10780 const bool HasPartialNSAEncoding = ST->hasPartialNSAEncoding();
10781 const bool UseNSA = ST->hasNSAEncoding() &&
10782 VAddrs.size() >= ST->getNSAThreshold(MF) &&
10783 (VAddrs.size() <= NSAMaxSize || HasPartialNSAEncoding);
10784 const bool UsePartialNSA =
10785 UseNSA && HasPartialNSAEncoding && VAddrs.size() > NSAMaxSize;
10786
10787 SDValue VAddr;
10788 if (UsePartialNSA) {
10789 VAddr = getBuildDwordsVector(DAG, DL,
10790 ArrayRef(VAddrs).drop_front(NSAMaxSize - 1));
10791 } else if (!UseNSA) {
10792 VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
10793 }
10794
10795 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
10796 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
10797 SDValue Unorm;
10798 if (!BaseOpcode->Sampler) {
10799 Unorm = True;
10800 } else {
10801 uint64_t UnormConst =
10802 Op.getConstantOperandVal(ArgOffset + Intr->UnormIndex);
10803
10804 Unorm = UnormConst ? True : False;
10805 }
10806
10807 SDValue TFE;
10808 SDValue LWE;
10809 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
10810 bool IsTexFail = false;
10811 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
10812 return Op;
10813
10814 if (IsTexFail) {
10815 if (!DMaskLanes) {
10816 // Expecting to get an error flag since TFC is on - and dmask is 0
10817 // Force dmask to be at least 1 otherwise the instruction will fail
10818 DMask = 0x1;
10819 DMaskLanes = 1;
10820 NumVDataDwords = 1;
10821 }
10822 NumVDataDwords += 1;
10823 AdjustRetType = true;
10824 }
10825
10826 // Has something earlier tagged that the return type needs adjusting
10827 // This happens if the instruction is a load or has set TexFailCtrl flags
10828 if (AdjustRetType) {
10829 // NumVDataDwords reflects the true number of dwords required in the return
10830 // type
10831 if (DMaskLanes == 0 && !BaseOpcode->Store) {
10832 // This is a no-op load. This can be eliminated
10833 SDValue Undef = DAG.getPOISON(Op.getValueType());
10834 if (isa<MemSDNode>(Op))
10835 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
10836 return Undef;
10837 }
10838
10839 EVT NewVT = NumVDataDwords > 1 ? EVT::getVectorVT(*DAG.getContext(),
10840 MVT::i32, NumVDataDwords)
10841 : MVT::i32;
10842
10843 ResultTypes[0] = NewVT;
10844 if (ResultTypes.size() == 3) {
10845 // Original result was aggregate type used for TexFailCtrl results
10846 // The actual instruction returns as a vector type which has now been
10847 // created. Remove the aggregate result.
10848 ResultTypes.erase(&ResultTypes[1]);
10849 }
10850 }
10851
10852 unsigned CPol = Op.getConstantOperandVal(ArgOffset + Intr->CachePolicyIndex);
10853 // Keep GLC only when the atomic's result is actually used.
10854 if (BaseOpcode->Atomic && !BaseOpcode->NoReturn)
10856 if (CPol & ~((IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12) |
10858 return Op;
10859
10861 if (BaseOpcode->Store || BaseOpcode->Atomic)
10862 Ops.push_back(VData); // vdata
10863 if (UsePartialNSA) {
10864 append_range(Ops, ArrayRef(VAddrs).take_front(NSAMaxSize - 1));
10865 Ops.push_back(VAddr);
10866 } else if (UseNSA)
10867 append_range(Ops, VAddrs);
10868 else
10869 Ops.push_back(VAddr);
10870 SDValue Rsrc = Op.getOperand(ArgOffset + Intr->RsrcIndex);
10871 EVT RsrcVT = Rsrc.getValueType();
10872 bool IndexedRsrc = IsGFX13 && RsrcVT == MVT::i32;
10873 if (RsrcVT != MVT::v4i32 && RsrcVT != MVT::v8i32 && !IndexedRsrc)
10874 return Op;
10875 Ops.push_back(Rsrc);
10876 bool IsSampIndexed = false;
10877 if (BaseOpcode->Sampler) {
10878 SDValue Samp = Op.getOperand(ArgOffset + Intr->SampIndex);
10879 EVT SampVT = Samp.getValueType();
10880 IsSampIndexed = IsGFX13 && SampVT == MVT::i32;
10881 if (SampVT != MVT::v4i32 && !IsSampIndexed)
10882 return Op;
10883 Ops.push_back(Samp);
10884 }
10885 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
10886 if (IsGFX10Plus)
10887 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
10888 if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
10889 Ops.push_back(Unorm);
10890 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
10891 Ops.push_back(IsA16 && // r128, a16 for gfx9
10892 ST->hasFeature(AMDGPU::FeatureR128A16)
10893 ? True
10894 : False);
10895 if (IsGFX10Plus)
10896 Ops.push_back(IsA16 ? True : False);
10897
10898 if (!Subtarget->hasGFX90AInsts())
10899 Ops.push_back(TFE); // tfe
10900 else if (TFE->getAsZExtVal()) {
10901 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10903 "TFE is not supported on this GPU", DL.getDebugLoc()));
10904 }
10905
10906 if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
10907 Ops.push_back(LWE); // lwe
10908 if (!IsGFX10Plus)
10909 Ops.push_back(DimInfo->DA ? True : False);
10910 if (BaseOpcode->HasD16)
10911 Ops.push_back(IsD16 ? True : False);
10912 if (isa<MemSDNode>(Op))
10913 Ops.push_back(Op.getOperand(0)); // chain
10914
10915 int NumVAddrDwords =
10916 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
10917 int Opcode = -1;
10918
10919 if (IsGFX13) {
10920 Opcode =
10921 AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx13, NumVDataDwords,
10922 NumVAddrDwords, IndexedRsrc, IsSampIndexed);
10923 } else if (IsGFX12Plus) {
10924 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx12,
10925 NumVDataDwords, NumVAddrDwords);
10926 } else if (IsGFX11Plus) {
10927 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
10928 UseNSA ? AMDGPU::MIMGEncGfx11NSA
10929 : AMDGPU::MIMGEncGfx11Default,
10930 NumVDataDwords, NumVAddrDwords);
10931 } else if (IsGFX10Plus) {
10932 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
10933 UseNSA ? AMDGPU::MIMGEncGfx10NSA
10934 : AMDGPU::MIMGEncGfx10Default,
10935 NumVDataDwords, NumVAddrDwords);
10936 } else {
10937 if (Subtarget->hasGFX90AInsts()) {
10938 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
10939 NumVDataDwords, NumVAddrDwords);
10940 if (Opcode == -1) {
10942 DAG, Op, OrigResultTypes, DL,
10943 "requested image instruction is not supported on this GPU");
10944 }
10945 }
10946 if (Opcode == -1 &&
10947 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
10948 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
10949 NumVDataDwords, NumVAddrDwords);
10950 if (Opcode == -1)
10951 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
10952 NumVDataDwords, NumVAddrDwords);
10953 }
10954 if (Opcode == -1)
10955 return Op;
10956
10957 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
10958 if (auto *MemOp = dyn_cast<MemSDNode>(Op)) {
10959 MachineMemOperand *MemRef = MemOp->getMemOperand();
10960 DAG.setNodeMemRefs(NewNode, {MemRef});
10961 }
10962
10963 if (BaseOpcode->NoReturn) {
10964 if (BaseOpcode->Atomic)
10965 return DAG.getMergeValues(
10966 {DAG.getPOISON(OrigResultTypes[0]), SDValue(NewNode, 0)}, DL);
10967
10968 return SDValue(NewNode, 0);
10969 }
10970
10971 if (BaseOpcode->AtomicX2) {
10973 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
10974 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
10975 }
10976
10977 return constructRetValue(DAG, NewNode, OrigResultTypes, IsTexFail,
10978 Subtarget->hasUnpackedD16VMem(), IsD16, DMaskLanes,
10979 NumVDataDwords, IsAtomicPacked16Bit, DL);
10980}
10981
10982SDValue SITargetLowering::lowerSBuffer(EVT VT, EVT MemVT, SDLoc DL,
10983 SDValue Chain, SDValue Rsrc,
10984 SDValue Offset, SDValue CachePolicy,
10985 SelectionDAG &DAG,
10986 MachineMemOperand *MMO) const {
10988 bool HasChainResult = MMO != nullptr;
10989
10990 // SBUFFER_LOAD only produces values that fill whole SGPRs, apart from the
10991 // subword loads below.
10992 bool IsSubwordLoad = (MemVT == MVT::i8 || MemVT == MVT::i16) &&
10993 Subtarget->hasScalarSubwordLoads();
10994 if ((!isTypeLegal(VT) || VT.getSizeInBits() % 32 != 0) && !IsSubwordLoad) {
10995 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
10996 MF.getFunction(), "unsupported s_buffer_load result type",
10997 DL.getDebugLoc()));
10998 EVT ResultTypes[] = {VT, MVT::Other};
10999 return DAG.getErrorMergeValues(
11000 ArrayRef(ResultTypes, HasChainResult ? 2 : 1), Chain, DL);
11001 }
11002
11003 if (!HasChainResult) {
11004 const DataLayout &DataLayout = DAG.getDataLayout();
11006 DataLayout.getABITypeAlign(MemVT.getTypeForEVT(*DAG.getContext()));
11007
11008 MMO = MF.getMachineMemOperand(MachinePointerInfo(),
11012 MemVT.getStoreSize(), Alignment);
11013 }
11014
11015 if (!Offset->isDivergent()) {
11016 SDValue Ops[] = {Chain, Rsrc, Offset, CachePolicy};
11017
11018 // Lower llvm.amdgcn.*s.buffer.load.{i,u}N intrinsics. First, generate
11019 // s_buffer_load_u* for signed and unsigned load instructions. Next, DAG
11020 // combiner tries to merge the s_buffer_load_uN with a sext instruction
11021 // (performSignExtendInRegCombine()) and it replaces s_buffer_load_uN with
11022 // s_buffer_load_iN.
11023 auto HandleScalarSubwordLoads = [&](unsigned Opcode) -> SDValue {
11024 SDValue BufferLoad = DAG.getMemIntrinsicNode(
11025 Opcode, DL, DAG.getVTList(MVT::i32, MVT::Other), Ops, MemVT, MMO);
11026 SDValue LoadVal = DAG.getAnyExtOrTrunc(
11027 DAG.getNode(ISD::TRUNCATE, DL, MemVT, BufferLoad), DL, VT);
11028 if (HasChainResult)
11029 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
11030 return LoadVal;
11031 };
11032 if (MemVT == MVT::i8 && Subtarget->hasScalarSubwordLoads())
11033 return HandleScalarSubwordLoads(AMDGPUISD::SBUFFER_LOAD_UBYTE);
11034
11035 if (MemVT == MVT::i16 && Subtarget->hasScalarSubwordLoads())
11036 return HandleScalarSubwordLoads(AMDGPUISD::SBUFFER_LOAD_USHORT);
11037
11038 // Widen vec3 load to vec4. Only 32-bit elements have a vec4 pattern.
11039 if (VT.isVector() && VT.getVectorNumElements() == 3 &&
11040 VT.getVectorElementType().getSizeInBits() == 32 &&
11041 !Subtarget->hasScalarDwordx3Loads()) {
11042 EVT WidenedVT =
11044 auto WidenedOp = DAG.getMemIntrinsicNode(
11045 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT, MVT::Other),
11046 Ops, WidenedVT,
11047 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
11048 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
11049 DAG.getVectorIdxConstant(0, DL));
11050 if (HasChainResult)
11051 return DAG.getMergeValues({Subvector, WidenedOp.getValue(1)}, DL);
11052 return Subvector;
11053 }
11054
11055 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
11056 DAG.getVTList(VT, MVT::Other), Ops, MemVT,
11057 MMO);
11058 }
11059
11060 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
11061 // assume that the buffer is unswizzled.
11062 SDValue Ops[] = {
11063 Chain, // Chain
11064 Rsrc, // rsrc
11065 DAG.getConstant(0, DL, MVT::i32), // vindex
11066 {}, // voffset
11067 {}, // soffset
11068 {}, // offset
11069 CachePolicy, // cachepolicy
11070 DAG.getTargetConstant(0, DL, MVT::i1), // idxen
11071 };
11072 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
11073 Subtarget->hasScalarSubwordLoads()) {
11074 setBufferOffsets(Offset, DAG, &Ops[3], Align(4));
11075 SDValue Load = handleByteShortBufferLoads(DAG, MemVT, DL, Ops, MMO);
11076 SDValue LoadVal = DAG.getAnyExtOrTrunc(Load.getOperand(0), DL, VT);
11077 if (HasChainResult)
11078 return DAG.getMergeValues({LoadVal, Load.getOperand(1)}, DL);
11079 return LoadVal;
11080 }
11081
11083 unsigned NumLoads = 1;
11084 MVT LoadVT = VT.getSimpleVT();
11085 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
11086 assert((LoadVT.getScalarType() == MVT::i32 ||
11087 LoadVT.getScalarType() == MVT::f32));
11088
11089 if (NumElts == 8 || NumElts == 16) {
11090 NumLoads = NumElts / 4;
11091 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
11092 }
11093
11094 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Other});
11095
11096 // Use the alignment to ensure that the required offsets will fit into the
11097 // immediate offsets.
11098 setBufferOffsets(Offset, DAG, &Ops[3],
11099 NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
11100
11101 uint64_t InstOffset = Ops[5]->getAsZExtVal();
11102 unsigned LoadSize = LoadVT.getStoreSize();
11103 for (unsigned i = 0; i < NumLoads; ++i) {
11104 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
11105 MachineMemOperand *LoadMMO = MF.getMachineMemOperand(MMO, 16 * i, LoadSize);
11106 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
11107 LoadVT, LoadMMO, DAG));
11108 }
11109
11110 if (NumElts == 8 || NumElts == 16) {
11111 SDValue LoadVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
11112 if (HasChainResult) {
11113 SmallVector<SDValue, 4> LoadChains;
11114 for (SDValue Load : Loads)
11115 LoadChains.push_back(Load.getValue(1));
11116 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoadChains);
11117 return DAG.getMergeValues({LoadVal, Chain}, DL);
11118 }
11119 return LoadVal;
11120 }
11121
11122 return Loads[0];
11123}
11124
11125SDValue SITargetLowering::lowerWaveID(SelectionDAG &DAG, SDValue Op) const {
11126 // With architected SGPRs, waveIDinGroup is in TTMP8[29:25].
11127 if (!Subtarget->hasArchitectedSGPRs())
11128 return {};
11129 SDLoc SL(Op);
11130 MVT VT = MVT::i32;
11131 SDValue TTMP8 = DAG.getCopyFromReg(DAG.getEntryNode(), SL, AMDGPU::TTMP8, VT);
11132 return DAG.getNode(AMDGPUISD::BFE_U32, SL, VT, TTMP8,
11133 DAG.getConstant(25, SL, VT), DAG.getConstant(5, SL, VT));
11134}
11135
11136SDValue SITargetLowering::lowerConstHwRegRead(SelectionDAG &DAG, SDValue Op,
11137 AMDGPU::Hwreg::Id HwReg,
11138 unsigned LowBit,
11139 unsigned Width) const {
11140 SDLoc SL(Op);
11141 using namespace AMDGPU::Hwreg;
11142 return {DAG.getMachineNode(
11143 AMDGPU::S_GETREG_B32_const, SL, MVT::i32,
11144 DAG.getTargetConstant(HwregEncoding::encode(HwReg, LowBit, Width),
11145 SL, MVT::i32)),
11146 0};
11147}
11148
11149SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
11150 unsigned Dim,
11151 const ArgDescriptor &Arg) const {
11152 SDLoc SL(Op);
11154 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
11155 if (MaxID == 0)
11156 return DAG.getConstant(0, SL, MVT::i32);
11157
11158 // It's undefined behavior if a function marked with the amdgpu-no-*
11159 // attributes uses the corresponding intrinsic.
11160 if (!Arg)
11161 return DAG.getPOISON(Op->getValueType(0));
11162
11163 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
11164 SDLoc(DAG.getEntryNode()), Arg);
11165
11166 // Don't bother inserting AssertZext for packed IDs since we're emitting the
11167 // masking operations anyway.
11168 //
11169 // TODO: We could assert the top bit is 0 for the source copy.
11170 if (Arg.isMasked())
11171 return Val;
11172
11173 // Preserve the known bits after expansion to a copy.
11174 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_width(MaxID));
11175 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
11176 DAG.getValueType(SmallVT));
11177}
11178
11179SDValue SITargetLowering::lowerFromFP8(SDValue Op, bool IsBF8,
11180 SelectionDAG &DAG) const {
11181 SDLoc SL(Op);
11182 SDValue Src = Op.getOperand(0);
11183 EVT DstVT = Op.getValueType();
11184 bool IsF16 = DstVT.getVectorElementType() == MVT::f16;
11185 assert((!IsF16 || Subtarget->hasFP8F16ConversionInsts()) &&
11186 "fp8/bf8 -> f16 conversion requires FP8F16ConversionInsts");
11187
11188 unsigned Opc;
11189 if (IsF16)
11190 Opc = IsBF8 ? AMDGPUISD::CVT_PK_F16_BF8 : AMDGPUISD::CVT_PK_F16_FP8;
11191 else
11192 Opc = IsBF8 ? AMDGPUISD::CVT_PK_F32_BF8 : AMDGPUISD::CVT_PK_F32_FP8;
11193
11194 // Pack the two i8 lanes into the integer type the packed HW node reads. The
11195 // f16 form takes i16 and the f32 form takes i32. v2i8 bitcasts to i16
11196 // directly and the f32 node reads the low half of an any-extended i32.
11197 EVT PackedVT =
11199 SDValue AsI16 = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11200 SDValue Packed = DAG.getAnyExtOrTrunc(AsI16, SL, PackedVT);
11201 return DAG.getNode(Opc, SL, DstVT, Packed);
11202}
11203
11204SDValue
11205SITargetLowering::LowerCONVERT_FROM_ARBITRARY_FP(SDValue Op,
11206 SelectionDAG &DAG) const {
11207 // Handle the OCP FP8 formats (E4M3FN, E5M2) and unsigned E5M3 on subtargets
11208 // with matching HW conversions. Other formats use the generic expansion.
11209 APFloatBase::Semantics FPSemantic =
11210 static_cast<APFloatBase::Semantics>(Op.getConstantOperandVal(1));
11211 const bool IsFP8 = FPSemantic == APFloatBase::S_Float8E4M3FN;
11212 const bool IsBF8 = FPSemantic == APFloatBase::S_Float8E5M2;
11213 const bool IsE5M3 = FPSemantic == APFloatBase::S_Float8E5M3FNU;
11214 const bool HasE5M3ConversionInsts =
11215 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
11216 const bool IsSupported = IsFP8 || IsBF8 || (IsE5M3 && HasE5M3ConversionInsts);
11217 if (!IsSupported)
11218 return SDValue();
11219
11220 EVT DstVT = Op.getValueType();
11221 // The custom action for a v2i8 source also reaches half conversions on
11222 // targets which only have FP8-to-f32 instructions.
11223 if (DstVT.getScalarType() == MVT::f16 &&
11224 !Subtarget->hasFP8F16ConversionInsts())
11225 return SDValue();
11226
11227 if (IsE5M3) {
11228 if (DstVT.getScalarType() != MVT::f32)
11229 return SDValue();
11230
11231 SDLoc SL(Op);
11232 SDValue Src = Op.getOperand(0);
11233 assert((!DstVT.isVector() || DstVT == MVT::v2f32) &&
11234 "only the v2f32 vector result is custom lowered");
11235
11236 if (DstVT.isVector())
11237 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11238 Src = DAG.getAnyExtOrTrunc(Src, SL, MVT::i32);
11239
11240 auto ConvertByte = [&](unsigned ByteSel) {
11241 return DAG.getNode(AMDGPUISD::CVT_F32_FP8_E5M3, SL, MVT::f32, Src,
11242 DAG.getTargetConstant(ByteSel, SL, MVT::i32));
11243 };
11244
11245 if (!DstVT.isVector())
11246 return ConvertByte(0);
11247 return DAG.getBuildVector(DstVT, SL, {ConvertByte(0), ConvertByte(1)});
11248 }
11249
11250 if (!DstVT.isVector()) {
11251 SDValue Src = Op.getOperand(0);
11252 if (Src.getValueType() != MVT::i32) {
11253 SDLoc SL(Op);
11254 SDValue SrcI32 = DAG.getAnyExtOrTrunc(Src, SL, MVT::i32);
11255 return DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, SL, DstVT, SrcI32,
11256 Op.getOperand(1));
11257 }
11258 return Op;
11259 }
11260
11261 EVT EltVT = DstVT.getVectorElementType();
11262 if (EltVT == MVT::f16 || EltVT == MVT::f32)
11263 return lowerFromFP8(Op, IsBF8, DAG);
11264 return SDValue();
11265}
11266
11267SDValue SITargetLowering::lowerToFP8(SDValue Op, bool IsBF8, bool IsE5M3,
11268 SelectionDAG &DAG) const {
11269 SDLoc SL(Op);
11270 SDValue Src = Op.getOperand(0);
11271 EVT ResVT = Op.getValueType();
11272 bool IsF16 = Src.getValueType().getScalarType() == MVT::f16;
11273 assert((!IsF16 || Subtarget->hasF16FP8ConversionInsts()) &&
11274 "f16 -> fp8/bf8 conversion requires F16FP8ConversionInsts");
11275 assert((!ResVT.isVector() || ResVT == MVT::v2i8) &&
11276 "only the v2i8 vector result is custom lowered");
11277
11278 if (IsF16) {
11279 unsigned Opc =
11280 IsBF8 ? AMDGPUISD::CVT_PK_BF8_F16 : AMDGPUISD::CVT_PK_FP8_F16;
11281 SDValue Bytes = DAG.getNode(Opc, SL, MVT::i16, Src);
11282 return DAG.getNode(ISD::BITCAST, SL, ResVT, Bytes);
11283 }
11284
11285 unsigned Opc = IsBF8 ? AMDGPUISD::CVT_PK_BF8_F32
11286 : IsE5M3 ? AMDGPUISD::CVT_PK_FP8_F32_E5M3
11287 : AMDGPUISD::CVT_PK_FP8_F32;
11288 SDValue PoisonI32 = DAG.getPOISON(MVT::i32);
11289 SDValue WordSel = DAG.getTargetConstant(0, SL, MVT::i1);
11290
11291 if (!ResVT.isVector()) {
11292 // Convert one lane, the second is unused. Feed it the same source so the
11293 // instruction does not read an undefined register.
11294 SDValue Packed =
11295 DAG.getNode(Opc, SL, MVT::i32, Src, Src, PoisonI32, WordSel);
11296 return DAG.getAnyExtOrTrunc(Packed, SL, ResVT);
11297 }
11298
11299 SDValue A = DAG.getExtractVectorElt(SL, MVT::f32, Src, 0);
11300 SDValue B = DAG.getExtractVectorElt(SL, MVT::f32, Src, 1);
11301 SDValue Packed = DAG.getNode(Opc, SL, MVT::i32, A, B, PoisonI32, WordSel);
11302 SDValue Bytes = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Packed);
11303 return DAG.getNode(ISD::BITCAST, SL, ResVT, Bytes);
11304}
11305
11306SDValue
11307SITargetLowering::LowerCONVERT_TO_ARBITRARY_FP(SDValue Op,
11308 SelectionDAG &DAG) const {
11309 // The OCP FP8 formats (E4M3FN, E5M2) and unsigned E5M3 map to HW conversions
11310 // on subtargets that support them. Everything else uses generic expansion.
11312 static_cast<APFloatBase::Semantics>(Op.getConstantOperandVal(1));
11313 const bool IsFP8 = Sem == APFloatBase::S_Float8E4M3FN;
11314 const bool IsBF8 = Sem == APFloatBase::S_Float8E5M2;
11315 const bool IsE5M3 = Sem == APFloatBase::S_Float8E5M3FNU;
11316 const bool HasE5M3ConversionInsts =
11317 Subtarget->hasFP8ConversionInsts() && Subtarget->hasFP8E5M3Insts();
11318 const bool IsSupported = IsFP8 || IsBF8 || (IsE5M3 && HasE5M3ConversionInsts);
11319 if (!IsSupported)
11320 return SDValue();
11321
11322 // The HW conversions only support nearest-even. The OCP conversions do not
11323 // saturate. The unsigned E5M3 conversion always clamps out-of-range inputs,
11324 // which also refines the non-saturating form where those inputs are poison.
11325 if (static_cast<RoundingMode>(Op.getConstantOperandVal(2)) !=
11327 return SDValue();
11328 if (!IsE5M3 && Op.getConstantOperandVal(3) != 0)
11329 return SDValue();
11330
11331 EVT SrcEltVT = Op.getOperand(0).getValueType().getScalarType();
11332 // The f32 form is built here rather than by a tablegen pattern because the
11333 // HW result is i32 while the node result is i16 after the i8 promotion.
11334 if (SrcEltVT == MVT::f32)
11335 return lowerToFP8(Op, IsBF8, IsE5M3, DAG);
11336 if (!IsE5M3 && SrcEltVT == MVT::f16 &&
11337 Subtarget->hasF16FP8ConversionInsts()) {
11338 // A scalar conversion is selected from the generic node by tablegen, only
11339 // the illegal v2i8 result type needs lowering here.
11340 if (!Op.getValueType().isVector())
11341 return Op;
11342 return lowerToFP8(Op, IsBF8, false, DAG);
11343 }
11344 return SDValue();
11345}
11346
11347SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
11348 SelectionDAG &DAG) const {
11350 auto *MFI = MF.getInfo<SIMachineFunctionInfo>();
11351
11352 EVT VT = Op.getValueType();
11353 SDLoc DL(Op);
11354 unsigned IntrinsicID = Op.getConstantOperandVal(0);
11355
11356 // TODO: Should this propagate fast-math-flags?
11357
11358 switch (IntrinsicID) {
11359 case Intrinsic::amdgcn_wave_reduce_min:
11360 case Intrinsic::amdgcn_wave_reduce_umin:
11361 case Intrinsic::amdgcn_wave_reduce_fmin:
11362 case Intrinsic::amdgcn_wave_reduce_max:
11363 case Intrinsic::amdgcn_wave_reduce_umax:
11364 case Intrinsic::amdgcn_wave_reduce_fmax:
11365 case Intrinsic::amdgcn_wave_reduce_add:
11366 case Intrinsic::amdgcn_wave_reduce_fadd:
11367 case Intrinsic::amdgcn_wave_reduce_sub:
11368 case Intrinsic::amdgcn_wave_reduce_fsub:
11369 case Intrinsic::amdgcn_wave_reduce_and:
11370 case Intrinsic::amdgcn_wave_reduce_or:
11371 case Intrinsic::amdgcn_wave_reduce_xor: {
11372 EVT SrcVT = Op.getOperand(1).getValueType();
11373 if (SrcVT.getFixedSizeInBits() == 16) {
11374 bool IsFPOp = SrcVT.isFloatingPoint();
11375 bool NeedsSignExt = IntrinsicID == Intrinsic::amdgcn_wave_reduce_min ||
11376 IntrinsicID == Intrinsic::amdgcn_wave_reduce_max ||
11377 IntrinsicID == Intrinsic::amdgcn_wave_reduce_add ||
11378 IntrinsicID == Intrinsic::amdgcn_wave_reduce_sub;
11379 unsigned ExtOpc = IsFPOp ? ISD::FP_EXTEND
11380 : NeedsSignExt ? ISD::SIGN_EXTEND
11382 auto SrcType = IsFPOp ? MVT::f16 : MVT::i16;
11383 auto ExtType = IsFPOp ? MVT::f32 : MVT::i32;
11384 SDValue ExtendedSrc = DAG.getNode(ExtOpc, DL, ExtType, Op.getOperand(1));
11385 SDValue Strategy = Op.getOperand(2);
11387 Op.getOperand(0), ExtendedSrc, Strategy);
11388 if (IsFPOp)
11389 return DAG.getNode(ISD::FP_ROUND, DL, SrcType, Result,
11390 DAG.getTargetConstant(1, DL, MVT::i32));
11391 else
11392 return DAG.getNode(ISD::TRUNCATE, DL, SrcType, Result);
11393 }
11394 return SDValue();
11395 }
11396 case Intrinsic::amdgcn_implicit_buffer_ptr: {
11397 if (!MFI->getUserSGPRInfo().hasImplicitBufferPtr()) {
11398 const char *Error =
11399 Subtarget->hasArchitectedFlatScratch()
11400 ? "intrinsic not supported on subtarget"
11401 : !Subtarget->isMesa3DOS()
11402 ? "intrinsic not supported for OS"
11403 : "intrinsic not supported for calling convention";
11404 DAG.getContext()->diagnose(
11405 DiagnosticInfoUnsupported(MF.getFunction(), Error, DL.getDebugLoc()));
11406 return DAG.getPOISON(VT);
11407 }
11408
11409 return getPreloadedValue(DAG, *MFI, VT,
11411 }
11412 case Intrinsic::amdgcn_dispatch_ptr:
11413 case Intrinsic::amdgcn_queue_ptr: {
11414 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
11415 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11416 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
11417 DL.getDebugLoc()));
11418 return DAG.getPOISON(VT);
11419 }
11420
11421 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr
11424 return getPreloadedValue(DAG, *MFI, VT, RegID);
11425 }
11426 case Intrinsic::amdgcn_implicitarg_ptr: {
11427 if (MFI->isEntryFunction())
11428 return getImplicitArgPtr(DAG, DL);
11429 return getPreloadedValue(DAG, *MFI, VT,
11431 }
11432 case Intrinsic::amdgcn_kernarg_segment_ptr: {
11433 if (!AMDGPU::isKernel(MF.getFunction())) {
11434 // This only makes sense to call in a kernel, so just lower to null.
11435 return DAG.getConstant(0, DL, VT);
11436 }
11437
11438 return getPreloadedValue(DAG, *MFI, VT,
11440 }
11441 case Intrinsic::amdgcn_dispatch_id: {
11442 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
11443 }
11444 case Intrinsic::amdgcn_rcp:
11445 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
11446 case Intrinsic::amdgcn_rsq:
11447 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
11448 case Intrinsic::amdgcn_rsq_legacy:
11449 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
11450 return emitRemovedIntrinsicError(DAG, DL, VT);
11451 return SDValue();
11452 case Intrinsic::amdgcn_rcp_legacy:
11453 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
11454 return emitRemovedIntrinsicError(DAG, DL, VT);
11455 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
11456 case Intrinsic::amdgcn_fma_legacy:
11457 case Intrinsic::amdgcn_sudot4:
11458 case Intrinsic::amdgcn_sudot8:
11459 case Intrinsic::amdgcn_tanh:
11460 return SDValue();
11461 case Intrinsic::amdgcn_rsq_clamp: {
11462 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
11463 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
11464
11465 Type *Type = VT.getTypeForEVT(*DAG.getContext());
11466 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
11467 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
11468
11469 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
11470 SDValue Tmp =
11471 DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, DAG.getConstantFP(Max, DL, VT));
11472 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
11473 DAG.getConstantFP(Min, DL, VT));
11474 }
11475 case Intrinsic::r600_read_ngroups_x:
11476 if (Subtarget->isAmdHsaOS())
11477 return emitNonHSAIntrinsicError(DAG, DL, VT);
11478
11479 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11481 false);
11482 case Intrinsic::r600_read_ngroups_y:
11483 if (Subtarget->isAmdHsaOS())
11484 return emitNonHSAIntrinsicError(DAG, DL, VT);
11485
11486 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11488 false);
11489 case Intrinsic::r600_read_ngroups_z:
11490 if (Subtarget->isAmdHsaOS())
11491 return emitNonHSAIntrinsicError(DAG, DL, VT);
11492
11493 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
11495 false);
11496 case Intrinsic::r600_read_local_size_x:
11497 if (Subtarget->isAmdHsaOS())
11498 return emitNonHSAIntrinsicError(DAG, DL, VT);
11499
11500 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11502 case Intrinsic::r600_read_local_size_y:
11503 if (Subtarget->isAmdHsaOS())
11504 return emitNonHSAIntrinsicError(DAG, DL, VT);
11505
11506 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11508 case Intrinsic::r600_read_local_size_z:
11509 if (Subtarget->isAmdHsaOS())
11510 return emitNonHSAIntrinsicError(DAG, DL, VT);
11511
11512 return lowerImplicitZextParam(DAG, Op, MVT::i16,
11514 case Intrinsic::amdgcn_workgroup_id_x:
11515 return lowerWorkGroupId(DAG, *MFI, VT,
11519 case Intrinsic::amdgcn_workgroup_id_y:
11520 return lowerWorkGroupId(DAG, *MFI, VT,
11524 case Intrinsic::amdgcn_workgroup_id_z:
11525 return lowerWorkGroupId(DAG, *MFI, VT,
11529 case Intrinsic::amdgcn_cluster_id_x:
11530 return Subtarget->hasClusters()
11531 ? getPreloadedValue(DAG, *MFI, VT,
11533 : DAG.getPOISON(VT);
11534 case Intrinsic::amdgcn_cluster_id_y:
11535 return Subtarget->hasClusters()
11536 ? getPreloadedValue(DAG, *MFI, VT,
11538 : DAG.getPOISON(VT);
11539 case Intrinsic::amdgcn_cluster_id_z:
11540 return Subtarget->hasClusters()
11541 ? getPreloadedValue(DAG, *MFI, VT,
11543 : DAG.getPOISON(VT);
11544 case Intrinsic::amdgcn_cluster_workgroup_id_x:
11545 return lowerClusterWorkGroupValue(
11547 case Intrinsic::amdgcn_cluster_workgroup_id_y:
11548 return lowerClusterWorkGroupValue(
11550 case Intrinsic::amdgcn_cluster_workgroup_id_z:
11551 return lowerClusterWorkGroupValue(
11553 case Intrinsic::amdgcn_cluster_workgroup_flat_id:
11554 return Subtarget->hasClusters()
11555 ? lowerConstHwRegRead(DAG, Op, AMDGPU::Hwreg::ID_IB_STS2, 21, 4)
11556 : SDValue();
11557 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
11558 return lowerClusterWorkGroupValue(
11560 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
11561 return lowerClusterWorkGroupValue(
11563 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
11564 return lowerClusterWorkGroupValue(
11566 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id:
11567 return lowerClusterWorkGroupValue(
11569 case Intrinsic::amdgcn_wave_id:
11570 return lowerWaveID(DAG, Op);
11571 case Intrinsic::amdgcn_lds_kernel_id: {
11572 if (MFI->isEntryFunction())
11573 return getLDSKernelId(DAG, DL);
11574 return getPreloadedValue(DAG, *MFI, VT,
11576 }
11577 case Intrinsic::amdgcn_workitem_id_x:
11578 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
11579 case Intrinsic::amdgcn_workitem_id_y:
11580 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
11581 case Intrinsic::amdgcn_workitem_id_z:
11582 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
11583 case Intrinsic::amdgcn_wavefrontsize:
11584 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
11585 SDLoc(Op), MVT::i32);
11586 case Intrinsic::amdgcn_s_buffer_load: {
11587 unsigned CPol = Op.getConstantOperandVal(3);
11588 // s_buffer_load, because of how it's optimized, can't be volatile
11589 // so reject ones with the volatile bit set.
11590 if (CPol & ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
11593 return Op;
11594 return lowerSBuffer(VT, VT, DL, DAG.getEntryNode(), Op.getOperand(1),
11595 Op.getOperand(2), Op.getOperand(3), DAG);
11596 }
11597 case Intrinsic::amdgcn_fdiv_fast:
11598 return lowerFDIV_FAST(Op, DAG);
11599 case Intrinsic::amdgcn_sin:
11600 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
11601
11602 case Intrinsic::amdgcn_cos:
11603 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
11604
11605 case Intrinsic::amdgcn_mul_u24:
11606 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1),
11607 Op.getOperand(2));
11608 case Intrinsic::amdgcn_mul_i24:
11609 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1),
11610 Op.getOperand(2));
11611
11612 case Intrinsic::amdgcn_log_clamp: {
11613 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
11614 return SDValue();
11615
11616 return emitRemovedIntrinsicError(DAG, DL, VT);
11617 }
11618 case Intrinsic::amdgcn_fract:
11619 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
11620
11621 case Intrinsic::amdgcn_class: {
11622 SDValue Src = Op.getOperand(1);
11623 EVT SrcVT = Src.getValueType();
11624 bool IsLegal = SrcVT == MVT::f32 || SrcVT == MVT::f64 ||
11625 (SrcVT == MVT::f16 && Subtarget->has16BitInsts());
11626 if (!IsLegal) {
11627 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
11629 "llvm.amdgcn.class only supports f16, f32, and f64",
11630 DL.getDebugLoc()));
11631 return DAG.getPOISON(VT);
11632 }
11633 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, Src, Op.getOperand(2));
11634 }
11635 case Intrinsic::amdgcn_div_fmas:
11636 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, Op.getOperand(1),
11637 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
11638
11639 case Intrinsic::amdgcn_div_fixup:
11640 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, Op.getOperand(1),
11641 Op.getOperand(2), Op.getOperand(3));
11642
11643 case Intrinsic::amdgcn_div_scale: {
11644 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
11645
11646 // Translate to the operands expected by the machine instruction. The
11647 // first parameter must be the same as the first instruction.
11648 SDValue Numerator = Op.getOperand(1);
11649 SDValue Denominator = Op.getOperand(2);
11650
11651 // Note this order is opposite of the machine instruction's operations,
11652 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
11653 // intrinsic has the numerator as the first operand to match a normal
11654 // division operation.
11655
11656 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
11657
11658 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
11659 Denominator, Numerator);
11660 }
11661 case Intrinsic::amdgcn_ballot:
11662 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
11663 case Intrinsic::amdgcn_fmed3:
11664 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, Op.getOperand(1),
11665 Op.getOperand(2), Op.getOperand(3), Op->getFlags());
11666 case Intrinsic::amdgcn_fdot2:
11667 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, Op.getOperand(1),
11668 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
11669 case Intrinsic::amdgcn_fmul_legacy:
11670 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, Op.getOperand(1),
11671 Op.getOperand(2));
11672 case Intrinsic::amdgcn_sbfe:
11673 case Intrinsic::amdgcn_ubfe:
11674 return lowerBFEIntrinsic(Op, DAG, IntrinsicID);
11675 case Intrinsic::amdgcn_cvt_pkrtz:
11676 case Intrinsic::amdgcn_cvt_pknorm_i16:
11677 case Intrinsic::amdgcn_cvt_pknorm_u16:
11678 case Intrinsic::amdgcn_cvt_pk_i16:
11679 case Intrinsic::amdgcn_cvt_pk_u16: {
11680 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
11681 EVT VT = Op.getValueType();
11682 unsigned Opcode;
11683
11684 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
11685 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
11686 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
11687 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
11688 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
11689 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
11690 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
11691 Opcode = AMDGPUISD::CVT_PK_I16_I32;
11692 else
11693 Opcode = AMDGPUISD::CVT_PK_U16_U32;
11694
11695 if (isTypeLegal(VT))
11696 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
11697
11698 SDValue Node =
11699 DAG.getNode(Opcode, DL, MVT::i32, Op.getOperand(1), Op.getOperand(2));
11700 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
11701 }
11702 case Intrinsic::amdgcn_fmad_ftz:
11703 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
11704 Op.getOperand(2), Op.getOperand(3));
11705
11706 case Intrinsic::amdgcn_if_break:
11707 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
11708 Op->getOperand(1), Op->getOperand(2)),
11709 0);
11710
11711 case Intrinsic::amdgcn_groupstaticsize: {
11713 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
11714 return Op;
11715
11716 const Module *M = MF.getFunction().getParent();
11717 const GlobalValue *GV =
11718 Intrinsic::getDeclarationIfExists(M, Intrinsic::amdgcn_groupstaticsize);
11719 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
11721 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
11722 }
11723 case Intrinsic::amdgcn_is_shared:
11724 case Intrinsic::amdgcn_is_private: {
11725 SDLoc SL(Op);
11726 SDValue SrcVec =
11727 DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
11728 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
11729 DAG.getConstant(1, SL, MVT::i32));
11730
11731 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared)
11733 : AMDGPUAS::PRIVATE_ADDRESS;
11734 if (AS == AMDGPUAS::PRIVATE_ADDRESS &&
11735 Subtarget->hasGloballyAddressableScratch()) {
11736 SDValue FlatScratchBaseHi(
11737 DAG.getMachineNode(
11738 AMDGPU::S_MOV_B32, DL, MVT::i32,
11739 DAG.getRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI, MVT::i32)),
11740 0);
11741 // Test bits 63..58 against the aperture address.
11742 return DAG.getSetCC(
11743 SL, MVT::i1,
11744 DAG.getNode(ISD::XOR, SL, MVT::i32, SrcHi, FlatScratchBaseHi),
11745 DAG.getConstant(1u << 26, SL, MVT::i32), ISD::SETULT);
11746 }
11747
11748 SDValue Aperture = getSegmentAperture(AS, SL, DAG);
11749 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
11750 }
11751 case Intrinsic::amdgcn_perm:
11752 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
11753 Op.getOperand(2), Op.getOperand(3));
11754 case Intrinsic::amdgcn_reloc_constant: {
11755 Module *M = MF.getFunction().getParent();
11756 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
11757 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
11758 auto *RelocSymbol = cast<GlobalVariable>(
11759 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
11760 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
11762 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
11763 }
11764 case Intrinsic::amdgcn_swmmac_f16_16x16x32_f16:
11765 case Intrinsic::amdgcn_swmmac_bf16_16x16x32_bf16:
11766 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf16:
11767 case Intrinsic::amdgcn_swmmac_f32_16x16x32_f16:
11768 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_fp8:
11769 case Intrinsic::amdgcn_swmmac_f32_16x16x32_fp8_bf8:
11770 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_fp8:
11771 case Intrinsic::amdgcn_swmmac_f32_16x16x32_bf8_bf8: {
11772 if (Op.getOperand(4).getValueType() == MVT::i32)
11773 return SDValue();
11774
11775 SDLoc SL(Op);
11776 auto IndexKeyi32 = DAG.getAnyExtOrTrunc(Op.getOperand(4), SL, MVT::i32);
11777 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11778 Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11779 Op.getOperand(3), IndexKeyi32);
11780 }
11781 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_fp8:
11782 case Intrinsic::amdgcn_swmmac_f32_16x16x128_fp8_bf8:
11783 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_fp8:
11784 case Intrinsic::amdgcn_swmmac_f32_16x16x128_bf8_bf8:
11785 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_fp8:
11786 case Intrinsic::amdgcn_swmmac_f16_16x16x128_fp8_bf8:
11787 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_fp8:
11788 case Intrinsic::amdgcn_swmmac_f16_16x16x128_bf8_bf8: {
11789 if (Op.getOperand(4).getValueType() == MVT::i64)
11790 return SDValue();
11791
11792 SDLoc SL(Op);
11793 auto IndexKeyi64 =
11794 Op.getOperand(4).getValueType() == MVT::v2i32
11795 ? DAG.getBitcast(MVT::i64, Op.getOperand(4))
11796 : DAG.getAnyExtOrTrunc(Op.getOperand(4), SL, MVT::i64);
11797 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11798 {Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11799 Op.getOperand(3), IndexKeyi64, Op.getOperand(5),
11800 Op.getOperand(6)});
11801 }
11802 case Intrinsic::amdgcn_swmmac_f16_16x16x64_f16:
11803 case Intrinsic::amdgcn_swmmac_bf16_16x16x64_bf16:
11804 case Intrinsic::amdgcn_swmmac_f32_16x16x64_bf16:
11805 case Intrinsic::amdgcn_swmmac_bf16f32_16x16x64_bf16:
11806 case Intrinsic::amdgcn_swmmac_f32_16x16x64_f16:
11807 case Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8: {
11808 EVT IndexKeyTy = IntrinsicID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8
11809 ? MVT::i64
11810 : MVT::i32;
11811 if (Op.getOperand(6).getValueType() == IndexKeyTy)
11812 return SDValue();
11813
11814 SDLoc SL(Op);
11815 auto IndexKey =
11816 Op.getOperand(6).getValueType().isVector()
11817 ? DAG.getBitcast(IndexKeyTy, Op.getOperand(6))
11818 : DAG.getAnyExtOrTrunc(Op.getOperand(6), SL, IndexKeyTy);
11820 Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11821 Op.getOperand(3), Op.getOperand(4), Op.getOperand(5),
11822 IndexKey, Op.getOperand(7), Op.getOperand(8)};
11823 if (IntrinsicID == Intrinsic::amdgcn_swmmac_i32_16x16x128_iu8)
11824 Args.push_back(Op.getOperand(9));
11825 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(), Args);
11826 }
11827 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu4:
11828 case Intrinsic::amdgcn_swmmac_i32_16x16x32_iu8:
11829 case Intrinsic::amdgcn_swmmac_i32_16x16x64_iu4: {
11830 if (Op.getOperand(6).getValueType() == MVT::i32)
11831 return SDValue();
11832
11833 SDLoc SL(Op);
11834 auto IndexKeyi32 = DAG.getAnyExtOrTrunc(Op.getOperand(6), SL, MVT::i32);
11835 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, Op.getValueType(),
11836 {Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
11837 Op.getOperand(3), Op.getOperand(4), Op.getOperand(5),
11838 IndexKeyi32, Op.getOperand(7)});
11839 }
11840 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
11841 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
11842 unsigned AFmt = (unsigned)Op.getConstantOperandVal(1);
11843 unsigned BFmt = (unsigned)Op.getConstantOperandVal(3);
11844 unsigned AScaleFmt = (unsigned)Op.getConstantOperandVal(8);
11845 unsigned BScaleFmt = (unsigned)Op.getConstantOperandVal(11);
11846 if (!AMDGPU::isValidWMMAScaleFmtCombination(AFmt, AScaleFmt, BFmt,
11847 BScaleFmt)) {
11849 "invalid matrix and scale format combination in wmma call");
11850 Op->print(errs());
11851 errs() << '\n';
11852 }
11853 return SDValue();
11854 }
11855 case Intrinsic::amdgcn_readlane:
11856 case Intrinsic::amdgcn_readfirstlane:
11857 case Intrinsic::amdgcn_writelane:
11858 case Intrinsic::amdgcn_permlane16:
11859 case Intrinsic::amdgcn_permlanex16:
11860 case Intrinsic::amdgcn_permlane64:
11861 case Intrinsic::amdgcn_set_inactive:
11862 case Intrinsic::amdgcn_set_inactive_chain_arg:
11863 case Intrinsic::amdgcn_mov_dpp8:
11864 case Intrinsic::amdgcn_update_dpp:
11865 case Intrinsic::amdgcn_permlane_bcast:
11866 case Intrinsic::amdgcn_permlane_up:
11867 case Intrinsic::amdgcn_permlane_down:
11868 case Intrinsic::amdgcn_permlane_xor:
11869 return lowerLaneOp(*this, Op.getNode(), DAG);
11870 case Intrinsic::amdgcn_dead: {
11872 for (const EVT ValTy : Op.getNode()->values())
11873 Poisons.push_back(DAG.getPOISON(ValTy));
11874 return DAG.getMergeValues(Poisons, SDLoc(Op));
11875 }
11876 case Intrinsic::amdgcn_wave_shuffle:
11877 return lowerWaveShuffle(*this, Op.getNode(), DAG);
11878 default:
11879 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
11881 return lowerImage(Op, ImageDimIntr, DAG, false);
11882
11883 return Op;
11884 }
11885}
11886
11887// On targets not supporting constant in soffset field, turn zero to
11888// SGPR_NULL to avoid generating an extra s_mov with zero.
11890 const GCNSubtarget *Subtarget) {
11891 if (Subtarget->hasRestrictedSOffset() && isNullConstant(SOffset))
11892 return DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32);
11893 return SOffset;
11894}
11895
11896// Lower the arguments of the buffer intrinsic \p Op into the operands of the
11897// corresponding AMDGPUISD buffer node: the chain, \p VData and the cmp operand
11898// if present, then rsrc, vindex, voffset, soffset, offset, [format,]
11899// cachepolicy and idxen.
11900SmallVector<SDValue, 10> SITargetLowering::getBufferIntrinsicOps(
11902 SDValue VData) const {
11903 SDLoc DL(Op);
11904 auto GetArg = [&](unsigned Arg) {
11905 return Op.getOperand(AMDGPU::getSDOperandIdx(Arg));
11906 };
11907
11908 SDValue Rsrc = bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG);
11909 auto [VOffset, Offset] =
11910 splitBufferOffsets(GetArg(*Info.getVOffsetArg()), DAG);
11911 SDValue SOffset =
11912 selectSOffset(GetArg(*Info.getSOffsetArg()), DAG, Subtarget);
11913
11914 SmallVector<SDValue, 10> Ops = {Op.getOperand(0)}; // Chain
11915 if (VData)
11916 Ops.push_back(VData);
11917 if (std::optional<unsigned> CmpArg = Info.getCmpArg())
11918 Ops.push_back(GetArg(*CmpArg));
11919 Ops.push_back(Rsrc);
11920 std::optional<unsigned> VIndexArg = Info.getVIndexArg();
11921 Ops.push_back(VIndexArg ? GetArg(*VIndexArg)
11922 : DAG.getConstant(0, DL, MVT::i32)); // vindex
11923 Ops.push_back(VOffset);
11924 Ops.push_back(SOffset);
11925 Ops.push_back(Offset);
11926 if (std::optional<unsigned> FormatArg = Info.getFormatArg())
11927 Ops.push_back(GetArg(*FormatArg));
11928 Ops.push_back(GetArg(*Info.getAuxArg())); // cachepolicy, swizzled buffer
11929 Ops.push_back(
11930 DAG.getTargetConstant(VIndexArg.has_value(), DL, MVT::i1)); // idxen
11931 return Ops;
11932}
11933
11934SDValue SITargetLowering::lowerBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
11935 unsigned NewOpcode) const {
11936 SDLoc DL(Op);
11937 const AMDGPU::BufferIntrinsicInfo &Info =
11938 *AMDGPU::lookupBufferIntrinsic(Op.getConstantOperandVal(1));
11939
11940 SDValue VData = Op.getOperand(AMDGPU::getSDOperandIdx(*Info.getVDataArg()));
11941 if (VData.getValueSizeInBits() != 32 && VData.getValueSizeInBits() != 64) {
11942 SmallVector<EVT, 2> ResultTypes(Op->values());
11943 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
11944 "unsupported buffer atomic data type");
11945 }
11946 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG, VData);
11947
11948 auto *M = cast<MemSDNode>(Op);
11949
11950 EVT MemVT = VData.getValueType();
11951 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
11952 M->getMemOperand());
11953}
11954
11955// Lower the buffer loads and the compare-and-swap atomics, which are all
11956// INTRINSIC_W_CHAIN nodes. Other atomics need an opcode for their operation,
11957// and so are handled by LowerINTRINSIC_W_CHAIN.
11958SDValue SITargetLowering::lowerBufferIntrinsicWithChain(
11960 SelectionDAG &DAG) const {
11961 SDLoc DL(Op);
11962 auto *M = cast<MemSDNode>(Op);
11963 auto GetArg = [&](unsigned Arg) {
11964 return Op.getOperand(AMDGPU::getSDOperandIdx(Arg));
11965 };
11966
11967 switch (Info.Kind) {
11968 case AMDGPU::BufferKindSLoad: {
11969 SDValue CachePolicy = GetArg(*Info.getAuxArg());
11970 if (CachePolicy->getAsZExtVal() &
11971 ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
11974 return Op;
11975
11976 return lowerSBuffer(
11977 Op.getValueType(), M->getMemoryVT(), DL, Op.getOperand(0),
11978 bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG),
11979 GetArg(*Info.getSOffsetArg()), CachePolicy, DAG, M->getMemOperand());
11980 }
11981 case AMDGPU::BufferKindLoad:
11982 case AMDGPU::BufferKindAtomicLoad: {
11983 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG);
11984 if (!Info.isTyped())
11985 return lowerIntrinsicLoad(M, Info.isFormatFromRsrc(), DAG, Ops);
11986
11987 EVT LoadVT = Op.getValueType();
11988 if (LoadVT.getScalarSizeInBits() == 16)
11989 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG,
11990 Ops);
11991 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
11992 Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
11993 DAG);
11994 }
11995 case AMDGPU::BufferKindAtomicCmpSwap: {
11996 SDValue Src = GetArg(*Info.getVDataArg());
11997 if (Src.getValueSizeInBits() != 32 && Src.getValueSizeInBits() != 64) {
11998 SmallVector<EVT, 2> ResultTypes(Op->values());
11999 return diagnoseUnsupportedImage(DAG, Op, ResultTypes, DL,
12000 "unsupported buffer atomic data type");
12001 }
12002 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG, Src);
12003 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
12004 Op->getVTList(), Ops, Op.getValueType(),
12005 M->getMemOperand());
12006 }
12007 default:
12008 llvm_unreachable("not a buffer intrinsic with a chain and a result");
12009 }
12010}
12011
12012// The async copies between memory and LDS add only the low 16 bits of the
12013// instruction offset to the LDS address, the memory side gets all of it. Fold
12014// any other offset into both addresses and leave 0 in the instruction.
12016 SDNode *N = Op.getNode();
12017 int64_t Offset = N->getConstantOperandAPInt(4).getSExtValue();
12018 if (isUInt<16>(Offset))
12019 return;
12021 for (unsigned OpIdx : {2, 3}) {
12022 EVT VT = Ops[OpIdx].getValueType();
12023 Ops[OpIdx] = DAG.getMemBasePlusOffset(
12024 Ops[OpIdx], DAG.getSignedConstant(Offset, DL, VT), DL);
12025 }
12026 Ops[4] = DAG.getTargetConstant(0, DL, MVT::i32);
12027 DAG.UpdateNodeOperands(N, Ops);
12028}
12029
12031 SDLoc DL) {
12032 SDNode *N = Op.getNode();
12033 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
12034 unsigned NumOperands = N->getNumOperands();
12035 if (N->getOperand(NumOperands - 1) == Zero)
12036 return;
12038 Ops[NumOperands - 1] = Zero; // M0 = 0
12039 DAG.UpdateNodeOperands(N, Ops);
12040}
12041
12042// Try to resolve a named barrier object to a constant barrier ID.
12043// Named barrier IDs are encoded at bits [5:0] of a BARRIER address space
12044// address - other bits of that address are ignored as reserved.
12045static std::optional<uint32_t>
12047 std::optional<uint64_t> BarVal;
12048 if (auto *C = dyn_cast<ConstantSDNode>(BarOp)) {
12049 BarVal = C->getZExtValue();
12050 } else if (BarOp->isUndef()) {
12051 // Refine poison to the 0 barrier to turn things into noops, thus reducing
12052 // the risk of hitting an unallocated barrier.
12053 BarVal = 0;
12054 } else if (auto *GA = dyn_cast<GlobalAddressSDNode>(BarOp)) {
12055 const auto *GV = cast<GlobalVariable>(GA->getGlobal());
12056 if (AMDGPU::isNamedBarrier(*GV) &&
12060 // Record the use of the manualy-specified barrier address to make sure
12061 // this function has the right number of resources. This function is named
12062 // weird, and we're calling it here since we're skipping the GlobalAddress
12063 // lowering with this pattern match.
12064 BarVal = MFI->allocateBarrierGlobal(DAG.getDataLayout(), *GV) +
12065 GA->getOffset();
12066 }
12067 }
12068 if (BarVal)
12069 return *BarVal & 0x3F;
12070 return std::nullopt;
12071}
12072
12073SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
12074 SelectionDAG &DAG) const {
12075 unsigned IntrID = Op.getConstantOperandVal(1);
12076 SDLoc DL(Op);
12077
12078 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
12080 BufInfo && BufInfo->Kind != AMDGPU::BufferKindAtomicRMW)
12081 return lowerBufferIntrinsicWithChain(Op, *BufInfo, DAG);
12082
12083 switch (IntrID) {
12084 case Intrinsic::amdgcn_cluster_load_b32:
12085 case Intrinsic::amdgcn_cluster_load_b64:
12086 case Intrinsic::amdgcn_cluster_load_b128: {
12087 if (Subtarget->hasGFX1250_STRICT())
12089 return SDValue();
12090 }
12091 case Intrinsic::amdgcn_ds_ordered_add:
12092 case Intrinsic::amdgcn_ds_ordered_swap: {
12093 MemSDNode *M = cast<MemSDNode>(Op);
12094 SDValue Chain = M->getOperand(0);
12095 SDValue M0 = M->getOperand(2);
12096 SDValue Value = M->getOperand(3);
12097 unsigned IndexOperand = M->getConstantOperandVal(7);
12098 unsigned WaveRelease = M->getConstantOperandVal(8);
12099 unsigned WaveDone = M->getConstantOperandVal(9);
12100
12101 unsigned OrderedCountIndex = IndexOperand & 0x3f;
12102 IndexOperand &= ~0x3f;
12103 unsigned CountDw = 0;
12104
12105 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
12106 CountDw = (IndexOperand >> 24) & 0xf;
12107 IndexOperand &= ~(0xf << 24);
12108
12109 if (CountDw < 1 || CountDw > 4) {
12110 const Function &Fn = DAG.getMachineFunction().getFunction();
12111 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12112 Fn, "ds_ordered_count: dword count must be between 1 and 4",
12113 DL.getDebugLoc()));
12114 CountDw = 1;
12115 }
12116 }
12117
12118 if (IndexOperand) {
12119 const Function &Fn = DAG.getMachineFunction().getFunction();
12120 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12121 Fn, "ds_ordered_count: bad index operand", DL.getDebugLoc()));
12122 }
12123
12124 if (WaveDone && !WaveRelease) {
12125 // TODO: Move this to IR verifier
12126 const Function &Fn = DAG.getMachineFunction().getFunction();
12127 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12128 Fn, "ds_ordered_count: wave_done requires wave_release",
12129 DL.getDebugLoc()));
12130 }
12131
12132 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
12133 unsigned ShaderType =
12135 unsigned Offset0 = OrderedCountIndex << 2;
12136 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
12137
12138 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
12139 Offset1 |= (CountDw - 1) << 6;
12140
12141 if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
12142 Offset1 |= ShaderType << 2;
12143
12144 unsigned Offset = Offset0 | (Offset1 << 8);
12145
12146 SDValue Ops[] = {
12147 Chain, Value, DAG.getTargetConstant(Offset, DL, MVT::i16),
12148 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
12149 };
12150 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
12151 M->getVTList(), Ops, M->getMemoryVT(),
12152 M->getMemOperand());
12153 }
12154 case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
12155 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fadd:
12156 case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
12157 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fadd:
12158 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
12159 case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
12160 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmin:
12161 case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
12162 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmin:
12163 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
12164 case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
12165 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmax:
12166 case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
12167 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmax:
12168 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
12169 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
12170 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_swap:
12171 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
12172 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_swap:
12173 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
12174 case Intrinsic::amdgcn_raw_buffer_atomic_add:
12175 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
12176 case Intrinsic::amdgcn_struct_buffer_atomic_add:
12177 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
12178 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
12179 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
12180 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
12181 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
12182 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
12183 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
12184 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
12185 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
12186 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
12187 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
12188 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
12189 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
12190 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
12191 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
12192 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
12193 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
12194 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
12195 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
12196 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
12197 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
12198 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
12199 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
12200 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
12201 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
12202 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
12203 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
12204 case Intrinsic::amdgcn_raw_buffer_atomic_and:
12205 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
12206 case Intrinsic::amdgcn_struct_buffer_atomic_and:
12207 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
12208 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
12209 case Intrinsic::amdgcn_raw_buffer_atomic_or:
12210 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
12211 case Intrinsic::amdgcn_struct_buffer_atomic_or:
12212 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
12213 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
12214 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
12215 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
12216 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
12217 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
12218 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
12219 case Intrinsic::amdgcn_raw_buffer_atomic_inc:
12220 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_inc:
12221 case Intrinsic::amdgcn_struct_buffer_atomic_inc:
12222 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_inc:
12223 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
12224 case Intrinsic::amdgcn_raw_buffer_atomic_dec:
12225 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_dec:
12226 case Intrinsic::amdgcn_struct_buffer_atomic_dec:
12227 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_dec:
12228 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
12229 case Intrinsic::amdgcn_raw_buffer_atomic_sub_clamp_u32:
12230 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub_clamp_u32:
12231 case Intrinsic::amdgcn_struct_buffer_atomic_sub_clamp_u32:
12232 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub_clamp_u32:
12233 return lowerBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_CSUB);
12234 case Intrinsic::amdgcn_raw_buffer_atomic_cond_sub_u32:
12235 case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cond_sub_u32:
12236 case Intrinsic::amdgcn_struct_buffer_atomic_cond_sub_u32:
12237 case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cond_sub_u32:
12238 return lowerBufferAtomicIntrin(Op, DAG,
12239 AMDGPUISD::BUFFER_ATOMIC_COND_SUB_U32);
12240 case Intrinsic::amdgcn_image_bvh_dual_intersect_ray:
12241 case Intrinsic::amdgcn_image_bvh8_intersect_ray: {
12242 MemSDNode *M = cast<MemSDNode>(Op);
12243 SDValue NodePtr = M->getOperand(2);
12244 SDValue RayExtent = M->getOperand(3);
12245 SDValue InstanceMask = M->getOperand(4);
12246 SDValue RayOrigin = M->getOperand(5);
12247 SDValue RayDir = M->getOperand(6);
12248 SDValue Offsets = M->getOperand(7);
12249 SDValue TDescr = M->getOperand(8);
12250
12251 assert(NodePtr.getValueType() == MVT::i64);
12252 assert(RayDir.getValueType() == MVT::v3f32);
12253
12254 bool IsBVH8 = IntrID == Intrinsic::amdgcn_image_bvh8_intersect_ray;
12255 const unsigned NumVDataDwords = 10;
12256 const unsigned NumVAddrDwords = IsBVH8 ? 11 : 12;
12257 int Opcode = AMDGPU::getMIMGOpcode(
12258 IsBVH8 ? AMDGPU::IMAGE_BVH8_INTERSECT_RAY
12259 : AMDGPU::IMAGE_BVH_DUAL_INTERSECT_RAY,
12260 AMDGPU::MIMGEncGfx12, NumVDataDwords, NumVAddrDwords);
12261 assert(Opcode != -1);
12262
12264 Ops.push_back(NodePtr);
12265 Ops.push_back(DAG.getBuildVector(
12266 MVT::v2i32, DL,
12267 {DAG.getBitcast(MVT::i32, RayExtent),
12268 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, InstanceMask)}));
12269 Ops.push_back(RayOrigin);
12270 Ops.push_back(RayDir);
12271 Ops.push_back(Offsets);
12272 Ops.push_back(TDescr);
12273 Ops.push_back(M->getChain());
12274
12275 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
12276 MachineMemOperand *MemRef = M->getMemOperand();
12277 DAG.setNodeMemRefs(NewNode, {MemRef});
12278 return SDValue(NewNode, 0);
12279 }
12280 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
12281 MemSDNode *M = cast<MemSDNode>(Op);
12282 SDValue NodePtr = M->getOperand(2);
12283 SDValue RayExtent = M->getOperand(3);
12284 SDValue RayOrigin = M->getOperand(4);
12285 SDValue RayDir = M->getOperand(5);
12286 SDValue RayInvDir = M->getOperand(6);
12287 SDValue TDescr = M->getOperand(7);
12288
12289 assert(NodePtr.getValueType() == MVT::i32 ||
12290 NodePtr.getValueType() == MVT::i64);
12291 assert(RayDir.getValueType() == MVT::v3f16 ||
12292 RayDir.getValueType() == MVT::v3f32);
12293
12294 const bool IsGFX11 = AMDGPU::isGFX11(*Subtarget);
12295 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
12296 const bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
12297 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
12298 const bool Is64 = NodePtr.getValueType() == MVT::i64;
12299 const unsigned NumVDataDwords = 4;
12300 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
12301 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
12302 const bool UseNSA = (Subtarget->hasNSAEncoding() &&
12303 NumVAddrs <= Subtarget->getNSAMaxSize()) ||
12304 IsGFX12Plus;
12305 const unsigned BaseOpcodes[2][2] = {
12306 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
12307 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
12308 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
12309 int Opcode;
12310 if (UseNSA) {
12311 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
12312 IsGFX12Plus ? AMDGPU::MIMGEncGfx12
12313 : IsGFX11 ? AMDGPU::MIMGEncGfx11NSA
12314 : AMDGPU::MIMGEncGfx10NSA,
12315 NumVDataDwords, NumVAddrDwords);
12316 } else {
12317 assert(!IsGFX12Plus);
12318 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
12319 IsGFX11 ? AMDGPU::MIMGEncGfx11Default
12320 : AMDGPU::MIMGEncGfx10Default,
12321 NumVDataDwords, NumVAddrDwords);
12322 }
12323 assert(Opcode != -1);
12324
12326
12327 auto packLanes = [&DAG, &Ops, &DL](SDValue Op, bool IsAligned) {
12329 DAG.ExtractVectorElements(Op, Lanes, 0, 3);
12330 if (Lanes[0].getValueSizeInBits() == 32) {
12331 for (unsigned I = 0; I < 3; ++I)
12332 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
12333 } else {
12334 if (IsAligned) {
12335 Ops.push_back(DAG.getBitcast(
12336 MVT::i32,
12337 DAG.getBuildVector(MVT::v2f16, DL, {Lanes[0], Lanes[1]})));
12338 Ops.push_back(Lanes[2]);
12339 } else {
12340 SDValue Elt0 = Ops.pop_back_val();
12341 Ops.push_back(DAG.getBitcast(
12342 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL, {Elt0, Lanes[0]})));
12343 Ops.push_back(DAG.getBitcast(
12344 MVT::i32,
12345 DAG.getBuildVector(MVT::v2f16, DL, {Lanes[1], Lanes[2]})));
12346 }
12347 }
12348 };
12349
12350 if (UseNSA && IsGFX11Plus) {
12351 Ops.push_back(NodePtr);
12352 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
12353 Ops.push_back(RayOrigin);
12354 if (IsA16) {
12355 SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
12356 DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
12357 DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
12358 for (unsigned I = 0; I < 3; ++I) {
12359 MergedLanes.push_back(DAG.getBitcast(
12360 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
12361 {DirLanes[I], InvDirLanes[I]})));
12362 }
12363 Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
12364 } else {
12365 Ops.push_back(RayDir);
12366 Ops.push_back(RayInvDir);
12367 }
12368 } else {
12369 if (Is64)
12370 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
12371 2);
12372 else
12373 Ops.push_back(NodePtr);
12374
12375 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
12376 packLanes(RayOrigin, true);
12377 packLanes(RayDir, true);
12378 packLanes(RayInvDir, false);
12379 }
12380
12381 if (!UseNSA) {
12382 // Build a single vector containing all the operands so far prepared.
12383 if (NumVAddrDwords > 12) {
12384 SDValue Undef = DAG.getPOISON(MVT::i32);
12385 Ops.append(16 - Ops.size(), Undef);
12386 }
12387 assert(Ops.size() >= 8 && Ops.size() <= 12);
12388 SDValue MergedOps =
12389 DAG.getBuildVector(MVT::getVectorVT(MVT::i32, Ops.size()), DL, Ops);
12390 Ops.clear();
12391 Ops.push_back(MergedOps);
12392 }
12393
12394 Ops.push_back(TDescr);
12395 Ops.push_back(DAG.getTargetConstant(IsA16, DL, MVT::i1));
12396 Ops.push_back(M->getChain());
12397
12398 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
12399 MachineMemOperand *MemRef = M->getMemOperand();
12400 DAG.setNodeMemRefs(NewNode, {MemRef});
12401 return SDValue(NewNode, 0);
12402 }
12403 case Intrinsic::amdgcn_global_atomic_fmin_num:
12404 case Intrinsic::amdgcn_global_atomic_fmax_num:
12405 case Intrinsic::amdgcn_flat_atomic_fmin_num:
12406 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
12407 MemSDNode *M = cast<MemSDNode>(Op);
12408 SDValue Ops[] = {
12409 M->getOperand(0), // Chain
12410 M->getOperand(2), // Ptr
12411 M->getOperand(3) // Value
12412 };
12413 unsigned Opcode = 0;
12414 switch (IntrID) {
12415 case Intrinsic::amdgcn_global_atomic_fmin_num:
12416 case Intrinsic::amdgcn_flat_atomic_fmin_num: {
12417 Opcode = ISD::ATOMIC_LOAD_FMIN;
12418 break;
12419 }
12420 case Intrinsic::amdgcn_global_atomic_fmax_num:
12421 case Intrinsic::amdgcn_flat_atomic_fmax_num: {
12422 Opcode = ISD::ATOMIC_LOAD_FMAX;
12423 break;
12424 }
12425 default:
12426 llvm_unreachable("unhandled atomic opcode");
12427 }
12428 return DAG.getAtomic(Opcode, SDLoc(Op), M->getMemoryVT(), M->getVTList(),
12429 Ops, M->getMemOperand());
12430 }
12431 case Intrinsic::amdgcn_s_alloc_vgpr: {
12432 SDValue NumVGPRs = Op.getOperand(2);
12433 if (!NumVGPRs->isDivergent())
12434 return Op;
12435
12436 SDValue ReadFirstLaneID =
12437 DAG.getTargetConstant(Intrinsic::amdgcn_readfirstlane, DL, MVT::i32);
12438 NumVGPRs = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
12439 ReadFirstLaneID, NumVGPRs);
12440
12441 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(),
12442 Op.getOperand(0), Op.getOperand(1), NumVGPRs);
12443 }
12444 case Intrinsic::amdgcn_s_get_barrier_state:
12445 case Intrinsic::amdgcn_s_get_named_barrier_state: {
12446 SDValue Chain = Op->getOperand(0);
12448 unsigned Opc;
12449
12450 std::optional<uint32_t> BarID;
12451 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state)
12452 BarID = getConstantNamedBarrierNumber(Op->getOperand(2), DAG);
12453 else if (auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(2)))
12454 BarID = C->getZExtValue();
12455
12456 if (BarID) {
12457 Opc = AMDGPU::S_GET_BARRIER_STATE_IMM;
12458 SDValue K = DAG.getTargetConstant(*BarID, DL, MVT::i32);
12459 Ops.push_back(K);
12460 Ops.push_back(Chain);
12461 } else {
12462 Opc = AMDGPU::S_GET_BARRIER_STATE_M0;
12463 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state) {
12464 SDValue M0Val = DAG.getNode(ISD::AND, DL, MVT::i32, Op->getOperand(2),
12465 DAG.getConstant(0x3F, DL, MVT::i32));
12466 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
12467 } else
12468 Ops.push_back(copyToM0(DAG, Chain, DL, Op->getOperand(2)).getValue(0));
12469 }
12470
12471 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
12472 return SDValue(NewMI, 0);
12473 }
12474 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
12475 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
12476 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B: {
12477 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12478 SDValue Chain = Op->getOperand(0);
12479 SDValue Ptr = Op->getOperand(2);
12480 EVT VT = Op->getValueType(0);
12481 return DAG.getAtomicLoad(ISD::NON_EXTLOAD, DL, MII->getMemoryVT(), VT,
12482 Chain, Ptr, MII->getMemOperand());
12483 }
12484 case Intrinsic::amdgcn_av_load_b8:
12485 case Intrinsic::amdgcn_av_load_b16:
12486 case Intrinsic::amdgcn_av_load_b32:
12487 case Intrinsic::amdgcn_av_load_b64:
12488 case Intrinsic::amdgcn_av_load_b128: {
12489 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12490 SDValue Chain = Op->getOperand(0);
12491 SDValue Ptr = Op->getOperand(2);
12492 EVT VT = Op->getValueType(0);
12493 // Lower to a regular ISD::LOAD. The MachineMemOperand carries Monotonic
12494 // ordering and syncscope so that SIMemoryLegalizer sets cache policy bits.
12495 // Address space filtering in the load_global/load_flat PatFrags selects
12496 // the correct GLOBAL vs FLAT instruction.
12497 return DAG.getLoad(VT, DL, Chain, Ptr, MII->getMemOperand());
12498 }
12499 case Intrinsic::amdgcn_flat_load_monitor_b32:
12500 case Intrinsic::amdgcn_flat_load_monitor_b64:
12501 case Intrinsic::amdgcn_flat_load_monitor_b128: {
12502 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12503 SDValue Chain = Op->getOperand(0);
12504 SDValue Ptr = Op->getOperand(2);
12505 return DAG.getMemIntrinsicNode(AMDGPUISD::FLAT_LOAD_MONITOR, DL,
12506 Op->getVTList(), {Chain, Ptr},
12507 MII->getMemoryVT(), MII->getMemOperand());
12508 }
12509 case Intrinsic::amdgcn_global_load_monitor_b32:
12510 case Intrinsic::amdgcn_global_load_monitor_b64:
12511 case Intrinsic::amdgcn_global_load_monitor_b128: {
12512 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
12513 SDValue Chain = Op->getOperand(0);
12514 SDValue Ptr = Op->getOperand(2);
12515 return DAG.getMemIntrinsicNode(AMDGPUISD::GLOBAL_LOAD_MONITOR, DL,
12516 Op->getVTList(), {Chain, Ptr},
12517 MII->getMemoryVT(), MII->getMemOperand());
12518 }
12519 default:
12520
12521 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
12523 return lowerImage(Op, ImageDimIntr, DAG, true);
12524
12525 return SDValue();
12526 }
12527}
12528
12529// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
12530// dwordx4 if on SI and handle TFE loads.
12531SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
12532 SDVTList VTList,
12533 ArrayRef<SDValue> Ops, EVT MemVT,
12534 MachineMemOperand *MMO,
12535 SelectionDAG &DAG) const {
12536 LLVMContext &C = *DAG.getContext();
12538 EVT VT = VTList.VTs[0];
12539
12540 assert(VTList.NumVTs == 2 || VTList.NumVTs == 3);
12541 bool IsTFE = VTList.NumVTs == 3;
12542 if (IsTFE) {
12543 unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
12544 unsigned NumOpDWords = NumValueDWords + 1;
12545 EVT OpDWordsVT = EVT::getVectorVT(C, MVT::i32, NumOpDWords);
12546 SDVTList OpDWordsVTList = DAG.getVTList(OpDWordsVT, VTList.VTs[2]);
12547 MachineMemOperand *OpDWordsMMO =
12548 MF.getMachineMemOperand(MMO, 0, NumOpDWords * 4);
12549 SDValue Op = getMemIntrinsicNode(Opcode, DL, OpDWordsVTList, Ops,
12550 OpDWordsVT, OpDWordsMMO, DAG);
12551 auto [Value, Status] = splitTFEValueAndStatus(Op, VT, DL, DAG);
12552 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
12553 }
12554
12555 if (!Subtarget->hasDwordx3LoadStores() &&
12556 (VT == MVT::v3i32 || VT == MVT::v3f32)) {
12557 EVT WidenedVT = EVT::getVectorVT(C, VT.getVectorElementType(), 4);
12558 EVT WidenedMemVT = EVT::getVectorVT(C, MemVT.getVectorElementType(), 4);
12559 MachineMemOperand *WidenedMMO = MF.getMachineMemOperand(MMO, 0, 16);
12560 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
12561 SDValue Op = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
12562 WidenedMemVT, WidenedMMO);
12564 DAG.getVectorIdxConstant(0, DL));
12565 return DAG.getMergeValues({Value, SDValue(Op.getNode(), 1)}, DL);
12566 }
12567
12568 return DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, MemVT, MMO);
12569}
12570
12571SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
12572 bool ImageStore) const {
12573 EVT StoreVT = VData.getValueType();
12574
12575 // No change for f16 and legal vector D16 types.
12576 if (!StoreVT.isVector())
12577 return VData;
12578
12579 SDLoc DL(VData);
12580 unsigned NumElements = StoreVT.getVectorNumElements();
12581
12582 if (Subtarget->hasUnpackedD16VMem()) {
12583 // We need to unpack the packed data to store.
12584 EVT IntStoreVT = StoreVT.changeTypeToInteger();
12585 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12586
12587 EVT EquivStoreVT =
12588 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
12589 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
12590 return DAG.UnrollVectorOp(ZExt.getNode());
12591 }
12592
12593 // The sq block of gfx8.1 does not estimate register use correctly for d16
12594 // image store instructions. The data operand is computed as if it were not a
12595 // d16 image instruction.
12596 if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
12597 // Bitcast to i16
12598 EVT IntStoreVT = StoreVT.changeTypeToInteger();
12599 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12600
12601 // Decompose into scalars
12603 DAG.ExtractVectorElements(IntVData, Elts);
12604
12605 // Group pairs of i16 into v2i16 and bitcast to i32
12606 SmallVector<SDValue, 4> PackedElts;
12607 for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
12608 SDValue Pair =
12609 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
12610 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
12611 PackedElts.push_back(IntPair);
12612 }
12613 if ((NumElements % 2) == 1) {
12614 // Handle v3i16
12615 unsigned I = Elts.size() / 2;
12616 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
12617 {Elts[I * 2], DAG.getPOISON(MVT::i16)});
12618 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
12619 PackedElts.push_back(IntPair);
12620 }
12621
12622 // Pad using UNDEF
12623 PackedElts.resize(Elts.size(), DAG.getPOISON(MVT::i32));
12624
12625 // Build final vector
12626 EVT VecVT =
12627 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
12628 return DAG.getBuildVector(VecVT, DL, PackedElts);
12629 }
12630
12631 if (NumElements == 3) {
12632 EVT IntStoreVT =
12634 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
12635
12636 EVT WidenedStoreVT = EVT::getVectorVT(
12637 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
12638 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
12639 WidenedStoreVT.getStoreSizeInBits());
12640 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
12641 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
12642 }
12643
12644 assert(isTypeLegal(StoreVT));
12645 return VData;
12646}
12647
12648static bool isAsyncLDSDMA(Intrinsic::ID Intr) {
12649 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
12651 return BufInfo->IsAsync;
12652 switch (Intr) {
12653 case Intrinsic::amdgcn_load_async_to_lds:
12654 case Intrinsic::amdgcn_global_load_async_lds:
12655 return true;
12656 }
12657 return false;
12658}
12659
12660// Lower the buffer stores, loads to LDS and prefetches, which are all
12661// INTRINSIC_VOID nodes.
12662SDValue SITargetLowering::lowerBufferIntrinsicVoid(
12664 SelectionDAG &DAG) const {
12665 SDLoc DL(Op);
12666 SDValue Chain = Op.getOperand(0);
12667 auto *M = cast<MemSDNode>(Op);
12668 auto GetArg = [&](unsigned Arg) {
12669 return Op.getOperand(AMDGPU::getSDOperandIdx(Arg));
12670 };
12671
12672 switch (Info.Kind) {
12673 case AMDGPU::BufferKindStore: {
12674 SDValue VData = GetArg(*Info.getVDataArg());
12675 EVT VDataVT = VData.getValueType();
12676 EVT EltType = VDataVT.getScalarType();
12677
12678 if (Info.isTyped()) {
12679 bool IsD16 = EltType.getSizeInBits() == 16;
12680 if (IsD16)
12681 VData = handleD16VData(VData, DAG);
12683 getBufferIntrinsicOps(Op, Info, DAG, VData);
12684 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16
12685 : AMDGPUISD::TBUFFER_STORE_FORMAT;
12686 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12687 M->getMemoryVT(), M->getMemOperand());
12688 }
12689
12690 bool IsFormat = Info.isFormatFromRsrc();
12691 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
12692
12693 if (IsFormat && !IsD16 && EltType.getSizeInBits() < 32) {
12694 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
12696 "unsupported sub-dword format buffer store", DL.getDebugLoc()));
12697 return Chain;
12698 }
12699
12700 if (IsD16) {
12701 VData = handleD16VData(VData, DAG);
12702 VDataVT = VData.getValueType();
12703 }
12704
12705 if (!isTypeLegal(VDataVT)) {
12706 VData =
12707 DAG.getNode(ISD::BITCAST, DL,
12708 getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
12709 }
12710
12711 SmallVector<SDValue, 10> Ops = getBufferIntrinsicOps(Op, Info, DAG, VData);
12712 unsigned Opc =
12713 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
12714 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
12715
12716 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
12717 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
12718 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops.data(), M);
12719
12720 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
12721 M->getMemoryVT(), M->getMemOperand());
12722 }
12723 case AMDGPU::BufferKindLoadToLDS: {
12724 unsigned Opc;
12725 std::optional<unsigned> VIndexArg = Info.getVIndexArg();
12726 bool HasVIndex = VIndexArg.has_value();
12727 SDValue VOffset = GetArg(*Info.getVOffsetArg());
12728 bool HasVOffset = !isNullConstant(VOffset);
12729 unsigned Size = GetArg(*Info.getSizeArg())->getAsZExtVal();
12730
12731 switch (Size) {
12732 default:
12733 return SDValue();
12734 case 1:
12735 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
12736 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
12737 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
12738 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
12739 break;
12740 case 2:
12741 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
12742 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
12743 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
12744 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
12745 break;
12746 case 4:
12747 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
12748 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
12749 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
12750 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
12751 break;
12752 case 12:
12753 if (!Subtarget->hasLDSLoadB96_B128())
12754 return SDValue();
12755 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_BOTHEN
12756 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_IDXEN
12757 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFEN
12758 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFSET;
12759 break;
12760 case 16:
12761 if (!Subtarget->hasLDSLoadB96_B128())
12762 return SDValue();
12763 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_BOTHEN
12764 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_IDXEN
12765 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFEN
12766 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFSET;
12767 break;
12768 }
12769
12770 SDValue M0Val = copyToM0(DAG, Chain, DL, GetArg(*Info.getLDSPtrArg()));
12771
12773
12774 if (HasVIndex && HasVOffset)
12775 Ops.push_back(
12776 DAG.getBuildVector(MVT::v2i32, DL, {GetArg(*VIndexArg), VOffset}));
12777 else if (HasVIndex)
12778 Ops.push_back(GetArg(*VIndexArg));
12779 else if (HasVOffset)
12780 Ops.push_back(VOffset);
12781
12782 SDValue Rsrc = bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG);
12783 Ops.push_back(Rsrc);
12784 Ops.push_back(GetArg(*Info.getSOffsetArg()));
12785 Ops.push_back(GetArg(*Info.getImmOffsetArg()));
12786 bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
12787 unsigned Aux = GetArg(*Info.getAuxArg())->getAsZExtVal();
12788 Ops.push_back(DAG.getTargetConstant(
12789 Aux & (IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12),
12790 DL, MVT::i16)); // cpol
12791 Ops.push_back(DAG.getTargetConstant(
12792 Aux & (IsGFX12Plus ? AMDGPU::CPol::SWZ : AMDGPU::CPol::SWZ_pregfx12)
12793 ? 1
12794 : 0,
12795 DL, MVT::i8)); // swz
12796 Ops.push_back(DAG.getTargetConstant(Info.IsAsync, DL, MVT::i8)); // async
12797 Ops.push_back(M0Val.getValue(0)); // Chain
12798 Ops.push_back(M0Val.getValue(1)); // Glue
12799
12800 auto *Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
12801 DAG.setNodeMemRefs(Load, M->memoperands());
12802
12803 return SDValue(Load, 0);
12804 }
12805 case AMDGPU::BufferKindPrefetch: {
12806 SDValue Ops[] = {
12807 Chain,
12808 bufferRsrcPtrToVector(GetArg(Info.RsrcArg), DAG),
12809 GetArg(*Info.getSOffsetArg()), // soffset
12810 GetArg(*Info.getSizeArg()), // length
12811 };
12812
12813 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_PREFETCH_DATA, DL,
12814 Op->getVTList(), Ops, M->getMemoryVT(),
12815 M->getMemOperand());
12816 }
12817 default:
12818 llvm_unreachable("not a buffer intrinsic without a result");
12819 }
12820}
12821
12822SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
12823 SelectionDAG &DAG) const {
12824 SDLoc DL(Op);
12825 SDValue Chain = Op.getOperand(0);
12826 unsigned IntrinsicID = Op.getConstantOperandVal(1);
12827
12828 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
12829 AMDGPU::lookupBufferIntrinsic(IntrinsicID))
12830 return lowerBufferIntrinsicVoid(Op, *BufInfo, DAG);
12831
12832 switch (IntrinsicID) {
12833 case Intrinsic::amdgcn_cluster_load_async_to_lds_b8:
12834 case Intrinsic::amdgcn_cluster_load_async_to_lds_b32:
12835 case Intrinsic::amdgcn_cluster_load_async_to_lds_b64:
12836 case Intrinsic::amdgcn_cluster_load_async_to_lds_b128: {
12837 foldAsyncLDSOffset(Op, DAG, DL);
12838 if (Subtarget->hasGFX1250_STRICT())
12840 return SDValue();
12841 }
12842 case Intrinsic::amdgcn_global_load_async_to_lds_b8:
12843 case Intrinsic::amdgcn_global_load_async_to_lds_b32:
12844 case Intrinsic::amdgcn_global_load_async_to_lds_b64:
12845 case Intrinsic::amdgcn_global_load_async_to_lds_b128:
12846 case Intrinsic::amdgcn_global_store_async_from_lds_b8:
12847 case Intrinsic::amdgcn_global_store_async_from_lds_b32:
12848 case Intrinsic::amdgcn_global_store_async_from_lds_b64:
12849 case Intrinsic::amdgcn_global_store_async_from_lds_b128:
12850 foldAsyncLDSOffset(Op, DAG, DL);
12851 return SDValue();
12852 case Intrinsic::amdgcn_exp_compr: {
12853 SDValue Src0 = Op.getOperand(4);
12854 SDValue Src1 = Op.getOperand(5);
12855 // Hack around illegal type on SI by directly selecting it.
12856 if (isTypeLegal(Src0.getValueType()))
12857 return SDValue();
12858
12859 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
12860 SDValue Undef = DAG.getPOISON(MVT::f32);
12861 const SDValue Ops[] = {
12862 Op.getOperand(2), // tgt
12863 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
12864 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
12865 Undef, // src2
12866 Undef, // src3
12867 Op.getOperand(7), // vm
12868 DAG.getTargetConstant(1, DL, MVT::i1), // compr
12869 Op.getOperand(3), // en
12870 Op.getOperand(0) // Chain
12871 };
12872
12873 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
12874 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
12875 }
12876
12877 // Buffers are handled by LowerBufferFatPointers, and we're going to go
12878 // for "trust me" that the remaining cases are global pointers until
12879 // such time as we can put two mem operands on an intrinsic.
12880 case Intrinsic::amdgcn_load_to_lds:
12881 case Intrinsic::amdgcn_load_async_to_lds:
12882 case Intrinsic::amdgcn_global_load_lds:
12883 case Intrinsic::amdgcn_global_load_async_lds: {
12884 if (!Subtarget->hasVMemToLDSLoad())
12885 return SDValue();
12886
12887 unsigned Opc;
12888 unsigned Size = Op->getConstantOperandVal(4);
12889 switch (Size) {
12890 default:
12891 return SDValue();
12892 case 1:
12893 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
12894 break;
12895 case 2:
12896 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
12897 break;
12898 case 4:
12899 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
12900 break;
12901 case 12:
12902 if (!Subtarget->hasLDSLoadB96_B128())
12903 return SDValue();
12904 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX3;
12905 break;
12906 case 16:
12907 if (!Subtarget->hasLDSLoadB96_B128())
12908 return SDValue();
12909 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX4;
12910 break;
12911 }
12912
12913 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
12914
12916
12917 SDValue Addr = Op.getOperand(2); // Global ptr
12918 SDValue VOffset;
12919 // Try to split SAddr and VOffset. Global and LDS pointers share the same
12920 // immediate offset, so we cannot use a regular SelectGlobalSAddr().
12921 if (Addr->isDivergent() && Addr->isAnyAdd()) {
12922 SDValue LHS = Addr.getOperand(0);
12923 SDValue RHS = Addr.getOperand(1);
12924
12925 if (LHS->isDivergent())
12926 std::swap(LHS, RHS);
12927
12928 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
12929 RHS.getOperand(0).getValueType() == MVT::i32) {
12930 // add (i64 sgpr), (zero_extend (i32 vgpr))
12931 Addr = LHS;
12932 VOffset = RHS.getOperand(0);
12933 }
12934 }
12935
12936 Ops.push_back(Addr);
12937 if (!Addr->isDivergent()) {
12939 if (!VOffset)
12940 VOffset =
12941 SDValue(DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
12942 DAG.getTargetConstant(0, DL, MVT::i32)),
12943 0);
12944 Ops.push_back(VOffset);
12945 }
12946
12947 Ops.push_back(Op.getOperand(5)); // Offset
12948
12949 unsigned Aux = Op.getConstantOperandVal(6);
12950 Ops.push_back(DAG.getTargetConstant(Aux & ~AMDGPU::CPol::VIRTUAL_BITS, DL,
12951 MVT::i32)); // CPol
12952 Ops.push_back(
12953 DAG.getTargetConstant(isAsyncLDSDMA(IntrinsicID), DL, MVT::i8));
12954
12955 Ops.push_back(M0Val.getValue(0)); // Chain
12956 Ops.push_back(M0Val.getValue(1)); // Glue
12957
12958 auto *M = cast<MemSDNode>(Op);
12959 auto *Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
12960 DAG.setNodeMemRefs(Load, M->memoperands());
12961
12962 return SDValue(Load, 0);
12963 }
12964 case Intrinsic::amdgcn_end_cf:
12965 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
12966 Op->getOperand(2), Chain),
12967 0);
12968 case Intrinsic::amdgcn_s_barrier_signal_var: {
12969 // Member count of 0 means to re-use a previous member count,
12970 // which, if the named barrier is statically chosen, means we can use
12971 // the immarg form. Otherwisee, fall through to constructiong M0 as for
12972 // s_barrier_init.
12973 SDValue CntOp = Op->getOperand(3);
12974 auto *CntC = dyn_cast<ConstantSDNode>(CntOp);
12975 if (CntC && CntC->isZero()) {
12976 SDValue Chain = Op->getOperand(0);
12977 SDValue BarOp = Op->getOperand(2);
12978
12979 if (auto BarID = getConstantNamedBarrierNumber(BarOp, DAG)) {
12980 std::array<SDValue, 2> Ops = {
12981 DAG.getTargetConstant(*BarID, DL, MVT::i32), Chain};
12982 auto *NewMI = DAG.getMachineNode(AMDGPU::S_BARRIER_SIGNAL_IMM, DL,
12983 Op->getVTList(), Ops);
12984 return SDValue(NewMI, 0);
12985 }
12986 }
12987 [[fallthrough]];
12988 }
12989 case Intrinsic::amdgcn_s_barrier_init: {
12990 // these two intrinsics have two operands: barrier pointer and member count
12991 SDValue Chain = Op->getOperand(0);
12993 SDValue BarOp = Op->getOperand(2);
12994 SDValue CntOp = Op->getOperand(3);
12995 SDValue M0Val;
12996 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_s_barrier_init
12997 ? AMDGPU::S_BARRIER_INIT_M0
12998 : AMDGPU::S_BARRIER_SIGNAL_M0;
12999 // extract the BarrierID from bits 0-5 of BarOp
13000 SDValue BarID = DAG.getNode(ISD::AND, DL, MVT::i32, BarOp,
13001 DAG.getConstant(0x3F, DL, MVT::i32));
13002 // Member count should be put into M0[ShAmt:+CntMask width]
13003 // Barrier ID should be put into M0[5:0]
13004 unsigned CntMask = AMDGPU::getBarrierMemberCountBitMask(
13005 AMDGPU::getIsaVersion(Subtarget->getCPU()));
13006 SDValue MemberCnt = DAG.getNode(ISD::AND, DL, MVT::i32, CntOp,
13007 DAG.getConstant(CntMask, DL, MVT::i32));
13008 constexpr unsigned ShAmt = 16;
13009 M0Val = DAG.getNode(ISD::SHL, DL, MVT::i32, MemberCnt,
13010 DAG.getShiftAmountConstant(ShAmt, MVT::i32, DL));
13011
13012 M0Val = DAG.getNode(ISD::OR, DL, MVT::i32, M0Val, BarID);
13013
13014 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
13015
13016 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
13017 return SDValue(NewMI, 0);
13018 }
13019 case Intrinsic::amdgcn_s_wakeup_barrier: {
13020 if (!Subtarget->hasSWakeupBarrier())
13021 return SDValue();
13022 [[fallthrough]];
13023 }
13024 case Intrinsic::amdgcn_s_barrier_join: {
13025 // these three intrinsics have one operand: barrier pointer
13026 SDValue Chain = Op->getOperand(0);
13028 SDValue BarOp = Op->getOperand(2);
13029 unsigned Opc;
13030
13031 if (auto BarID = getConstantNamedBarrierNumber(BarOp, DAG)) {
13032 switch (IntrinsicID) {
13033 default:
13034 return SDValue();
13035 case Intrinsic::amdgcn_s_barrier_join:
13036 Opc = AMDGPU::S_BARRIER_JOIN_IMM;
13037 break;
13038 case Intrinsic::amdgcn_s_wakeup_barrier:
13039 Opc = AMDGPU::S_WAKEUP_BARRIER_IMM;
13040 break;
13041 }
13042 SDValue K = DAG.getTargetConstant(*BarID, DL, MVT::i32);
13043 Ops.push_back(K);
13044 Ops.push_back(Chain);
13045 } else {
13046 switch (IntrinsicID) {
13047 default:
13048 return SDValue();
13049 case Intrinsic::amdgcn_s_barrier_join:
13050 Opc = AMDGPU::S_BARRIER_JOIN_M0;
13051 break;
13052 case Intrinsic::amdgcn_s_wakeup_barrier:
13053 Opc = AMDGPU::S_WAKEUP_BARRIER_M0;
13054 break;
13055 }
13056 // extract the BarrierID from bits 0-5 of BarOp, copy to M0[5:0]
13057 SDValue M0Val = DAG.getNode(ISD::AND, DL, MVT::i32, BarOp,
13058 DAG.getConstant(0x3F, DL, MVT::i32));
13059 Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
13060 }
13061
13062 auto *NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
13063 return SDValue(NewMI, 0);
13064 }
13065 case Intrinsic::amdgcn_s_prefetch_data:
13066 case Intrinsic::amdgcn_s_prefetch_inst: {
13067 // For non-global address space preserve the chain and remove the call.
13069 return Op.getOperand(0);
13070 return Op;
13071 }
13072 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
13073 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
13074 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
13075 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
13076 SDValue Chain = Op->getOperand(0);
13077 SDValue Ptr = Op->getOperand(2);
13078 SDValue Val = Op->getOperand(3);
13079 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MII->getMemoryVT(), Chain, Val,
13080 Ptr, MII->getMemOperand());
13081 }
13082 case Intrinsic::amdgcn_av_store_b8:
13083 case Intrinsic::amdgcn_av_store_b16:
13084 case Intrinsic::amdgcn_av_store_b32:
13085 case Intrinsic::amdgcn_av_store_b64:
13086 case Intrinsic::amdgcn_av_store_b128: {
13087 MemIntrinsicSDNode *MII = cast<MemIntrinsicSDNode>(Op);
13088 SDValue Chain = Op->getOperand(0);
13089 SDValue Ptr = Op->getOperand(2);
13090 SDValue Val = Op->getOperand(3);
13091 return DAG.getStore(Chain, DL, Val, Ptr, MII->getMemOperand());
13092 }
13093 default: {
13094 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
13096 return lowerImage(Op, ImageDimIntr, DAG, true);
13097
13098 return Op;
13099 }
13100 }
13101}
13102
13103// Return whether the operation has NoUnsignedWrap property.
13104static bool isNoUnsignedWrap(SDValue Addr) {
13105 return (Addr.getOpcode() == ISD::ADD &&
13106 Addr->getFlags().hasNoUnsignedWrap()) ||
13107 Addr->getOpcode() == ISD::OR;
13108}
13109
13111 EVT PtrVT) const {
13112 return PtrVT == MVT::i64;
13113}
13114
13116 EVT PtrVT) const {
13117 return true;
13118}
13119
13120// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
13121// offset (the offset that is included in bounds checking and swizzling, to be
13122// split between the instruction's voffset and immoffset fields) and soffset
13123// (the offset that is excluded from bounds checking and swizzling, to go in
13124// the instruction's soffset field). This function takes the first kind of
13125// offset and figures out how to split it between voffset and immoffset.
13126std::pair<SDValue, SDValue>
13127SITargetLowering::splitBufferOffsets(SDValue Offset, SelectionDAG &DAG) const {
13128 SDLoc DL(Offset);
13129 const unsigned MaxImm = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
13130 SDValue N0 = Offset;
13131 ConstantSDNode *C1 = nullptr;
13132
13133 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
13134 N0 = SDValue();
13135 else if (DAG.isBaseWithConstantOffset(N0)) {
13136 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
13137 // being added, so we can only safely match a 32-bit addition with no
13138 // unsigned overflow.
13139 bool CheckNUW = Subtarget->hasGFX1250Insts();
13140 if (!CheckNUW || isNoUnsignedWrap(N0)) {
13142 N0 = N0.getOperand(0);
13143 }
13144 }
13145
13146 if (C1) {
13147 unsigned ImmOffset = C1->getZExtValue();
13148 // If the immediate value is too big for the immoffset field, put only bits
13149 // that would normally fit in the immoffset field. The remaining value that
13150 // is copied/added for the voffset field is a large power of 2, and it
13151 // stands more chance of being CSEd with the copy/add for another similar
13152 // load/store.
13153 // However, do not do that rounding down if that is a negative
13154 // number, as it appears to be illegal to have a negative offset in the
13155 // vgpr, even if adding the immediate offset makes it positive.
13156 unsigned Overflow = ImmOffset & ~MaxImm;
13157 ImmOffset -= Overflow;
13158 if ((int32_t)Overflow < 0) {
13159 Overflow += ImmOffset;
13160 ImmOffset = 0;
13161 }
13162 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
13163 if (Overflow) {
13164 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
13165 if (!N0)
13166 N0 = OverflowVal;
13167 else {
13168 SDValue Ops[] = {N0, OverflowVal};
13169 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
13170 }
13171 }
13172 }
13173 if (!N0)
13174 N0 = DAG.getConstant(0, DL, MVT::i32);
13175 if (!C1)
13176 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
13177 return {N0, SDValue(C1, 0)};
13178}
13179
13180// Analyze a combined offset from an amdgcn_s_buffer_load intrinsic and store
13181// the three offsets (voffset, soffset and instoffset) into the SDValue[3] array
13182// pointed to by Offsets.
13183void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
13184 SelectionDAG &DAG, SDValue *Offsets,
13185 Align Alignment) const {
13186 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
13187 SDLoc DL(CombinedOffset);
13188 if (auto *C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
13189 uint32_t Imm = C->getZExtValue();
13190 uint32_t SOffset, ImmOffset;
13191 if (TII->splitMUBUFOffset(Imm, SOffset, ImmOffset, Alignment)) {
13192 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
13193 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
13194 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
13195 return;
13196 }
13197 }
13198 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
13199 // On GFX1250+, voffset and immoffset are zero-extended from 32 bits before
13200 // being added, so we can only safely match a 32-bit addition with no
13201 // unsigned overflow.
13202 bool CheckNUW = Subtarget->hasGFX1250Insts();
13203 SDValue N0 = CombinedOffset.getOperand(0);
13204 SDValue N1 = CombinedOffset.getOperand(1);
13205 uint32_t SOffset, ImmOffset;
13206 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
13207 if (Offset >= 0 && (!CheckNUW || isNoUnsignedWrap(CombinedOffset)) &&
13208 TII->splitMUBUFOffset(Offset, SOffset, ImmOffset, Alignment)) {
13209 Offsets[0] = N0;
13210 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
13211 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
13212 return;
13213 }
13214 }
13215
13216 SDValue SOffsetZero = Subtarget->hasRestrictedSOffset()
13217 ? DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32)
13218 : DAG.getConstant(0, DL, MVT::i32);
13219
13220 Offsets[0] = CombinedOffset;
13221 Offsets[1] = SOffsetZero;
13222 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
13223}
13224
13225SDValue SITargetLowering::bufferRsrcPtrToVector(SDValue MaybePointer,
13226 SelectionDAG &DAG) const {
13227 if (!MaybePointer.getValueType().isScalarInteger())
13228 return MaybePointer;
13229
13230 SDValue Rsrc = DAG.getBitcast(MVT::v4i32, MaybePointer);
13231 return Rsrc;
13232}
13233
13234// Wrap a global or flat pointer into a buffer intrinsic using the flags
13235// specified in the intrinsic.
13236SDValue SITargetLowering::lowerPointerAsRsrcIntrin(SDNode *Op,
13237 SelectionDAG &DAG) const {
13238 SDLoc Loc(Op);
13239
13240 SDValue Pointer = Op->getOperand(1);
13241 SDValue Stride = Op->getOperand(2);
13242 SDValue NumRecords = Op->getOperand(3);
13243 SDValue Flags = Op->getOperand(4);
13244
13245 SDValue ExtStride = DAG.getAnyExtOrTrunc(Stride, Loc, MVT::i32);
13246 SDValue Rsrc;
13247
13248 if (Subtarget->getBufferResourceNumRecordsWidth() == 45) {
13249 NumRecords = DAG.getZExtOrTrunc(NumRecords, Loc, MVT::i64);
13250 NumRecords = DAG.getNode(ISD::AND, Loc, MVT::i64, NumRecords,
13251 DAG.getConstant((1ULL << 45) - 1, Loc, MVT::i64));
13252 SDValue Zero = DAG.getConstant(0, Loc, MVT::i32);
13253 // Build the lower 64-bit value, which has a 57-bit base and the lower 7-bit
13254 // num_records.
13255 SDValue ExtPointer = DAG.getAnyExtOrTrunc(Pointer, Loc, MVT::i64);
13256 SDValue NumRecordsLHS =
13257 DAG.getNode(ISD::SHL, Loc, MVT::i64, NumRecords,
13258 DAG.getShiftAmountConstant(57, MVT::i32, Loc));
13259 SDValue LowHalf =
13260 DAG.getNode(ISD::OR, Loc, MVT::i64, ExtPointer, NumRecordsLHS);
13261
13262 // Build the higher 64-bit value, which has the higher 38-bit num_records,
13263 // 6-bit zero (omit), 16-bit stride and scale and 4-bit flag.
13264 SDValue NumRecordsRHS =
13265 DAG.getNode(ISD::SRL, Loc, MVT::i64, NumRecords,
13266 DAG.getShiftAmountConstant(7, MVT::i32, Loc));
13267 SDValue ShiftedStride =
13268 DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
13269 DAG.getShiftAmountConstant(12, MVT::i32, Loc));
13270 SDValue ExtShiftedStrideVec =
13271 DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i32, Zero, ShiftedStride);
13272 SDValue ExtShiftedStride =
13273 DAG.getNode(ISD::BITCAST, Loc, MVT::i64, ExtShiftedStrideVec);
13274 SDValue ShiftedFlags =
13275 DAG.getNode(ISD::SHL, Loc, MVT::i32, Flags,
13276 DAG.getShiftAmountConstant(28, MVT::i32, Loc));
13277 SDValue ExtShiftedFlagsVec =
13278 DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i32, Zero, ShiftedFlags);
13279 SDValue ExtShiftedFlags =
13280 DAG.getNode(ISD::BITCAST, Loc, MVT::i64, ExtShiftedFlagsVec);
13281 SDValue CombinedFields =
13282 DAG.getNode(ISD::OR, Loc, MVT::i64, NumRecordsRHS, ExtShiftedStride);
13283 SDValue HighHalf =
13284 DAG.getNode(ISD::OR, Loc, MVT::i64, CombinedFields, ExtShiftedFlags);
13285
13286 Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v2i64, LowHalf, HighHalf);
13287 } else {
13288 NumRecords = DAG.getZExtOrTrunc(NumRecords, Loc, MVT::i32);
13289 auto [LowHalf, HighHalf] =
13290 DAG.SplitScalar(Pointer, Loc, MVT::i32, MVT::i32);
13291 SDValue Mask = DAG.getConstant(0x0000ffff, Loc, MVT::i32);
13292 SDValue Masked = DAG.getNode(ISD::AND, Loc, MVT::i32, HighHalf, Mask);
13293 SDValue ShiftedStride =
13294 DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
13295 DAG.getShiftAmountConstant(16, MVT::i32, Loc));
13296 SDValue NewHighHalf =
13297 DAG.getNode(ISD::OR, Loc, MVT::i32, Masked, ShiftedStride);
13298
13299 Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v4i32, LowHalf, NewHighHalf,
13300 NumRecords, Flags);
13301 }
13302
13303 SDValue RsrcPtr = DAG.getNode(ISD::BITCAST, Loc, MVT::i128, Rsrc);
13304 return RsrcPtr;
13305}
13306
13307// Handle 8 bit and 16 bit buffer loads
13308SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
13309 EVT LoadVT, SDLoc DL,
13311 MachineMemOperand *MMO,
13312 bool IsTFE) const {
13313 EVT IntVT = LoadVT.changeTypeToInteger();
13314
13315 if (IsTFE) {
13316 unsigned Opc = (LoadVT.getScalarType() == MVT::i8)
13317 ? AMDGPUISD::BUFFER_LOAD_UBYTE_TFE
13318 : AMDGPUISD::BUFFER_LOAD_USHORT_TFE;
13320 MachineMemOperand *OpMMO = MF.getMachineMemOperand(MMO, 0, 8);
13321 SDVTList VTs = DAG.getVTList(MVT::v2i32, MVT::Other);
13322 SDValue Op = getMemIntrinsicNode(Opc, DL, VTs, Ops, MVT::v2i32, OpMMO, DAG);
13323 SDValue Status = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
13324 DAG.getConstant(1, DL, MVT::i32));
13325 SDValue Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
13326 DAG.getConstant(0, DL, MVT::i32));
13327 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Data);
13328 SDValue Value = DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc);
13329 return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
13330 }
13331
13332 unsigned Opc = LoadVT.getScalarType() == MVT::i8
13333 ? AMDGPUISD::BUFFER_LOAD_UBYTE
13334 : AMDGPUISD::BUFFER_LOAD_USHORT;
13335
13336 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
13337 SDValue BufferLoad =
13338 DAG.getMemIntrinsicNode(Opc, DL, ResList, Ops, IntVT, MMO);
13339 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
13340 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
13341
13342 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
13343}
13344
13345// Handle 8 bit and 16 bit buffer stores
13346SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
13347 EVT VDataType, SDLoc DL,
13348 SDValue Ops[],
13349 MemSDNode *M) const {
13350 if (VDataType == MVT::f16 || VDataType == MVT::bf16)
13351 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
13352
13353 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
13354 Ops[1] = BufferStoreExt;
13355 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE
13356 : AMDGPUISD::BUFFER_STORE_SHORT;
13357 ArrayRef<SDValue> OpsRef = ArrayRef(&Ops[0], 9);
13358 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
13359 M->getMemOperand());
13360}
13361
13363 SDValue Op, const SDLoc &SL, EVT VT) {
13364 if (VT.bitsLT(Op.getValueType()))
13365 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
13366
13367 switch (ExtType) {
13368 case ISD::SEXTLOAD:
13369 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
13370 case ISD::ZEXTLOAD:
13371 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
13372 case ISD::EXTLOAD:
13373 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
13374 case ISD::NON_EXTLOAD:
13375 return Op;
13376 }
13377
13378 llvm_unreachable("invalid ext type");
13379}
13380
13381// Try to turn 8 and 16-bit scalar loads into SMEM eligible 32-bit loads.
13382// TODO: Skip this on GFX12 which does have scalar sub-dword loads.
13383SDValue SITargetLowering::widenLoad(LoadSDNode *Ld,
13384 DAGCombinerInfo &DCI) const {
13385 SelectionDAG &DAG = DCI.DAG;
13386 if (Ld->getAlign() < Align(4) || Ld->isDivergent())
13387 return SDValue();
13388
13389 // FIXME: Constant loads should all be marked invariant.
13390 unsigned AS = Ld->getAddressSpace();
13391 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
13393 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
13394 return SDValue();
13395
13396 // Don't do this early, since it may interfere with adjacent load merging for
13397 // illegal types. We can avoid losing alignment information for exotic types
13398 // pre-legalize.
13399 EVT MemVT = Ld->getMemoryVT();
13400 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
13401 MemVT.getSizeInBits() >= 32)
13402 return SDValue();
13403
13404 SDLoc SL(Ld);
13405
13406 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
13407 "unexpected vector extload");
13408
13409 // TODO: Drop only high part of range.
13410 SDValue Ptr = Ld->getBasePtr();
13411 SDValue NewLoad = DAG.getLoad(
13412 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
13413 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
13414 Ld->getMemOperand()->getFlags(), Ld->getAAInfo()); // Drop ranges
13415
13416 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
13417 if (MemVT.isFloatingPoint()) {
13418 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
13419 "unexpected fp extload");
13420 TruncVT = MemVT.changeTypeToInteger();
13421 }
13422
13423 SDValue Cvt = NewLoad;
13424 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
13425 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
13426 DAG.getValueType(TruncVT));
13427 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
13428 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
13429 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
13430 } else {
13431 assert(Ld->getExtensionType() == ISD::EXTLOAD);
13432 }
13433
13434 EVT VT = Ld->getValueType(0);
13435 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
13436
13437 DCI.AddToWorklist(Cvt.getNode());
13438
13439 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
13440 // the appropriate extension from the 32-bit load.
13441 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
13442 DCI.AddToWorklist(Cvt.getNode());
13443
13444 // Handle conversion back to floating point if necessary.
13445 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
13446
13447 return DAG.getMergeValues({Cvt, NewLoad.getValue(1)}, SL);
13448}
13449
13451 const SIMachineFunctionInfo &Info) {
13452 // TODO: Should check if the address can definitely not access stack.
13453 if (Info.isEntryFunction())
13454 return Info.getUserSGPRInfo().hasFlatScratchInit();
13455 return true;
13456}
13457
13458// Lower a VGPR ("as memory") load or store to a REG_LOAD / REG_STORE node
13459// carrying the dword index. TODO: sub-dword accesses.
13460SDValue SITargetLowering::lowerLoadStoreVGPR(SDValue Op,
13461 SelectionDAG &DAG) const {
13462 SDLoc DL(Op);
13463 MemSDNode *MemOp = cast<MemSDNode>(Op);
13464 EVT MemVT = MemOp->getMemoryVT();
13465 unsigned BitWidth = MemVT.getSizeInBits();
13466
13467 // Each caller replaces the node, so this is diagnosed once.
13468 auto reportUnsupported = [&]() -> SDValue {
13469 const Function &F = DAG.getMachineFunction().getFunction();
13470 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
13471 F,
13472 "unsupported access of VGPR 'as memory' address space (13); only "
13473 "dword-aligned whole-dword loads and stores are implemented",
13474 DL.getDebugLoc()));
13475 SmallVector<EVT, 2> ResultTypes(Op->values());
13476 return DAG.getErrorMergeValues(ResultTypes, MemOp->getChain(), DL);
13477 };
13478
13479 if (BitWidth < 32)
13480 return reportUnsupported();
13481
13482 // The index is the pointer >> 2, so an under-aligned access would silently
13483 // reach the containing dword rather than the bytes asked for.
13484 if (MemOp->getAlign() < Align(4))
13485 return reportUnsupported();
13486 auto *Store = dyn_cast<StoreSDNode>(MemOp);
13487 if (Store && Store->isTruncatingStore())
13488 return reportUnsupported();
13489 // Only a width some VGPR tuple has is looked up. A whole-dword access of any
13490 // other width is done as one of <N x i32>, which type legalization splits.
13491 auto *Load = dyn_cast<LoadSDNode>(MemOp);
13492 if (!Subtarget->getRegisterInfo()->getVGPRClassForBitWidth(BitWidth) ||
13494 if (BitWidth % 32 != 0)
13495 return reportUnsupported();
13496 EVT ViewVT = getEquivalentMemType(*DAG.getContext(), MemVT);
13497 if (Store) {
13498 if (MemVT == ViewVT)
13499 return SDValue();
13500 return DAG.getStore(Store->getChain(), DL,
13501 DAG.getBitcast(ViewVT, Store->getValue()),
13502 Store->getBasePtr(), Store->getMemOperand());
13503 }
13504 if (MemVT == ViewVT && Load->getExtensionType() == ISD::NON_EXTLOAD)
13505 return SDValue();
13506 // The range is for the elements of MemVT, not for dwords.
13507 Load->getMemOperand()->clearRanges();
13508 SDValue NewLoad = DAG.getLoad(ViewVT, DL, Load->getChain(),
13509 Load->getBasePtr(), Load->getMemOperand());
13510 SDValue Value = getLoadExtOrTrunc(DAG, Load->getExtensionType(),
13511 DAG.getBitcast(MemVT, NewLoad), DL,
13512 Load->getValueType(0));
13513 return DAG.getMergeValues({Value, NewLoad.getValue(1)}, DL);
13514 }
13515
13516 SDValue Chain = MemOp->getChain();
13517 SDValue Index = DAG.getNode(ISD::SRL, DL, MVT::i32, MemOp->getBasePtr(),
13518 DAG.getConstant(2, DL, MVT::i32));
13519
13520 // View as i32 / <N x i32> when the memory type is not register legal.
13521 EVT RegVT = MemVT;
13522 if (!isTypeLegal(RegVT)) {
13523 unsigned NumDwords = BitWidth / 32;
13524 RegVT = NumDwords == 1
13525 ? EVT(MVT::i32)
13526 : EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumDwords);
13527 }
13528
13529 if (Store) {
13530 SDValue Value = DAG.getBitcast(RegVT, Store->getValue());
13531 return DAG.getMemIntrinsicNode(
13532 AMDGPUISD::REG_STORE, DL, DAG.getVTList(MVT::Other),
13533 {Chain, Value, Index}, MemVT, Store->getMemOperand());
13534 }
13535
13536 SDValue NewLoad = DAG.getMemIntrinsicNode(
13537 AMDGPUISD::REG_LOAD, DL, DAG.getVTList(RegVT, MVT::Other), {Chain, Index},
13538 MemVT, Load->getMemOperand());
13539 SDValue Value = DAG.getBitcast(MemVT, NewLoad);
13540 // The combiner folds an extension of a whole-dword load into the load.
13541 Value = getLoadExtOrTrunc(DAG, Load->getExtensionType(), Value, DL,
13542 Load->getValueType(0));
13543 if (Value == NewLoad)
13544 return NewLoad;
13545 return DAG.getMergeValues({Value, NewLoad.getValue(1)}, DL);
13546}
13547
13548SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
13549 SDLoc DL(Op);
13550 LoadSDNode *Load = cast<LoadSDNode>(Op);
13551 assert(Load->getExtensionType() == ISD::NON_EXTLOAD &&
13552 "Unexpected custom extending load!");
13553 EVT MemVT = Load->getMemoryVT();
13554 MachineMemOperand *MMO = Load->getMemOperand();
13555
13556 if (MemVT.getSizeInBits() < 32) {
13557 // Legalize uniform 16-bit loads to i16 = trunc (zextload i16->i32)
13558 // to match subword load patterns.
13559 // Only do this for loads that can use scalar subword load instructions.
13560 if (!MemVT.isVector() && MemVT.getSizeInBits() == 16 &&
13561 isTypeLegal(MemVT) && Subtarget->hasScalarSubwordLoads() &&
13563 SDValue Chain = Load->getChain();
13564 SDValue BasePtr = Load->getBasePtr();
13565
13566 // Load as i16 and zero-extend to i32 (matches S_LOAD_U16 behavior)
13567 SDValue NewLD = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
13568 BasePtr, MVT::i16, MMO);
13569
13570 // Truncate back to i16
13571 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, NewLD);
13572
13573 // For f16/bf16, bitcast from i16 to the original fp type
13574 SDValue Result = (MemVT == MVT::i16)
13575 ? Trunc
13576 : DAG.getNode(ISD::BITCAST, DL, MemVT, Trunc);
13577
13578 SDValue Ops[] = {Result, NewLD.getValue(1)};
13579 return DAG.getMergeValues(Ops, DL);
13580 }
13581
13582 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
13583 return SDValue();
13584
13585 // FIXME: Copied from PPC
13586 // First, load into 32 bits, then truncate to 1 bit.
13587
13588 SDValue Chain = Load->getChain();
13589 SDValue BasePtr = Load->getBasePtr();
13590
13591 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
13592
13593 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, BasePtr,
13594 RealMemVT, MMO);
13595
13596 if (!MemVT.isVector()) {
13597 SDValue Ops[] = {DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
13598 NewLD.getValue(1)};
13599
13600 return DAG.getMergeValues(Ops, DL);
13601 }
13602
13604 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
13605 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
13606 DAG.getConstant(I, DL, MVT::i32));
13607
13608 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
13609 }
13610
13611 SDValue Ops[] = {DAG.getBuildVector(MemVT, DL, Elts), NewLD.getValue(1)};
13612
13613 return DAG.getMergeValues(Ops, DL);
13614 }
13615
13616 assert(MemVT.isVector() &&
13617 Op.getValueType().getVectorElementType() == MVT::i32 &&
13618 "Custom lowering for non-i32 vectors hasn't been implemented.");
13619
13620 Align Alignment = Load->getAlign();
13621 unsigned AS = Load->getAddressSpace();
13622 if (Subtarget->hasLDSMisalignedBugInWGPMode() &&
13623 AS == AMDGPUAS::FLAT_ADDRESS &&
13624 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
13625 return SplitVectorLoad(Op, DAG);
13626 }
13627
13629 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
13630 // If there is a possibility that flat instruction access scratch memory
13631 // then we need to use the same legalization rules we use for private.
13632 if (AS == AMDGPUAS::FLAT_ADDRESS &&
13633 !Subtarget->hasMultiDwordFlatScratchAddressing())
13634 AS = addressMayBeAccessedAsPrivate(Load->getMemOperand(), *MFI)
13637
13638 unsigned NumElements = MemVT.getVectorNumElements();
13639
13640 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
13642 (AS == AMDGPUAS::GLOBAL_ADDRESS && Load->isSimple() &&
13643 (Load->isInvariant() || isMemOpHasNoClobberedMemOperand(Load)))) {
13644 if ((!Op->isDivergent() || AMDGPU::isUniformMMO(MMO)) &&
13645 Alignment >= Align(4) && NumElements < 32) {
13646 if (MemVT.isPow2VectorType() ||
13647 (Subtarget->hasScalarDwordx3Loads() && NumElements == 3))
13648 return SDValue();
13649 return WidenOrSplitVectorLoad(Op, DAG);
13650 }
13651 // Non-uniform loads will be selected to MUBUF instructions, so they
13652 // have the same legalization requirements as global and private
13653 // loads.
13654 //
13655 }
13656 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
13659 if (NumElements > 4)
13660 return SplitVectorLoad(Op, DAG);
13661 // v3 loads not supported on SI.
13662 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
13663 return WidenOrSplitVectorLoad(Op, DAG);
13664
13665 // v3 and v4 loads are supported for private and global memory.
13666 return SDValue();
13667 }
13668 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
13669 // Depending on the setting of the private_element_size field in the
13670 // resource descriptor, we can only make private accesses up to a certain
13671 // size.
13672 switch (Subtarget->getMaxPrivateElementSize()) {
13673 case 4: {
13674 auto [Op0, Op1] = scalarizeVectorLoad(Load, DAG);
13675 return DAG.getMergeValues({Op0, Op1}, DL);
13676 }
13677 case 8:
13678 if (NumElements > 2)
13679 return SplitVectorLoad(Op, DAG);
13680 return SDValue();
13681 case 16:
13682 // Same as global/flat
13683 if (NumElements > 4)
13684 return SplitVectorLoad(Op, DAG);
13685 // v3 loads not supported on SI.
13686 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
13687 return WidenOrSplitVectorLoad(Op, DAG);
13688
13689 return SDValue();
13690 default:
13691 llvm_unreachable("unsupported private_element_size");
13692 }
13693 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
13694 unsigned Fast = 0;
13695 auto Flags = Load->getMemOperand()->getFlags();
13697 Load->getAlign(), Flags, &Fast) &&
13698 Fast > 1)
13699 return SDValue();
13700
13701 return SplitVectorLoad(Op, DAG);
13702 }
13703
13705 MemVT, *Load->getMemOperand())) {
13706 auto [Op0, Op1] = expandUnalignedLoad(Load, DAG);
13707 return DAG.getMergeValues({Op0, Op1}, DL);
13708 }
13709
13710 return SDValue();
13711}
13712
13713SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13714 EVT VT = Op.getValueType();
13715 if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256 ||
13716 VT.getSizeInBits() == 512)
13717 return splitTernaryVectorOp(Op, DAG);
13718
13719 assert(VT.getSizeInBits() == 64);
13720
13721 SDLoc DL(Op);
13722 SDValue Cond = DAG.getFreeze(Op.getOperand(0));
13723
13724 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
13725 SDValue One = DAG.getConstant(1, DL, MVT::i32);
13726
13727 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
13728 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
13729
13730 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
13731 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
13732
13733 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
13734
13735 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
13736 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
13737
13738 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
13739
13740 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
13741 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
13742}
13743
13744// Catch division cases where we can use shortcuts with rcp and rsq
13745// instructions.
13746SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
13747 SelectionDAG &DAG) const {
13748 SDLoc SL(Op);
13749 SDValue LHS = Op.getOperand(0);
13750 SDValue RHS = Op.getOperand(1);
13751 EVT VT = Op.getValueType();
13752 const SDNodeFlags Flags = Op->getFlags();
13753
13754 bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
13755
13756 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
13757 // Without !fpmath accuracy information, we can't do more because we don't
13758 // know exactly whether rcp is accurate enough to meet !fpmath requirement.
13759 // f16 is always accurate enough
13760 if (!AllowInaccurateRcp && VT != MVT::f16 && VT != MVT::bf16)
13761 return SDValue();
13762
13763 if (CLHS->isOne()) {
13764 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
13765 // the CI documentation has a worst case error of 1 ulp.
13766 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
13767 // use it as long as we aren't trying to use denormals.
13768 //
13769 // v_rcp_f16 and v_rsq_f16 DO support denormals and 0.51ulp.
13770
13771 // 1.0 / sqrt(x) -> rsq(x)
13772
13773 // XXX - Is afn sufficient to do this for f64? The maximum ULP
13774 // error seems really high at 2^29 ULP.
13775 // 1.0 / x -> rcp(x)
13776 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13777 }
13778
13779 // Same as for 1.0, but expand the sign out of the constant.
13780 if (CLHS->isMinusOne()) {
13781 // -1.0 / x -> fneg (rcp x)
13782 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13783 return DAG.getNode(ISD::FNEG, SL, VT, Rcp);
13784 }
13785 }
13786
13787 // For f16 and bf16 require afn or arcp.
13788 // For f32 require afn.
13789 if (!AllowInaccurateRcp &&
13790 ((VT != MVT::f16 && VT != MVT::bf16) || !Flags.hasAllowReciprocal()))
13791 return SDValue();
13792
13793 // Turn into multiply by the reciprocal.
13794 // x / y -> x * (1.0 / y)
13795 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
13796 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
13797}
13798
13799SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
13800 SelectionDAG &DAG) const {
13801 SDLoc SL(Op);
13802 SDValue X = Op.getOperand(0);
13803 SDValue Y = Op.getOperand(1);
13804 EVT VT = Op.getValueType();
13805 const SDNodeFlags Flags = Op->getFlags();
13806
13807 bool AllowInaccurateDiv = Flags.hasApproximateFuncs();
13808 if (!AllowInaccurateDiv)
13809 return SDValue();
13810
13811 const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(X);
13812 bool IsNegRcp = CLHS && CLHS->isMinusOne();
13813
13814 // Pull out the negation so it folds for free into the source modifiers.
13815 if (IsNegRcp)
13816 X = DAG.getConstantFP(1.0, SL, VT);
13817
13818 SDValue NegY = IsNegRcp ? Y : DAG.getNode(ISD::FNEG, SL, VT, Y);
13819 SDValue One = DAG.getConstantFP(1.0, SL, VT);
13820
13821 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
13822 if (IsNegRcp)
13823 R = DAG.getNode(ISD::FNEG, SL, VT, R);
13824
13825 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
13826
13827 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
13828 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
13829 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
13830
13831 // Skip the last 2 correction terms for reciprocal.
13832 if (IsNegRcp || (CLHS && CLHS->isOne()))
13833 return R;
13834
13835 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
13836 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
13837 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
13838}
13839
13840static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
13841 EVT VT, SDValue A, SDValue B, SDValue GlueChain,
13842 SDNodeFlags Flags) {
13843 if (GlueChain->getNumValues() <= 1) {
13844 return DAG.getNode(Opcode, SL, VT, A, B, Flags);
13845 }
13846
13847 assert(GlueChain->getNumValues() == 3);
13848
13849 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
13850 switch (Opcode) {
13851 default:
13852 llvm_unreachable("no chain equivalent for opcode");
13853 case ISD::FMUL:
13854 Opcode = AMDGPUISD::FMUL_W_CHAIN;
13855 break;
13856 }
13857
13858 return DAG.getNode(Opcode, SL, VTList,
13859 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
13860 Flags);
13861}
13862
13863static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
13864 EVT VT, SDValue A, SDValue B, SDValue C,
13865 SDValue GlueChain, SDNodeFlags Flags) {
13866 if (GlueChain->getNumValues() <= 1) {
13867 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
13868 }
13869
13870 assert(GlueChain->getNumValues() == 3);
13871
13872 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
13873 switch (Opcode) {
13874 default:
13875 llvm_unreachable("no chain equivalent for opcode");
13876 case ISD::FMA:
13877 Opcode = AMDGPUISD::FMA_W_CHAIN;
13878 break;
13879 }
13880
13881 return DAG.getNode(Opcode, SL, VTList,
13882 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
13883 Flags);
13884}
13885
13886SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
13887 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
13888 return FastLowered;
13889
13890 SDLoc SL(Op);
13891 EVT VT = Op.getValueType();
13892 SDValue LHS = Op.getOperand(0);
13893 SDValue RHS = Op.getOperand(1);
13894
13895 SDValue LHSExt = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, LHS);
13896 SDValue RHSExt = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, RHS);
13897
13898 if (VT == MVT::bf16) {
13899 SDValue ExtDiv =
13900 DAG.getNode(ISD::FDIV, SL, MVT::f32, LHSExt, RHSExt, Op->getFlags());
13901 return DAG.getNode(ISD::FP_ROUND, SL, MVT::bf16, ExtDiv,
13902 DAG.getTargetConstant(0, SL, MVT::i32));
13903 }
13904
13905 assert(VT == MVT::f16);
13906
13907 // a32.u = opx(V_CVT_F32_F16, a.u); // CVT to F32
13908 // b32.u = opx(V_CVT_F32_F16, b.u); // CVT to F32
13909 // r32.u = opx(V_RCP_F32, b32.u); // rcp = 1 / d
13910 // q32.u = opx(V_MUL_F32, a32.u, r32.u); // q = n * rcp
13911 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
13912 // q32.u = opx(V_MAD_F32, e32.u, r32.u, q32.u); // q = n * rcp
13913 // e32.u = opx(V_MAD_F32, (b32.u^_neg32), q32.u, a32.u); // err = -d * q + n
13914 // tmp.u = opx(V_MUL_F32, e32.u, r32.u);
13915 // tmp.u = opx(V_AND_B32, tmp.u, 0xff800000)
13916 // q32.u = opx(V_ADD_F32, tmp.u, q32.u);
13917 // q16.u = opx(V_CVT_F16_F32, q32.u);
13918 // q16.u = opx(V_DIV_FIXUP_F16, q16.u, b.u, a.u); // q = touchup(q, d, n)
13919
13920 // We will use ISD::FMA on targets that don't support ISD::FMAD.
13921 unsigned FMADOpCode =
13923 SDValue NegRHSExt = DAG.getNode(ISD::FNEG, SL, MVT::f32, RHSExt);
13924 SDValue Rcp =
13925 DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, RHSExt, Op->getFlags());
13926 SDValue Quot =
13927 DAG.getNode(ISD::FMUL, SL, MVT::f32, LHSExt, Rcp, Op->getFlags());
13928 SDValue Err = DAG.getNode(FMADOpCode, SL, MVT::f32, NegRHSExt, Quot, LHSExt,
13929 Op->getFlags());
13930 Quot = DAG.getNode(FMADOpCode, SL, MVT::f32, Err, Rcp, Quot, Op->getFlags());
13931 Err = DAG.getNode(FMADOpCode, SL, MVT::f32, NegRHSExt, Quot, LHSExt,
13932 Op->getFlags());
13933 SDValue Tmp = DAG.getNode(ISD::FMUL, SL, MVT::f32, Err, Rcp, Op->getFlags());
13934 SDValue TmpCast = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Tmp);
13935 TmpCast = DAG.getNode(ISD::AND, SL, MVT::i32, TmpCast,
13936 DAG.getConstant(0xff800000, SL, MVT::i32));
13937 Tmp = DAG.getNode(ISD::BITCAST, SL, MVT::f32, TmpCast);
13938 Quot = DAG.getNode(ISD::FADD, SL, MVT::f32, Tmp, Quot, Op->getFlags());
13939 SDValue RDst = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot,
13940 DAG.getTargetConstant(0, SL, MVT::i32));
13941 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, RDst, RHS, LHS,
13942 Op->getFlags());
13943}
13944
13945// Faster 2.5 ULP division that does not support denormals.
13946SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
13947 SDNodeFlags Flags = Op->getFlags();
13948 SDLoc SL(Op);
13949 SDValue LHS = Op.getOperand(1);
13950 SDValue RHS = Op.getOperand(2);
13951
13952 // TODO: The combiner should probably handle elimination of redundant fabs.
13954 ? RHS
13955 : DAG.getNode(ISD::FABS, SL, MVT::f32, RHS, Flags);
13956
13957 const APFloat K0Val(0x1p+96f);
13958 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
13959
13960 const APFloat K1Val(0x1p-32f);
13961 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
13962
13963 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
13964
13965 EVT SetCCVT =
13966 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
13967
13968 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
13969
13970 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One, Flags);
13971
13972 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3, Flags);
13973
13974 // rcp does not support denormals.
13975 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1, Flags);
13976
13977 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0, Flags);
13978
13979 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul, Flags);
13980}
13981
13982// Returns immediate value for setting the F32 denorm mode when using the
13983// S_DENORM_MODE instruction.
13985 const SIMachineFunctionInfo *Info,
13986 const GCNSubtarget *ST) {
13987 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
13988 uint32_t DPDenormModeDefault = Info->getMode().fpDenormModeDPValue();
13989 uint32_t Mode = SPDenormMode | (DPDenormModeDefault << 2);
13990 return DAG.getTargetConstant(Mode, SDLoc(), MVT::i32);
13991}
13992
13993SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
13994 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
13995 return FastLowered;
13996
13997 // The selection matcher assumes anything with a chain selecting to a
13998 // mayRaiseFPException machine instruction. Since we're introducing a chain
13999 // here, we need to explicitly report nofpexcept for the regular fdiv
14000 // lowering.
14001 SDNodeFlags Flags = Op->getFlags();
14002 Flags.setNoFPExcept(true);
14003
14004 SDLoc SL(Op);
14005 SDValue LHS = Op.getOperand(0);
14006 SDValue RHS = Op.getOperand(1);
14007
14008 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
14009
14010 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
14011
14012 SDValue DenominatorScaled =
14013 DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, {RHS, RHS, LHS}, Flags);
14014 SDValue NumeratorScaled =
14015 DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, {LHS, RHS, LHS}, Flags);
14016
14017 // Denominator is scaled to not be denormal, so using rcp is ok.
14018 SDValue ApproxRcp =
14019 DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled, Flags);
14020 SDValue NegDivScale0 =
14021 DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled, Flags);
14022
14023 using namespace AMDGPU::Hwreg;
14024 const unsigned Denorm32Reg = HwregEncoding::encode(ID_MODE, 4, 2);
14025 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
14026
14027 const MachineFunction &MF = DAG.getMachineFunction();
14028 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
14029 const DenormalMode DenormMode = Info->getMode().FP32Denormals;
14030
14031 const bool PreservesDenormals = DenormMode == DenormalMode::getIEEE();
14032 const bool HasDynamicDenormals =
14033 (DenormMode.Input == DenormalMode::Dynamic) ||
14034 (DenormMode.Output == DenormalMode::Dynamic);
14035
14036 SDValue SavedDenormMode;
14037
14038 if (!PreservesDenormals) {
14039 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
14040 // lowering. The chain dependence is insufficient, and we need glue. We do
14041 // not need the glue variants in a strictfp function.
14042
14043 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
14044
14045 SDValue Glue = DAG.getEntryNode();
14046 if (HasDynamicDenormals) {
14047 SDNode *GetReg = DAG.getMachineNode(AMDGPU::S_GETREG_B32, SL,
14048 DAG.getVTList(MVT::i32, MVT::Glue),
14049 {BitField, Glue});
14050 SavedDenormMode = SDValue(GetReg, 0);
14051
14052 Glue = DAG.getMergeValues(
14053 {DAG.getEntryNode(), SDValue(GetReg, 0), SDValue(GetReg, 1)}, SL);
14054 }
14055
14056 SDNode *EnableDenorm;
14057 if (Subtarget->hasDenormModeInst()) {
14058 const SDValue EnableDenormValue =
14059 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, Info, Subtarget);
14060
14061 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, Glue,
14062 EnableDenormValue)
14063 .getNode();
14064 } else {
14065 const SDValue EnableDenormValue =
14066 DAG.getConstant(FP_DENORM_FLUSH_NONE, SL, MVT::i32);
14067 EnableDenorm = DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
14068 {EnableDenormValue, BitField, Glue});
14069 }
14070
14071 SDValue Ops[3] = {NegDivScale0, SDValue(EnableDenorm, 0),
14072 SDValue(EnableDenorm, 1)};
14073
14074 NegDivScale0 = DAG.getMergeValues(Ops, SL);
14075 }
14076
14077 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
14078 ApproxRcp, One, NegDivScale0, Flags);
14079
14080 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
14081 ApproxRcp, Fma0, Flags);
14082
14083 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1,
14084 Fma1, Flags);
14085
14086 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
14087 NumeratorScaled, Mul, Flags);
14088
14089 SDValue Fma3 =
14090 getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2, Flags);
14091
14092 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
14093 NumeratorScaled, Fma3, Flags);
14094
14095 if (!PreservesDenormals) {
14096 SDNode *DisableDenorm;
14097 if (!HasDynamicDenormals && Subtarget->hasDenormModeInst()) {
14098 const SDValue DisableDenormValue = getSPDenormModeValue(
14099 FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, Info, Subtarget);
14100
14101 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
14102 DisableDenorm =
14103 DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
14104 Fma4.getValue(1), DisableDenormValue, Fma4.getValue(2))
14105 .getNode();
14106 } else {
14107 assert(HasDynamicDenormals == (bool)SavedDenormMode);
14108 const SDValue DisableDenormValue =
14109 HasDynamicDenormals
14110 ? SavedDenormMode
14111 : DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
14112
14113 DisableDenorm = DAG.getMachineNode(
14114 AMDGPU::S_SETREG_B32, SL, MVT::Other,
14115 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
14116 }
14117
14118 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
14119 SDValue(DisableDenorm, 0), DAG.getRoot());
14120 DAG.setRoot(OutputChain);
14121 }
14122
14123 SDValue Scale = NumeratorScaled.getValue(1);
14124 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
14125 {Fma4, Fma1, Fma3, Scale}, Flags);
14126
14127 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
14128}
14129
14130SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
14131 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
14132 return FastLowered;
14133
14134 SDLoc SL(Op);
14135 SDValue X = Op.getOperand(0);
14136 SDValue Y = Op.getOperand(1);
14137
14138 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
14139
14140 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
14141
14142 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
14143
14144 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
14145
14146 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
14147
14148 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
14149
14150 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
14151
14152 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
14153
14154 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
14155
14156 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
14157 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
14158
14159 SDValue Fma4 =
14160 DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Mul, DivScale1);
14161
14162 SDValue Scale;
14163
14164 if (!Subtarget->hasUsableDivScaleConditionOutput()) {
14165 // Workaround a hardware bug on SI where the condition output from div_scale
14166 // is not usable.
14167
14168 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
14169
14170 // Figure out if the scale to use for div_fmas.
14171 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
14172 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
14173 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
14174 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
14175
14176 SDValue NumHi =
14177 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
14178 SDValue DenHi =
14179 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
14180
14181 SDValue Scale0Hi =
14182 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
14183 SDValue Scale1Hi =
14184 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
14185
14186 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
14187 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
14188 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
14189 } else {
14190 Scale = DivScale1.getValue(1);
14191 }
14192
14193 SDValue Fmas =
14194 DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, Fma4, Fma3, Mul, Scale);
14195
14196 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
14197}
14198
14199SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
14200 EVT VT = Op.getValueType();
14201
14202 if (VT == MVT::f32)
14203 return LowerFDIV32(Op, DAG);
14204
14205 if (VT == MVT::f64)
14206 return LowerFDIV64(Op, DAG);
14207
14208 if (VT == MVT::f16 || VT == MVT::bf16)
14209 return LowerFDIV16(Op, DAG);
14210
14211 llvm_unreachable("Unexpected type for fdiv");
14212}
14213
14214SDValue SITargetLowering::LowerFFREXP(SDValue Op, SelectionDAG &DAG) const {
14215 SDLoc dl(Op);
14216 SDValue Val = Op.getOperand(0);
14217 EVT VT = Val.getValueType();
14218 EVT ResultExpVT = Op->getValueType(1);
14219 EVT InstrExpVT = VT == MVT::f16 ? MVT::i16 : MVT::i32;
14220
14221 SDValue Mant = DAG.getNode(
14223 DAG.getTargetConstant(Intrinsic::amdgcn_frexp_mant, dl, MVT::i32), Val);
14224
14225 SDValue Exp = DAG.getNode(
14226 ISD::INTRINSIC_WO_CHAIN, dl, InstrExpVT,
14227 DAG.getTargetConstant(Intrinsic::amdgcn_frexp_exp, dl, MVT::i32), Val);
14228
14229 if (Subtarget->hasFractBug()) {
14230 SDValue Fabs = DAG.getNode(ISD::FABS, dl, VT, Val);
14231 SDValue Inf =
14233
14234 SDValue IsFinite = DAG.getSetCC(dl, MVT::i1, Fabs, Inf, ISD::SETOLT);
14235 SDValue Zero = DAG.getConstant(0, dl, InstrExpVT);
14236 Exp = DAG.getNode(ISD::SELECT, dl, InstrExpVT, IsFinite, Exp, Zero);
14237 Mant = DAG.getNode(ISD::SELECT, dl, VT, IsFinite, Mant, Val);
14238 }
14239
14240 SDValue CastExp = DAG.getSExtOrTrunc(Exp, dl, ResultExpVT);
14241 return DAG.getMergeValues({Mant, CastExp}, dl);
14242}
14243
14244SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
14245 SDLoc DL(Op);
14246 StoreSDNode *Store = cast<StoreSDNode>(Op);
14247 assert(!Store->isTruncatingStore() && "Unexpected custom truncating store!");
14248 EVT VT = Store->getMemoryVT();
14249
14250 if (VT == MVT::i1) {
14251 return DAG.getTruncStore(
14252 Store->getChain(), DL,
14253 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
14254 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
14255 }
14256
14257 assert(VT.isVector() &&
14258 Store->getValue().getValueType().getScalarType() == MVT::i32);
14259
14260 unsigned AS = Store->getAddressSpace();
14261 if (Subtarget->hasLDSMisalignedBugInWGPMode() &&
14262 AS == AMDGPUAS::FLAT_ADDRESS &&
14263 Store->getAlign().value() < VT.getStoreSize() &&
14264 VT.getSizeInBits() > 32) {
14265 return SplitVectorStore(Op, DAG);
14266 }
14267
14269 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
14270 // If there is a possibility that flat instruction access scratch memory
14271 // then we need to use the same legalization rules we use for private.
14272 if (AS == AMDGPUAS::FLAT_ADDRESS &&
14273 !Subtarget->hasMultiDwordFlatScratchAddressing())
14274 AS = addressMayBeAccessedAsPrivate(Store->getMemOperand(), *MFI)
14277
14278 unsigned NumElements = VT.getVectorNumElements();
14280 if (NumElements > 4)
14281 return SplitVectorStore(Op, DAG);
14282 // v3 stores not supported on SI.
14283 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
14284 return SplitVectorStore(Op, DAG);
14285
14287 VT, *Store->getMemOperand()))
14288 return expandUnalignedStore(Store, DAG);
14289
14290 return SDValue();
14291 }
14292 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
14293 switch (Subtarget->getMaxPrivateElementSize()) {
14294 case 4:
14295 return scalarizeVectorStore(Store, DAG);
14296 case 8:
14297 if (NumElements > 2)
14298 return SplitVectorStore(Op, DAG);
14299 return SDValue();
14300 case 16:
14301 if (NumElements > 4 ||
14302 (NumElements == 3 && !Subtarget->hasFlatScratchEnabled()))
14303 return SplitVectorStore(Op, DAG);
14304 return SDValue();
14305 default:
14306 llvm_unreachable("unsupported private_element_size");
14307 }
14308 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
14309 unsigned Fast = 0;
14310 auto Flags = Store->getMemOperand()->getFlags();
14312 Store->getAlign(), Flags, &Fast) &&
14313 Fast > 1)
14314 return SDValue();
14315
14316 return SplitVectorStore(Op, DAG);
14317 }
14318
14319 // Probably an invalid store. If so we'll end up emitting a selection error.
14320 return SDValue();
14321}
14322
14323// Avoid the full correct expansion for f32 sqrt when promoting from f16.
14324SDValue SITargetLowering::lowerFSQRTF16(SDValue Op, SelectionDAG &DAG) const {
14325 SDLoc SL(Op);
14326 assert(!Subtarget->has16BitInsts());
14327 SDNodeFlags Flags = Op->getFlags();
14328 SDValue Ext =
14329 DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op.getOperand(0), Flags);
14330
14331 SDValue SqrtID = DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, SL, MVT::i32);
14332 SDValue Sqrt =
14333 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::f32, SqrtID, Ext, Flags);
14334
14335 return DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Sqrt,
14336 DAG.getTargetConstant(0, SL, MVT::i32), Flags);
14337}
14338
14339SDValue SITargetLowering::lowerFSQRTF32(SDValue Op, SelectionDAG &DAG) const {
14340 SDLoc DL(Op);
14341 SDNodeFlags Flags = Op->getFlags();
14342 MVT VT = Op.getValueType().getSimpleVT();
14343 const SDValue X = Op.getOperand(0);
14344
14345 if (allowApproxFunc(DAG, Flags)) {
14346 // Instruction is 1ulp but ignores denormals.
14347 return DAG.getNode(
14349 DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32), X, Flags);
14350 }
14351
14352 SDValue ScaleThreshold = DAG.getConstantFP(0x1.0p-96f, DL, VT);
14353 SDValue NeedScale = DAG.getSetCC(DL, MVT::i1, X, ScaleThreshold, ISD::SETOLT);
14354
14355 SDValue ScaleUpFactor = DAG.getConstantFP(0x1.0p+32f, DL, VT);
14356
14357 SDValue ScaledX = DAG.getNode(ISD::FMUL, DL, VT, X, ScaleUpFactor, Flags);
14358
14359 SDValue SqrtX =
14360 DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledX, X, Flags);
14361
14362 SDValue SqrtS;
14363 if (needsDenormHandlingF32(DAG, X, Flags)) {
14364 SDValue SqrtID =
14365 DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32);
14366 SqrtS = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, SqrtID, SqrtX, Flags);
14367
14368 SDValue SqrtSAsInt = DAG.getNode(ISD::BITCAST, DL, MVT::i32, SqrtS);
14369 SDValue SqrtSNextDownInt =
14370 DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
14371 DAG.getAllOnesConstant(DL, MVT::i32));
14372 SDValue SqrtSNextDown = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextDownInt);
14373
14374 SDValue NegSqrtSNextDown =
14375 DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextDown, Flags);
14376
14377 SDValue SqrtVP =
14378 DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextDown, SqrtS, SqrtX, Flags);
14379
14380 SDValue SqrtSNextUpInt = DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
14381 DAG.getConstant(1, DL, MVT::i32));
14382 SDValue SqrtSNextUp = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextUpInt);
14383
14384 SDValue NegSqrtSNextUp = DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextUp, Flags);
14385 SDValue SqrtVS =
14386 DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextUp, SqrtS, SqrtX, Flags);
14387
14388 SDValue Zero = DAG.getConstantFP(0.0f, DL, VT);
14389 SDValue SqrtVPLE0 = DAG.getSetCC(DL, MVT::i1, SqrtVP, Zero, ISD::SETOLE);
14390
14391 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPLE0, SqrtSNextDown, SqrtS,
14392 Flags);
14393
14394 SDValue SqrtVPVSGT0 = DAG.getSetCC(DL, MVT::i1, SqrtVS, Zero, ISD::SETOGT);
14395 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPVSGT0, SqrtSNextUp, SqrtS,
14396 Flags);
14397 } else {
14398 SDValue SqrtR = DAG.getNode(AMDGPUISD::RSQ, DL, VT, SqrtX, Flags);
14399
14400 SqrtS = DAG.getNode(ISD::FMUL, DL, VT, SqrtX, SqrtR, Flags);
14401
14402 SDValue Half = DAG.getConstantFP(0.5f, DL, VT);
14403 SDValue SqrtH = DAG.getNode(ISD::FMUL, DL, VT, SqrtR, Half, Flags);
14404 SDValue NegSqrtH = DAG.getNode(ISD::FNEG, DL, VT, SqrtH, Flags);
14405
14406 SDValue SqrtE = DAG.getNode(ISD::FMA, DL, VT, NegSqrtH, SqrtS, Half, Flags);
14407 SqrtH = DAG.getNode(ISD::FMA, DL, VT, SqrtH, SqrtE, SqrtH, Flags);
14408 SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtS, SqrtE, SqrtS, Flags);
14409
14410 SDValue NegSqrtS = DAG.getNode(ISD::FNEG, DL, VT, SqrtS, Flags);
14411 SDValue SqrtD =
14412 DAG.getNode(ISD::FMA, DL, VT, NegSqrtS, SqrtS, SqrtX, Flags);
14413 SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtD, SqrtH, SqrtS, Flags);
14414 }
14415
14416 SDValue ScaleDownFactor = DAG.getConstantFP(0x1.0p-16f, DL, VT);
14417
14418 SDValue ScaledDown =
14419 DAG.getNode(ISD::FMUL, DL, VT, SqrtS, ScaleDownFactor, Flags);
14420
14421 SqrtS = DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledDown, SqrtS, Flags);
14422 SDValue IsZeroOrInf =
14423 DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
14424 DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
14425
14426 return DAG.getNode(ISD::SELECT, DL, VT, IsZeroOrInf, SqrtX, SqrtS, Flags);
14427}
14428
14429SDValue SITargetLowering::lowerFSQRTF64(SDValue Op, SelectionDAG &DAG) const {
14430 // For double type, the SQRT and RSQ instructions don't have required
14431 // precision, we apply Goldschmidt's algorithm to improve the result:
14432 //
14433 // y0 = rsq(x)
14434 // g0 = x * y0
14435 // h0 = 0.5 * y0
14436 //
14437 // r0 = 0.5 - h0 * g0
14438 // g1 = g0 * r0 + g0
14439 // h1 = h0 * r0 + h0
14440 //
14441 // r1 = 0.5 - h1 * g1 => d0 = x - g1 * g1
14442 // g2 = g1 * r1 + g1 g2 = d0 * h1 + g1
14443 // h2 = h1 * r1 + h1
14444 //
14445 // r2 = 0.5 - h2 * g2 => d1 = x - g2 * g2
14446 // g3 = g2 * r2 + g2 g3 = d1 * h1 + g2
14447 //
14448 // sqrt(x) = g3
14449
14450 SDNodeFlags Flags = Op->getFlags();
14451
14452 SDLoc DL(Op);
14453
14454 SDValue X = Op.getOperand(0);
14455 SDValue ZeroInt = DAG.getConstant(0, DL, MVT::i32);
14456
14457 SDValue SqrtX = X;
14458 SDValue Scaling;
14459 if (!Flags.hasApproximateFuncs()) {
14460 SDValue ScaleConstant = DAG.getConstantFP(0x1.0p-767, DL, MVT::f64);
14461 Scaling = DAG.getSetCC(DL, MVT::i1, X, ScaleConstant, ISD::SETOLT);
14462
14463 // Scale up input if it is too small.
14464 SDValue ScaleUpFactor = DAG.getConstant(256, DL, MVT::i32);
14465 SDValue ScaleUp =
14466 DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling, ScaleUpFactor, ZeroInt);
14467 SqrtX = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, X, ScaleUp, Flags);
14468 }
14469
14470 SDValue SqrtY = DAG.getNode(AMDGPUISD::RSQ, DL, MVT::f64, SqrtX);
14471
14472 SDValue SqrtS0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtX, SqrtY);
14473
14474 SDValue Half = DAG.getConstantFP(0.5, DL, MVT::f64);
14475 SDValue SqrtH0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtY, Half);
14476
14477 SDValue NegSqrtH0 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtH0);
14478 SDValue SqrtR0 = DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtH0, SqrtS0, Half);
14479
14480 SDValue SqrtH1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtH0, SqrtR0, SqrtH0);
14481
14482 SDValue SqrtS1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtS0, SqrtR0, SqrtS0);
14483
14484 SDValue NegSqrtS1 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS1);
14485 SDValue SqrtD0 =
14486 DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS1, SqrtS1, SqrtX);
14487
14488 SDValue SqrtS2 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD0, SqrtH1, SqrtS1);
14489
14490 SDValue SqrtRet = SqrtS2;
14491 if (!Flags.hasApproximateFuncs()) {
14492 SDValue NegSqrtS2 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS2);
14493 SDValue SqrtD1 =
14494 DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS2, SqrtS2, SqrtX);
14495
14496 SqrtRet = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD1, SqrtH1, SqrtS2);
14497
14498 SDValue ScaleDownFactor = DAG.getSignedConstant(-128, DL, MVT::i32);
14499 SDValue ScaleDown = DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling,
14500 ScaleDownFactor, ZeroInt);
14501 SqrtRet = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, SqrtRet, ScaleDown, Flags);
14502 }
14503
14504 // TODO: Check for DAZ and expand to subnormals
14505
14506 SDValue IsZeroOrInf;
14507 if (Flags.hasNoInfs()) {
14508 SDValue Zero = DAG.getConstantFP(0.0, DL, MVT::f64);
14509 IsZeroOrInf = DAG.getSetCC(DL, MVT::i1, SqrtX, Zero, ISD::SETOEQ);
14510 } else {
14511 IsZeroOrInf =
14512 DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
14513 DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
14514 }
14515
14516 // If x is +INF, +0, or -0, use its original value
14517 return DAG.getNode(ISD::SELECT, DL, MVT::f64, IsZeroOrInf, SqrtX, SqrtRet,
14518 Flags);
14519}
14520
14521SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
14522 SDLoc DL(Op);
14523 EVT VT = Op.getValueType();
14524 SDValue Arg = Op.getOperand(0);
14525 SDValue TrigVal;
14526
14527 // Propagate fast-math flags so that the multiply we introduce can be folded
14528 // if Arg is already the result of a multiply by constant.
14529 auto Flags = Op->getFlags();
14530
14531 // AMDGPUISD nodes of vector type must be unrolled here since
14532 // they will not be expanded elsewhere.
14533 auto UnrollIfVec = [&DAG](SDValue V) -> SDValue {
14534 if (!V.getValueType().isVector())
14535 return V;
14536
14537 return DAG.UnrollVectorOp(cast<SDNode>(V));
14538 };
14539
14540 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
14541
14542 if (Subtarget->hasTrigReducedRange()) {
14543 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
14544 TrigVal = UnrollIfVec(DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags));
14545 } else {
14546 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
14547 }
14548
14549 switch (Op.getOpcode()) {
14550 case ISD::FCOS:
14551 TrigVal = DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
14552 break;
14553 case ISD::FSIN:
14554 TrigVal = DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
14555 break;
14556 default:
14557 llvm_unreachable("Wrong trig opcode");
14558 }
14559
14560 return UnrollIfVec(TrigVal);
14561}
14562
14563SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
14564 SelectionDAG &DAG) const {
14565 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
14566 assert(AtomicNode->isCompareAndSwap());
14567 unsigned AS = AtomicNode->getAddressSpace();
14568
14569 // No custom lowering required for local address space
14571 return Op;
14572
14573 // Non-local address space requires custom lowering for atomic compare
14574 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
14575 SDLoc DL(Op);
14576 SDValue ChainIn = Op.getOperand(0);
14577 SDValue Addr = Op.getOperand(1);
14578 SDValue Old = Op.getOperand(2);
14579 SDValue New = Op.getOperand(3);
14580 EVT VT = Op.getValueType();
14581 MVT SimpleVT = VT.getSimpleVT();
14582 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
14583
14584 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
14585 SDValue Ops[] = {ChainIn, Addr, NewOld};
14586
14587 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL,
14588 Op->getVTList(), Ops, VT,
14589 AtomicNode->getMemOperand());
14590}
14591
14592//===----------------------------------------------------------------------===//
14593// Custom DAG optimizations
14594//===----------------------------------------------------------------------===//
14595
14596SDValue
14597SITargetLowering::performUCharToFloatCombine(SDNode *N,
14598 DAGCombinerInfo &DCI) const {
14599 EVT VT = N->getValueType(0);
14600 EVT ScalarVT = VT.getScalarType();
14601 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
14602 return SDValue();
14603
14604 SelectionDAG &DAG = DCI.DAG;
14605 SDLoc DL(N);
14606
14607 SDValue Src = N->getOperand(0);
14608 EVT SrcVT = Src.getValueType();
14609
14610 // TODO: We could try to match extracting the higher bytes, which would be
14611 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
14612 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
14613 // about in practice.
14614 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
14615 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
14616 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
14617 DCI.AddToWorklist(Cvt.getNode());
14618
14619 // For the f16 case, fold to a cast to f32 and then cast back to f16.
14620 if (ScalarVT != MVT::f32) {
14621 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
14622 DAG.getTargetConstant(0, DL, MVT::i32));
14623 }
14624 return Cvt;
14625 }
14626 }
14627
14628 return SDValue();
14629}
14630
14631SDValue SITargetLowering::performFCopySignCombine(SDNode *N,
14632 DAGCombinerInfo &DCI) const {
14633 SDValue MagnitudeOp = N->getOperand(0);
14634 SDValue SignOp = N->getOperand(1);
14635
14636 // The generic combine for fcopysign + fp cast is too conservative with
14637 // vectors, and also gets confused by the splitting we will perform here, so
14638 // peek through FP casts.
14639 if (SignOp.getOpcode() == ISD::FP_EXTEND ||
14640 SignOp.getOpcode() == ISD::FP_ROUND)
14641 SignOp = SignOp.getOperand(0);
14642
14643 SelectionDAG &DAG = DCI.DAG;
14644 SDLoc DL(N);
14645 EVT SignVT = SignOp.getValueType();
14646
14647 // f64 fcopysign is really an f32 copysign on the high bits, so replace the
14648 // lower half with a copy.
14649 // fcopysign f64:x, _:y -> x.lo32, (fcopysign (f32 x.hi32), _:y)
14650 EVT MagVT = MagnitudeOp.getValueType();
14651
14652 unsigned NumElts = MagVT.isVector() ? MagVT.getVectorNumElements() : 1;
14653
14654 if (MagVT.getScalarType() == MVT::f64) {
14655 EVT F32VT = MagVT.isVector()
14656 ? EVT::getVectorVT(*DAG.getContext(), MVT::f32, 2 * NumElts)
14657 : MVT::v2f32;
14658
14659 SDValue MagAsVector = DAG.getNode(ISD::BITCAST, DL, F32VT, MagnitudeOp);
14660
14662 for (unsigned I = 0; I != NumElts; ++I) {
14663 SDValue MagLo =
14664 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
14665 DAG.getConstant(2 * I, DL, MVT::i32));
14666 SDValue MagHi =
14667 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
14668 DAG.getConstant(2 * I + 1, DL, MVT::i32));
14669
14670 SDValue SignOpElt =
14671 MagVT.isVector()
14673 SignOp, DAG.getConstant(I, DL, MVT::i32))
14674 : SignOp;
14675
14676 SDValue HiOp =
14677 DAG.getNode(ISD::FCOPYSIGN, DL, MVT::f32, MagHi, SignOpElt);
14678
14679 SDValue Vector =
14680 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32, MagLo, HiOp);
14681
14682 SDValue NewElt = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Vector);
14683 NewElts.push_back(NewElt);
14684 }
14685
14686 if (NewElts.size() == 1)
14687 return NewElts[0];
14688
14689 return DAG.getNode(ISD::BUILD_VECTOR, DL, MagVT, NewElts);
14690 }
14691
14692 if (SignVT.getScalarType() != MVT::f64)
14693 return SDValue();
14694
14695 // Reduce width of sign operand, we only need the highest bit.
14696 //
14697 // fcopysign f64:x, f64:y ->
14698 // fcopysign f64:x, (extract_vector_elt (bitcast f64:y to v2f32), 1)
14699 // TODO: In some cases it might make sense to go all the way to f16.
14700
14701 EVT F32VT = MagVT.isVector()
14702 ? EVT::getVectorVT(*DAG.getContext(), MVT::f32, 2 * NumElts)
14703 : MVT::v2f32;
14704
14705 SDValue SignAsVector = DAG.getNode(ISD::BITCAST, DL, F32VT, SignOp);
14706
14707 SmallVector<SDValue, 8> F32Signs;
14708 for (unsigned I = 0; I != NumElts; ++I) {
14709 // Take sign from odd elements of cast vector
14710 SDValue SignAsF32 =
14711 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, SignAsVector,
14712 DAG.getConstant(2 * I + 1, DL, MVT::i32));
14713 F32Signs.push_back(SignAsF32);
14714 }
14715
14716 SDValue NewSign =
14717 NumElts == 1
14718 ? F32Signs.back()
14720 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumElts),
14721 F32Signs);
14722
14723 return DAG.getNode(ISD::FCOPYSIGN, DL, N->getValueType(0), N->getOperand(0),
14724 NewSign);
14725}
14726
14727// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
14728// (shl (or x, c1), c2) -> add (shl x, c2), (shl c1, c2) iff x and c1 share no
14729// bits
14730
14731// This is a variant of
14732// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
14733//
14734// The normal DAG combiner will do this, but only if the add has one use since
14735// that would increase the number of instructions.
14736//
14737// This prevents us from seeing a constant offset that can be folded into a
14738// memory instruction's addressing mode. If we know the resulting add offset of
14739// a pointer can be folded into an addressing offset, we can replace the pointer
14740// operand with the add of new constant offset. This eliminates one of the uses,
14741// and may allow the remaining use to also be simplified.
14742//
14743SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, unsigned AddrSpace,
14744 EVT MemVT,
14745 DAGCombinerInfo &DCI) const {
14746 SDValue N0 = N->getOperand(0);
14747 SDValue N1 = N->getOperand(1);
14748
14749 // We only do this to handle cases where it's profitable when there are
14750 // multiple uses of the add, so defer to the standard combine.
14751 if ((!N0->isAnyAdd() && N0.getOpcode() != ISD::OR) || N0->hasOneUse())
14752 return SDValue();
14753
14754 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
14755 if (!CN1)
14756 return SDValue();
14757
14758 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14759 if (!CAdd)
14760 return SDValue();
14761
14762 SelectionDAG &DAG = DCI.DAG;
14763
14764 if (N0->getOpcode() == ISD::OR &&
14765 !DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1)))
14766 return SDValue();
14767
14768 // If the resulting offset is too large, we can't fold it into the
14769 // addressing mode offset.
14770 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
14771 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
14772
14773 AddrMode AM;
14774 AM.HasBaseReg = true;
14775 AM.BaseOffs = Offset.getSExtValue();
14776 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
14777 return SDValue();
14778
14779 SDLoc SL(N);
14780 EVT VT = N->getValueType(0);
14781
14782 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
14783 SDValue COffset = DAG.getConstant(Offset, SL, VT);
14784
14785 SDNodeFlags Flags;
14786 Flags.setNoUnsignedWrap(
14787 N->getFlags().hasNoUnsignedWrap() &&
14788 (N0.getOpcode() == ISD::OR || N0->getFlags().hasNoUnsignedWrap()));
14789
14790 // Use ISD::ADD even if the original operation was ISD::PTRADD, since we can't
14791 // be sure that the new left operand is a proper base pointer.
14792 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
14793}
14794
14795/// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
14796/// by the chain and intrinsic ID. Theoretically we would also need to check the
14797/// specific intrinsic, but they all place the pointer operand first.
14798static unsigned getBasePtrIndex(const MemSDNode *N) {
14799 switch (N->getOpcode()) {
14800 case ISD::STORE:
14803 return 2;
14804 default:
14805 return 1;
14806 }
14807}
14808
14809SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
14810 DAGCombinerInfo &DCI) const {
14811 SelectionDAG &DAG = DCI.DAG;
14812
14813 unsigned PtrIdx = getBasePtrIndex(N);
14814 SDValue Ptr = N->getOperand(PtrIdx);
14815
14816 // TODO: We could also do this for multiplies.
14817 if (Ptr.getOpcode() == ISD::SHL) {
14818 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
14819 N->getMemoryVT(), DCI);
14820 if (NewPtr) {
14821 SmallVector<SDValue, 8> NewOps(N->ops());
14822
14823 NewOps[PtrIdx] = NewPtr;
14824 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
14825 }
14826 }
14827
14828 return SDValue();
14829}
14830
14831static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
14832 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
14833 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
14834 (Opc == ISD::XOR && Val == 0);
14835}
14836
14837// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
14838// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
14839// integer combine opportunities since most 64-bit operations are decomposed
14840// this way. TODO: We won't want this for SALU especially if it is an inline
14841// immediate.
14842SDValue SITargetLowering::splitBinaryBitConstantOp(
14843 DAGCombinerInfo &DCI, const SDLoc &SL, unsigned Opc, SDValue LHS,
14844 const ConstantSDNode *CRHS) const {
14845 uint64_t Val = CRHS->getZExtValue();
14846 uint32_t ValLo = Lo_32(Val);
14847 uint32_t ValHi = Hi_32(Val);
14848 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14849
14850 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
14852 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
14853 // We have 64-bit scalar and/or/xor, but do not have vector forms.
14854 if (Subtarget->has64BitLiterals() && CRHS->hasOneUse() &&
14855 !CRHS->user_begin()->isDivergent())
14856 return SDValue();
14857
14858 // If we need to materialize a 64-bit immediate, it will be split up later
14859 // anyway. Avoid creating the harder to understand 64-bit immediate
14860 // materialization.
14861 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
14862 }
14863
14864 return SDValue();
14865}
14866
14868 if (V.getValueType() != MVT::i1)
14869 return false;
14870 switch (V.getOpcode()) {
14871 default:
14872 break;
14873 case ISD::SETCC:
14874 case ISD::IS_FPCLASS:
14875 case AMDGPUISD::FP_CLASS:
14876 return true;
14877 case ISD::AND:
14878 case ISD::OR:
14879 case ISD::XOR:
14880 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
14881 case ISD::SADDO:
14882 case ISD::UADDO:
14883 case ISD::SSUBO:
14884 case ISD::USUBO:
14885 case ISD::SMULO:
14886 case ISD::UMULO:
14887 return V.getResNo() == 1;
14889 unsigned IntrinsicID = V.getConstantOperandVal(0);
14890 switch (IntrinsicID) {
14891 case Intrinsic::amdgcn_is_shared:
14892 case Intrinsic::amdgcn_is_private:
14893 return true;
14894 default:
14895 return false;
14896 }
14897
14898 return false;
14899 }
14900 }
14901 return false;
14902}
14903
14905 return (V.getOpcode() == ISD::SIGN_EXTEND ||
14906 V.getOpcode() == ISD::ANY_EXTEND) &&
14907 isBoolSGPR(V.getOperand(0));
14908}
14909
14910// If a constant has all zeroes or all ones within each byte return it.
14911// Otherwise return 0.
14913 // 0xff for any zero byte in the mask
14914 uint32_t ZeroByteMask = 0;
14915 if (!(C & 0x000000ff))
14916 ZeroByteMask |= 0x000000ff;
14917 if (!(C & 0x0000ff00))
14918 ZeroByteMask |= 0x0000ff00;
14919 if (!(C & 0x00ff0000))
14920 ZeroByteMask |= 0x00ff0000;
14921 if (!(C & 0xff000000))
14922 ZeroByteMask |= 0xff000000;
14923 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
14924 if ((NonZeroByteMask & C) != NonZeroByteMask)
14925 return 0; // Partial bytes selected.
14926 return C;
14927}
14928
14929// Check if a node selects whole bytes from its operand 0 starting at a byte
14930// boundary while masking the rest. Returns select mask as in the v_perm_b32
14931// or -1 if not succeeded.
14932// Note byte select encoding:
14933// value 0-3 selects corresponding source byte;
14934// value 0xc selects zero;
14935// value 0xff selects 0xff.
14937 assert(V.getValueSizeInBits() == 32);
14938
14939 if (V.getNumOperands() != 2)
14940 return ~0;
14941
14942 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
14943 if (!N1)
14944 return ~0;
14945
14946 uint32_t C = N1->getZExtValue();
14947
14948 switch (V.getOpcode()) {
14949 default:
14950 break;
14951 case ISD::AND:
14952 if (uint32_t ConstMask = getConstantPermuteMask(C))
14953 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
14954 break;
14955
14956 case ISD::OR:
14957 if (uint32_t ConstMask = getConstantPermuteMask(C))
14958 return (0x03020100 & ~ConstMask) | ConstMask;
14959 break;
14960
14961 case ISD::SHL:
14962 if (C % 8)
14963 return ~0;
14964
14965 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
14966
14967 case ISD::SRL:
14968 if (C % 8)
14969 return ~0;
14970
14971 return uint32_t(0x0c0c0c0c03020100ull >> C);
14972 }
14973
14974 return ~0;
14975}
14976
14977SDValue SITargetLowering::performAndCombine(SDNode *N,
14978 DAGCombinerInfo &DCI) const {
14979 if (DCI.isBeforeLegalize())
14980 return SDValue();
14981
14982 SelectionDAG &DAG = DCI.DAG;
14983 EVT VT = N->getValueType(0);
14984 SDValue LHS = N->getOperand(0);
14985 SDValue RHS = N->getOperand(1);
14986
14987 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
14988 if (VT == MVT::i64 && CRHS) {
14989 if (SDValue Split =
14990 splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
14991 return Split;
14992 }
14993
14994 if (CRHS && VT == MVT::i32) {
14995 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
14996 // nb = number of trailing zeroes in mask
14997 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
14998 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
14999 uint64_t Mask = CRHS->getZExtValue();
15000 unsigned Bits = llvm::popcount(Mask);
15001 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
15002 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
15003 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
15004 unsigned Shift = CShift->getZExtValue();
15005 unsigned NB = CRHS->getAPIntValue().countr_zero();
15006 unsigned Offset = NB + Shift;
15007 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
15008 SDLoc SL(N);
15009 SDValue BFE =
15010 DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, LHS->getOperand(0),
15011 DAG.getConstant(Offset, SL, MVT::i32),
15012 DAG.getConstant(Bits, SL, MVT::i32));
15013 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
15014 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
15015 DAG.getValueType(NarrowVT));
15016 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
15017 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
15018 return Shl;
15019 }
15020 }
15021 }
15022
15023 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
15024 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
15025 isa<ConstantSDNode>(LHS.getOperand(2))) {
15026 uint32_t Sel = getConstantPermuteMask(Mask);
15027 if (!Sel)
15028 return SDValue();
15029
15030 // Select 0xc for all zero bytes
15031 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
15032 SDLoc DL(N);
15033 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15034 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
15035 }
15036 }
15037
15038 // and (trunc (srl x, c)), mask => srl (trunc x), c
15039 // if mask keeps exactly the bits that srl leaves in the low half
15040 if (CRHS && VT == MVT::i16 && LHS.getOpcode() == ISD::TRUNCATE &&
15041 LHS.hasOneUse() && LHS.getOperand(0).getOpcode() == ISD::SRL) {
15042 auto *Shift = dyn_cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1));
15043 if (Shift && Shift->getZExtValue() < 16 &&
15044 CRHS->getAPIntValue().isMask(16 - Shift->getZExtValue())) {
15045 SDLoc SL(N);
15046 SDValue Trunc =
15047 DAG.getNode(ISD::TRUNCATE, SL, VT, LHS.getOperand(0).getOperand(0));
15048 return DAG.getNode(
15049 ISD::SRL, SL, VT, Trunc,
15050 DAG.getShiftAmountConstant(Shift->getZExtValue(), VT, SL));
15051 }
15052 }
15053
15054 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
15055 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
15056 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
15057 ISD::CondCode LCC = LHS.getOperandCondCode(2);
15058 ISD::CondCode RCC = RHS.getOperandCondCode(2);
15059
15060 SDValue X = LHS.getOperand(0);
15061 SDValue Y = RHS.getOperand(0);
15062 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X ||
15063 !isTypeLegal(X.getValueType()))
15064 return SDValue();
15065
15066 if (LCC == ISD::SETO) {
15067 if (X != LHS.getOperand(1))
15068 return SDValue();
15069
15070 if (RCC == ISD::SETUNE) {
15071 const ConstantFPSDNode *C1 =
15072 dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
15073 if (!C1 || !C1->isInfinity() || C1->isNegative())
15074 return SDValue();
15075
15076 const uint32_t Mask = SIInstrFlags::N_NORMAL |
15080
15081 static_assert(
15084 0x3ff) == Mask,
15085 "mask not equal");
15086
15087 SDLoc DL(N);
15088 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, X,
15089 DAG.getConstant(Mask, DL, MVT::i32));
15090 }
15091 }
15092 }
15093
15094 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
15095 std::swap(LHS, RHS);
15096
15097 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
15098 RHS.hasOneUse()) {
15099 ISD::CondCode LCC = LHS.getOperandCondCode(2);
15100 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan |
15101 // n_nan) and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan
15102 // | n_nan)
15103 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
15104 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
15105 (RHS.getOperand(0) == LHS.getOperand(0) &&
15106 LHS.getOperand(0) == LHS.getOperand(1))) {
15107 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
15108 unsigned NewMask = LCC == ISD::SETO ? Mask->getZExtValue() & ~OrdMask
15109 : Mask->getZExtValue() & OrdMask;
15110
15111 SDLoc DL(N);
15112 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
15113 DAG.getConstant(NewMask, DL, MVT::i32));
15114 }
15115 }
15116
15117 if (VT == MVT::i32 && (RHS.getOpcode() == ISD::SIGN_EXTEND ||
15118 LHS.getOpcode() == ISD::SIGN_EXTEND)) {
15119 // and x, (sext cc from i1) => select cc, x, 0
15120 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
15121 std::swap(LHS, RHS);
15122 if (isBoolSGPR(RHS.getOperand(0)))
15123 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), LHS,
15124 DAG.getConstant(0, SDLoc(N), MVT::i32));
15125 }
15126
15127 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
15128 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15129 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
15130 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
15131 uint32_t LHSMask = getPermuteMask(LHS);
15132 uint32_t RHSMask = getPermuteMask(RHS);
15133 if (LHSMask != ~0u && RHSMask != ~0u) {
15134 // Canonicalize the expression in an attempt to have fewer unique masks
15135 // and therefore fewer registers used to hold the masks.
15136 if (LHSMask > RHSMask) {
15137 std::swap(LHSMask, RHSMask);
15138 std::swap(LHS, RHS);
15139 }
15140
15141 // Select 0xc for each lane used from source operand. Zero has 0xc mask
15142 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
15143 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15144 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15145
15146 // Check of we need to combine values from two sources within a byte.
15147 if (!(LHSUsedLanes & RHSUsedLanes) &&
15148 // If we select high and lower word keep it for SDWA.
15149 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
15150 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
15151 // Each byte in each mask is either selector mask 0-3, or has higher
15152 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
15153 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
15154 // mask which is not 0xff wins. By anding both masks we have a correct
15155 // result except that 0x0c shall be corrected to give 0x0c only.
15156 uint32_t Mask = LHSMask & RHSMask;
15157 for (unsigned I = 0; I < 32; I += 8) {
15158 uint32_t ByteSel = 0xff << I;
15159 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
15160 Mask &= (0x0c << I) & 0xffffffff;
15161 }
15162
15163 // Add 4 to each active LHS lane. It will not affect any existing 0xff
15164 // or 0x0c.
15165 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
15166 SDLoc DL(N);
15167
15168 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15169 RHS.getOperand(0),
15170 DAG.getConstant(Sel, DL, MVT::i32));
15171 }
15172 }
15173 }
15174
15175 return SDValue();
15176}
15177
15178// A key component of v_perm is a mapping between byte position of the src
15179// operands, and the byte position of the dest. To provide such, we need: 1. the
15180// node that provides x byte of the dest of the OR, and 2. the byte of the node
15181// used to provide that x byte. calculateByteProvider finds which node provides
15182// a certain byte of the dest of the OR, and calculateSrcByte takes that node,
15183// and finds an ultimate src and byte position For example: The supported
15184// LoadCombine pattern for vector loads is as follows
15185// t1
15186// or
15187// / \
15188// t2 t3
15189// zext shl
15190// | | \
15191// t4 t5 16
15192// or anyext
15193// / \ |
15194// t6 t7 t8
15195// srl shl or
15196// / | / \ / \
15197// t9 t10 t11 t12 t13 t14
15198// trunc* 8 trunc* 8 and and
15199// | | / | | \
15200// t15 t16 t17 t18 t19 t20
15201// trunc* 255 srl -256
15202// | / \
15203// t15 t15 16
15204//
15205// *In this example, the truncs are from i32->i16
15206//
15207// calculateByteProvider would find t6, t7, t13, and t14 for bytes 0-3
15208// respectively. calculateSrcByte would find (given node) -> ultimate src &
15209// byteposition: t6 -> t15 & 1, t7 -> t16 & 0, t13 -> t15 & 0, t14 -> t15 & 3.
15210// After finding the mapping, we can combine the tree into vperm t15, t16,
15211// 0x05000407
15212
15213// Find the source and byte position from a node.
15214// \p DestByte is the byte position of the dest of the or that the src
15215// ultimately provides. \p SrcIndex is the byte of the src that maps to this
15216// dest of the or byte. \p Depth tracks how many recursive iterations we have
15217// performed.
15218static const std::optional<ByteProvider<SDValue>>
15219calculateSrcByte(const SDValue Op, uint64_t DestByte, uint64_t SrcIndex = 0,
15220 unsigned Depth = 0) {
15221 // We may need to recursively traverse a series of SRLs
15222 if (Depth >= 6)
15223 return std::nullopt;
15224
15225 if (Op.getValueSizeInBits() < 8)
15226 return std::nullopt;
15227
15228 if (Op.getValueType().isVector())
15229 return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
15230
15231 switch (Op->getOpcode()) {
15232 case ISD::TRUNCATE: {
15233 return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
15234 }
15235
15236 case ISD::ANY_EXTEND:
15237 case ISD::SIGN_EXTEND:
15238 case ISD::ZERO_EXTEND:
15240 SDValue NarrowOp = Op->getOperand(0);
15241 auto NarrowVT = NarrowOp.getValueType();
15242 if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG) {
15243 auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
15244 NarrowVT = VTSign->getVT();
15245 }
15246 if (!NarrowVT.isByteSized())
15247 return std::nullopt;
15248 uint64_t NarrowByteWidth = NarrowVT.getStoreSize();
15249
15250 if (SrcIndex >= NarrowByteWidth)
15251 return std::nullopt;
15252 return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
15253 }
15254
15255 case ISD::SRA:
15256 case ISD::SRL: {
15257 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15258 if (!ShiftOp)
15259 return std::nullopt;
15260
15261 uint64_t BitShift = ShiftOp->getZExtValue();
15262
15263 if (BitShift % 8 != 0)
15264 return std::nullopt;
15265
15266 uint64_t NewSrcIndex = SrcIndex + BitShift / 8;
15267 if (NewSrcIndex >= Op.getScalarValueSizeInBits() / 8)
15268 return std::nullopt;
15269
15270 return calculateSrcByte(Op->getOperand(0), DestByte, NewSrcIndex,
15271 Depth + 1);
15272 }
15273
15274 default: {
15275 return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
15276 }
15277 }
15278 llvm_unreachable("fully handled switch");
15279}
15280
15281// For a byte position in the result of an Or, traverse the tree and find the
15282// node (and the byte of the node) which ultimately provides this {Or,
15283// BytePosition}. \p Op is the operand we are currently examining. \p Index is
15284// the byte position of the Op that corresponds with the originally requested
15285// byte of the Or \p Depth tracks how many recursive iterations we have
15286// performed. \p StartingIndex is the originally requested byte of the Or
15287static const std::optional<ByteProvider<SDValue>>
15288calculateByteProvider(const SDValue &Op, unsigned Index, unsigned Depth,
15289 unsigned StartingIndex = 0) {
15290 // Finding Src tree of RHS of or typically requires at least 1 additional
15291 // depth
15292 if (Depth > 6)
15293 return std::nullopt;
15294
15295 unsigned BitWidth = Op.getScalarValueSizeInBits();
15296 if (BitWidth % 8 != 0)
15297 return std::nullopt;
15298 if (Index > BitWidth / 8 - 1)
15299 return std::nullopt;
15300
15301 bool IsVec = Op.getValueType().isVector();
15302 switch (Op.getOpcode()) {
15303 case ISD::OR: {
15304 if (IsVec)
15305 return std::nullopt;
15306
15307 auto RHS = calculateByteProvider(Op.getOperand(1), Index, Depth + 1,
15308 StartingIndex);
15309 if (!RHS)
15310 return std::nullopt;
15311 auto LHS = calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
15312 StartingIndex);
15313 if (!LHS)
15314 return std::nullopt;
15315 // A well formed Or will have two ByteProviders for each byte, one of which
15316 // is constant zero
15317 if (!LHS->isConstantZero() && !RHS->isConstantZero())
15318 return std::nullopt;
15319 if (!LHS || LHS->isConstantZero())
15320 return RHS;
15321 if (!RHS || RHS->isConstantZero())
15322 return LHS;
15323 return std::nullopt;
15324 }
15325
15326 case ISD::AND: {
15327 if (IsVec)
15328 return std::nullopt;
15329
15330 auto *BitMaskOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15331 if (!BitMaskOp)
15332 return std::nullopt;
15333
15334 uint32_t BitMask = BitMaskOp->getZExtValue();
15335 // Bits we expect for our StartingIndex
15336 uint32_t IndexMask = 0xFF << (Index * 8);
15337
15338 if ((IndexMask & BitMask) != IndexMask) {
15339 // If the result of the and partially provides the byte, then it
15340 // is not well formatted
15341 if (IndexMask & BitMask)
15342 return std::nullopt;
15344 }
15345
15346 return calculateSrcByte(Op->getOperand(0), StartingIndex, Index);
15347 }
15348
15349 case ISD::FSHR: {
15350 if (IsVec)
15351 return std::nullopt;
15352
15353 // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
15354 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(2));
15355 if (!ShiftOp || Op.getValueType().isVector())
15356 return std::nullopt;
15357
15358 uint64_t BitsProvided = Op.getValueSizeInBits();
15359 if (BitsProvided % 8 != 0)
15360 return std::nullopt;
15361
15362 uint64_t BitShift = ShiftOp->getAPIntValue().urem(BitsProvided);
15363 if (BitShift % 8)
15364 return std::nullopt;
15365
15366 uint64_t ConcatSizeInBytes = BitsProvided / 4;
15367 uint64_t ByteShift = BitShift / 8;
15368
15369 uint64_t NewIndex = (Index + ByteShift) % ConcatSizeInBytes;
15370 uint64_t BytesProvided = BitsProvided / 8;
15371 SDValue NextOp = Op.getOperand(NewIndex >= BytesProvided ? 0 : 1);
15372 NewIndex %= BytesProvided;
15373 return calculateByteProvider(NextOp, NewIndex, Depth + 1, StartingIndex);
15374 }
15375
15376 case ISD::SRA:
15377 case ISD::SRL: {
15378 if (IsVec)
15379 return std::nullopt;
15380
15381 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15382 if (!ShiftOp)
15383 return std::nullopt;
15384
15385 uint64_t BitShift = ShiftOp->getZExtValue();
15386 if (BitShift % 8)
15387 return std::nullopt;
15388
15389 auto BitsProvided = Op.getScalarValueSizeInBits();
15390 if (BitsProvided % 8 != 0)
15391 return std::nullopt;
15392
15393 uint64_t BytesProvided = BitsProvided / 8;
15394 uint64_t ByteShift = BitShift / 8;
15395 if (Index + ByteShift < BytesProvided)
15396 return calculateSrcByte(Op->getOperand(0), StartingIndex,
15397 Index + ByteShift);
15398 // SRA's out-of-range bytes are sign bits, not constant zero.
15399 if (Op.getOpcode() == ISD::SRA)
15400 return std::nullopt;
15402 }
15403
15404 case ISD::SHL: {
15405 if (IsVec)
15406 return std::nullopt;
15407
15408 auto *ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15409 if (!ShiftOp)
15410 return std::nullopt;
15411
15412 uint64_t BitShift = ShiftOp->getZExtValue();
15413 if (BitShift % 8 != 0)
15414 return std::nullopt;
15415 uint64_t ByteShift = BitShift / 8;
15416
15417 // If we are shifting by an amount greater than (or equal to)
15418 // the index we are trying to provide, then it provides 0s. If not,
15419 // then this bytes are not definitively 0s, and the corresponding byte
15420 // of interest is Index - ByteShift of the src
15421 return Index < ByteShift
15423 : calculateByteProvider(Op.getOperand(0), Index - ByteShift,
15424 Depth + 1, StartingIndex);
15425 }
15426 case ISD::ANY_EXTEND:
15427 case ISD::SIGN_EXTEND:
15428 case ISD::ZERO_EXTEND:
15430 case ISD::AssertZext:
15431 case ISD::AssertSext: {
15432 if (IsVec)
15433 return std::nullopt;
15434
15435 SDValue NarrowOp = Op->getOperand(0);
15436 unsigned NarrowBitWidth = NarrowOp.getValueSizeInBits();
15437 if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG ||
15438 Op->getOpcode() == ISD::AssertZext ||
15439 Op->getOpcode() == ISD::AssertSext) {
15440 auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
15441 NarrowBitWidth = VTSign->getVT().getSizeInBits();
15442 }
15443 if (NarrowBitWidth % 8 != 0)
15444 return std::nullopt;
15445 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
15446
15447 if (Index >= NarrowByteWidth)
15448 return Op.getOpcode() == ISD::ZERO_EXTEND
15449 ? std::optional<ByteProvider<SDValue>>(
15451 : std::nullopt;
15452 return calculateByteProvider(NarrowOp, Index, Depth + 1, StartingIndex);
15453 }
15454
15455 case ISD::TRUNCATE: {
15456 if (IsVec)
15457 return std::nullopt;
15458
15459 uint64_t NarrowByteWidth = BitWidth / 8;
15460
15461 if (NarrowByteWidth >= Index) {
15462 return calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
15463 StartingIndex);
15464 }
15465
15466 return std::nullopt;
15467 }
15468
15469 case ISD::CopyFromReg: {
15470 if (BitWidth / 8 > Index)
15471 return calculateSrcByte(Op, StartingIndex, Index);
15472
15473 return std::nullopt;
15474 }
15475
15476 case ISD::LOAD: {
15477 auto *L = cast<LoadSDNode>(Op.getNode());
15478
15479 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
15480 if (NarrowBitWidth % 8 != 0)
15481 return std::nullopt;
15482 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
15483
15484 // If the width of the load does not reach byte we are trying to provide for
15485 // and it is not a ZEXTLOAD, then the load does not provide for the byte in
15486 // question
15487 if (Index >= NarrowByteWidth) {
15488 return L->getExtensionType() == ISD::ZEXTLOAD
15489 ? std::optional<ByteProvider<SDValue>>(
15491 : std::nullopt;
15492 }
15493
15494 if (NarrowByteWidth > Index) {
15495 return calculateSrcByte(Op, StartingIndex, Index);
15496 }
15497
15498 return std::nullopt;
15499 }
15500
15501 case ISD::BSWAP: {
15502 if (IsVec)
15503 return std::nullopt;
15504
15505 return calculateByteProvider(Op->getOperand(0), BitWidth / 8 - Index - 1,
15506 Depth + 1, StartingIndex);
15507 }
15508
15510 auto *IdxOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15511 if (!IdxOp)
15512 return std::nullopt;
15513 auto VecIdx = IdxOp->getZExtValue();
15514 auto ScalarSize = Op.getScalarValueSizeInBits();
15515 if (ScalarSize < 32)
15516 Index = ScalarSize == 8 ? VecIdx : VecIdx * 2 + Index;
15517 return calculateSrcByte(ScalarSize >= 32 ? Op : Op.getOperand(0),
15518 StartingIndex, Index);
15519 }
15520
15521 case AMDGPUISD::PERM: {
15522 if (IsVec)
15523 return std::nullopt;
15524
15525 auto *PermMask = dyn_cast<ConstantSDNode>(Op->getOperand(2));
15526 if (!PermMask)
15527 return std::nullopt;
15528
15529 auto IdxMask =
15530 (PermMask->getZExtValue() & (0xFF << (Index * 8))) >> (Index * 8);
15531 if (IdxMask > 0x07 && IdxMask != 0x0c)
15532 return std::nullopt;
15533
15534 auto NextOp = Op.getOperand(IdxMask > 0x03 ? 0 : 1);
15535 auto NextIndex = IdxMask > 0x03 ? IdxMask % 4 : IdxMask;
15536
15537 return IdxMask != 0x0c ? calculateSrcByte(NextOp, StartingIndex, NextIndex)
15540 }
15541
15542 default: {
15543 return std::nullopt;
15544 }
15545 }
15546
15547 llvm_unreachable("fully handled switch");
15548}
15549
15550// Returns true if the Operand is a scalar and is 16 bits
15551static bool isExtendedFrom16Bits(SDValue &Operand) {
15552
15553 switch (Operand.getOpcode()) {
15554 case ISD::ANY_EXTEND:
15555 case ISD::SIGN_EXTEND:
15556 case ISD::ZERO_EXTEND: {
15557 auto OpVT = Operand.getOperand(0).getValueType();
15558 return !OpVT.isVector() && OpVT.getSizeInBits() == 16;
15559 }
15560 case ISD::LOAD: {
15561 LoadSDNode *L = cast<LoadSDNode>(Operand.getNode());
15562 auto ExtType = cast<LoadSDNode>(L)->getExtensionType();
15563 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::SEXTLOAD ||
15564 ExtType == ISD::EXTLOAD) {
15565 auto MemVT = L->getMemoryVT();
15566 return !MemVT.isVector() && MemVT.getSizeInBits() == 16;
15567 }
15568 return L->getMemoryVT().getSizeInBits() == 16;
15569 }
15570 default:
15571 return false;
15572 }
15573}
15574
15575// Returns true if the mask matches consecutive bytes, and the first byte
15576// begins at a power of 2 byte offset from 0th byte
15577static bool addresses16Bits(int Mask) {
15578 int Low8 = Mask & 0xff;
15579 int Hi8 = (Mask & 0xff00) >> 8;
15580
15581 assert(Low8 < 8 && Hi8 < 8);
15582 // Are the bytes contiguous in the order of increasing addresses.
15583 bool IsConsecutive = (Hi8 - Low8 == 1);
15584 // Is the first byte at location that is aligned for 16 bit instructions.
15585 // A counter example is taking 2 consecutive bytes starting at the 8th bit.
15586 // In this case, we still need code to extract the 16 bit operand, so it
15587 // is better to use i8 v_perm
15588 bool Is16Aligned = !(Low8 % 2);
15589
15590 return IsConsecutive && Is16Aligned;
15591}
15592
15593// Do not lower into v_perm if the operands are actually 16 bit
15594// and the selected bits (based on PermMask) correspond with two
15595// easily addressable 16 bit operands.
15597 SDValue &OtherOp) {
15598 int Low16 = PermMask & 0xffff;
15599 int Hi16 = (PermMask & 0xffff0000) >> 16;
15600
15601 auto TempOp = peekThroughBitcasts(Op);
15602 auto TempOtherOp = peekThroughBitcasts(OtherOp);
15603
15604 auto OpIs16Bit =
15605 TempOp.getValueSizeInBits() == 16 || isExtendedFrom16Bits(TempOp);
15606 if (!OpIs16Bit)
15607 return true;
15608
15609 auto OtherOpIs16Bit = TempOtherOp.getValueSizeInBits() == 16 ||
15610 isExtendedFrom16Bits(TempOtherOp);
15611 if (!OtherOpIs16Bit)
15612 return true;
15613
15614 // Do we cleanly address both
15615 return !addresses16Bits(Low16) || !addresses16Bits(Hi16);
15616}
15617
15619 unsigned DWordOffset) {
15620 SDValue Ret;
15621
15622 auto TypeSize = Src.getValueSizeInBits().getFixedValue();
15623 // ByteProvider must be at least 8 bits
15624 assert(Src.getValueSizeInBits().isKnownMultipleOf(8));
15625
15626 if (TypeSize <= 32)
15627 return DAG.getBitcastedAnyExtOrTrunc(Src, SL, MVT::i32);
15628
15629 if (Src.getValueType().isVector()) {
15630 auto ScalarTySize = Src.getScalarValueSizeInBits();
15631 auto ScalarTy = Src.getValueType().getScalarType();
15632 if (ScalarTySize == 32) {
15633 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Src,
15634 DAG.getConstant(DWordOffset, SL, MVT::i32));
15635 }
15636 if (ScalarTySize > 32) {
15637 Ret = DAG.getNode(
15638 ISD::EXTRACT_VECTOR_ELT, SL, ScalarTy, Src,
15639 DAG.getConstant(DWordOffset / (ScalarTySize / 32), SL, MVT::i32));
15640 auto ShiftVal = 32 * (DWordOffset % (ScalarTySize / 32));
15641 if (ShiftVal)
15642 Ret = DAG.getNode(ISD::SRL, SL, Ret.getValueType(), Ret,
15643 DAG.getConstant(ShiftVal, SL, MVT::i32));
15644 return DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15645 }
15646
15647 assert(ScalarTySize < 32);
15648 if (TypeSize % 32 == 0) {
15649 assert(DWordOffset < TypeSize / 32);
15650 SDValue Cast = DAG.getBitcast(
15651 EVT::getVectorVT(*DAG.getContext(), MVT::i32, TypeSize / 32), Src);
15652 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
15653 DAG.getConstant(DWordOffset, SL, MVT::i32));
15654 }
15655
15656 auto NumElements = TypeSize / ScalarTySize;
15657 auto Trunc32Elements = (ScalarTySize * NumElements) / 32;
15658 auto NormalizedTrunc = Trunc32Elements * 32 / ScalarTySize;
15659 auto NumElementsIn32 = 32 / ScalarTySize;
15660 auto NumAvailElements = DWordOffset < Trunc32Elements
15661 ? NumElementsIn32
15662 : NumElements - NormalizedTrunc;
15663
15665 DAG.ExtractVectorElements(Src, VecSrcs, DWordOffset * NumElementsIn32,
15666 NumAvailElements);
15667
15668 Ret = DAG.getBuildVector(
15669 MVT::getVectorVT(MVT::getIntegerVT(ScalarTySize), NumAvailElements), SL,
15670 VecSrcs);
15671 return Ret = DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15672 }
15673
15674 /// Scalar Type
15675 auto ShiftVal = 32 * DWordOffset;
15676 Ret = DAG.getNode(ISD::SRL, SL, Src.getValueType(), Src,
15677 DAG.getConstant(ShiftVal, SL, MVT::i32));
15678 return DAG.getBitcastedAnyExtOrTrunc(Ret, SL, MVT::i32);
15679}
15680
15682 SelectionDAG &DAG = DCI.DAG;
15683 [[maybe_unused]] EVT VT = N->getValueType(0);
15685
15686 // VT is known to be MVT::i32, so we need to provide 4 bytes.
15687 assert(VT == MVT::i32);
15688 for (int i = 0; i < 4; i++) {
15689 // Find the ByteProvider that provides the ith byte of the result of OR
15690 std::optional<ByteProvider<SDValue>> P =
15691 calculateByteProvider(SDValue(N, 0), i, 0, /*StartingIndex = */ i);
15692 // TODO support constantZero
15693 if (!P || P->isConstantZero())
15694 return SDValue();
15695
15696 PermNodes.push_back(*P);
15697 }
15698 if (PermNodes.size() != 4)
15699 return SDValue();
15700
15701 std::pair<unsigned, unsigned> FirstSrc(0, PermNodes[0].SrcOffset / 4);
15702 std::optional<std::pair<unsigned, unsigned>> SecondSrc;
15703 uint64_t PermMask = 0x00000000;
15704 for (size_t i = 0; i < PermNodes.size(); i++) {
15705 auto PermOp = PermNodes[i];
15706 // Since the mask is applied to Src1:Src2, Src1 bytes must be offset
15707 // by sizeof(Src2) = 4
15708 int SrcByteAdjust = 4;
15709
15710 // If the Src uses a byte from a different DWORD, then it corresponds
15711 // with a difference source
15712 if (!PermOp.hasSameSrc(PermNodes[FirstSrc.first]) ||
15713 ((PermOp.SrcOffset / 4) != FirstSrc.second)) {
15714 if (SecondSrc)
15715 if (!PermOp.hasSameSrc(PermNodes[SecondSrc->first]) ||
15716 ((PermOp.SrcOffset / 4) != SecondSrc->second))
15717 return SDValue();
15718
15719 // Set the index of the second distinct Src node
15720 SecondSrc = {i, PermNodes[i].SrcOffset / 4};
15721 assert(!(PermNodes[SecondSrc->first].Src->getValueSizeInBits() % 8));
15722 SrcByteAdjust = 0;
15723 }
15724 assert((PermOp.SrcOffset % 4) + SrcByteAdjust < 8);
15726 PermMask |= ((PermOp.SrcOffset % 4) + SrcByteAdjust) << (i * 8);
15727 }
15728 SDLoc DL(N);
15729 SDValue Op = *PermNodes[FirstSrc.first].Src;
15730 Op = getDWordFromOffset(DAG, DL, Op, FirstSrc.second);
15731 assert(Op.getValueSizeInBits() == 32);
15732
15733 // Check that we are not just extracting the bytes in order from an op
15734 if (!SecondSrc) {
15735 int Low16 = PermMask & 0xffff;
15736 int Hi16 = (PermMask & 0xffff0000) >> 16;
15737
15738 bool WellFormedLow = (Low16 == 0x0504) || (Low16 == 0x0100);
15739 bool WellFormedHi = (Hi16 == 0x0706) || (Hi16 == 0x0302);
15740
15741 // The perm op would really just produce Op. So combine into Op
15742 if (WellFormedLow && WellFormedHi)
15743 return DAG.getBitcast(MVT::getIntegerVT(32), Op);
15744 }
15745
15746 SDValue OtherOp = SecondSrc ? *PermNodes[SecondSrc->first].Src : Op;
15747
15748 if (SecondSrc) {
15749 OtherOp = getDWordFromOffset(DAG, DL, OtherOp, SecondSrc->second);
15750 assert(OtherOp.getValueSizeInBits() == 32);
15751 }
15752
15753 // Check that we haven't just recreated the same FSHR node.
15754 if (N->getOpcode() == ISD::FSHR &&
15755 (N->getOperand(0) == Op || N->getOperand(0) == OtherOp) &&
15756 (N->getOperand(1) == Op || N->getOperand(1) == OtherOp))
15757 return SDValue();
15758
15759 if (hasNon16BitAccesses(PermMask, Op, OtherOp)) {
15760
15761 assert(Op.getValueType().isByteSized() &&
15762 OtherOp.getValueType().isByteSized());
15763
15764 // If the ultimate src is less than 32 bits, then we will only be
15765 // using bytes 0: Op.getValueSizeInBytes() - 1 in the or.
15766 // CalculateByteProvider would not have returned Op as source if we
15767 // used a byte that is outside its ValueType. Thus, we are free to
15768 // ANY_EXTEND as the extended bits are dont-cares.
15769 Op = DAG.getBitcastedAnyExtOrTrunc(Op, DL, MVT::i32);
15770 OtherOp = DAG.getBitcastedAnyExtOrTrunc(OtherOp, DL, MVT::i32);
15771
15772 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op, OtherOp,
15773 DAG.getConstant(PermMask, DL, MVT::i32));
15774 }
15775 return SDValue();
15776}
15777
15778/// If \p V is a 32-bit value whose low or high 16 bits are known zero because
15779/// it was built as a half-zero pack, return the i16 value occupying the other
15780/// half and set \p IsHigh to say which half that is. Otherwise return a null
15781/// SDValue.
15782static SDValue matchHalfZeroPack(SDValue V, bool &IsHigh) {
15783 if (V.getOpcode() == ISD::ZERO_EXTEND &&
15784 V.getOperand(0).getValueType() == MVT::i16) {
15785 IsHigh = false;
15786 return V.getOperand(0);
15787 }
15788
15789 if (V.getOpcode() != ISD::BITCAST)
15790 return SDValue();
15791
15792 SDValue BV = V.getOperand(0);
15793 if (BV.getOpcode() != ISD::BUILD_VECTOR || BV.getValueType() != MVT::v2i16)
15794 return SDValue();
15795
15796 if (isNullConstant(BV.getOperand(0)) &&
15797 BV.getOperand(1).getValueType() == MVT::i16) {
15798 IsHigh = true;
15799 return BV.getOperand(1);
15800 }
15801 if (isNullConstant(BV.getOperand(1)) &&
15802 BV.getOperand(0).getValueType() == MVT::i16) {
15803 IsHigh = false;
15804 return BV.getOperand(0);
15805 }
15806 return SDValue();
15807}
15808
15809SDValue SITargetLowering::performOrCombine(SDNode *N,
15810 DAGCombinerInfo &DCI) const {
15811 SelectionDAG &DAG = DCI.DAG;
15812 SDValue LHS = N->getOperand(0);
15813 SDValue RHS = N->getOperand(1);
15814
15815 EVT VT = N->getValueType(0);
15816 if (VT == MVT::i1) {
15817 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
15818 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
15819 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
15820 SDValue Src = LHS.getOperand(0);
15821 if (Src != RHS.getOperand(0))
15822 return SDValue();
15823
15824 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
15825 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
15826 if (!CLHS || !CRHS)
15827 return SDValue();
15828
15829 // Only 10 bits are used.
15830 static const uint32_t MaxMask = 0x3ff;
15831
15832 uint32_t NewMask =
15833 (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
15834 SDLoc DL(N);
15835 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, Src,
15836 DAG.getConstant(NewMask, DL, MVT::i32));
15837 }
15838
15839 return SDValue();
15840 }
15841
15842 if (VT == MVT::i32 && !DCI.isBeforeLegalize()) {
15843 for (unsigned I : {1u, 0u}) {
15844 SDValue Ext = N->getOperand(I);
15845 // The select may need an e64 cndmask, so only fold when it eliminates
15846 // the extension.
15847 if (!Ext.hasOneUse() || !isBoolSGPRExt(Ext))
15848 continue;
15849 // A divergent select still needs to materialize a uniform condition.
15850 // Sharing that condition can also require converting it back to SCC.
15851 SDValue Cond = Ext.getOperand(0);
15852 if (N->isDivergent() && !Cond->isDivergent() && !Cond.hasOneUse())
15853 continue;
15854
15855 // or x, (sext/anyext cc from i1) => select cc, -1, x
15856 // Any-extended bits can be chosen to match sign extension.
15857 SDLoc DL(N);
15858 return DAG.getSelect(DL, MVT::i32, Cond,
15859 DAG.getAllOnesConstant(DL, MVT::i32),
15860 N->getOperand(1 - I));
15861 }
15862 }
15863
15864 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
15866 LHS.getOpcode() == AMDGPUISD::PERM &&
15867 isa<ConstantSDNode>(LHS.getOperand(2))) {
15868 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
15869 if (!Sel)
15870 return SDValue();
15871
15872 Sel |= LHS.getConstantOperandVal(2);
15873 SDLoc DL(N);
15874 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15875 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
15876 }
15877
15878 // Rejoin the two 16-bit halves of a 32-bit value into a packed vector:
15879 //
15880 // (or (bitcast (v2i16 build_vector 0, Hi)), (zero_extend i16:Lo)) ->
15881 // (bitcast (v2i16 build_vector Lo, Hi))
15882 //
15883 // The pack selects to v_perm_b32, whose selector mask is a 32-bit literal.
15884 // Without a VOP3 literal that mask needs an extra s_mov_b32, so the combine
15885 // is not worth it there.
15886 if (VT == MVT::i32 && Subtarget->hasVOP3Literal()) {
15887 bool LHSIsHigh, RHSIsHigh;
15888 SDValue LHSHalf = matchHalfZeroPack(LHS, LHSIsHigh);
15889 SDValue RHSHalf = matchHalfZeroPack(RHS, RHSIsHigh);
15890 if (LHSHalf && RHSHalf && LHSIsHigh != RHSIsHigh) {
15891 SDLoc SL(N);
15892 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i16,
15893 LHSIsHigh ? RHSHalf : LHSHalf,
15894 LHSIsHigh ? LHSHalf : RHSHalf);
15895 return DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
15896 }
15897 }
15898
15899 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
15900 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15901 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
15902 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
15903
15904 // If all the uses of an or need to extract the individual elements, do not
15905 // attempt to lower into v_perm
15906 auto usesCombinedOperand = [](SDNode *OrUse) {
15907 // If we have any non-vectorized use, then it is a candidate for v_perm
15908 if (OrUse->getOpcode() != ISD::BITCAST ||
15909 !OrUse->getValueType(0).isVector())
15910 return true;
15911
15912 // If we have any non-vectorized use, then it is a candidate for v_perm
15913 for (auto *VUser : OrUse->users()) {
15914 if (!VUser->getValueType(0).isVector())
15915 return true;
15916
15917 // If the use of a vector is a store, then combining via a v_perm
15918 // is beneficial.
15919 // TODO -- whitelist more uses
15920 for (auto VectorwiseOp : {ISD::STORE, ISD::CopyToReg, ISD::CopyFromReg})
15921 if (VUser->getOpcode() == VectorwiseOp)
15922 return true;
15923 }
15924 return false;
15925 };
15926
15927 if (!any_of(N->users(), usesCombinedOperand))
15928 return SDValue();
15929
15930 uint32_t LHSMask = getPermuteMask(LHS);
15931 uint32_t RHSMask = getPermuteMask(RHS);
15932
15933 if (LHSMask != ~0u && RHSMask != ~0u) {
15934 // Canonicalize the expression in an attempt to have fewer unique masks
15935 // and therefore fewer registers used to hold the masks.
15936 if (LHSMask > RHSMask) {
15937 std::swap(LHSMask, RHSMask);
15938 std::swap(LHS, RHS);
15939 }
15940
15941 // Select 0xc for each lane used from source operand. Zero has 0xc mask
15942 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
15943 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15944 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
15945
15946 // Check of we need to combine values from two sources within a byte.
15947 if (!(LHSUsedLanes & RHSUsedLanes) &&
15948 // If we select high and lower word keep it for SDWA.
15949 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
15950 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
15951 // Kill zero bytes selected by other mask. Zero value is 0xc.
15952 LHSMask &= ~RHSUsedLanes;
15953 RHSMask &= ~LHSUsedLanes;
15954 // Add 4 to each active LHS lane
15955 LHSMask |= LHSUsedLanes & 0x04040404;
15956 // Combine masks
15957 uint32_t Sel = LHSMask | RHSMask;
15958 SDLoc DL(N);
15959
15960 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
15961 RHS.getOperand(0),
15962 DAG.getConstant(Sel, DL, MVT::i32));
15963 }
15964 }
15965 if (LHSMask == ~0u || RHSMask == ~0u) {
15966 if (SDValue Perm = matchPERM(N, DCI))
15967 return Perm;
15968 }
15969 }
15970
15971 // Detect identity v2i32 OR and replace with identity source node.
15972 // Specifically an Or that has operands constructed from the same source node
15973 // via extract_vector_elt and build_vector. I.E.
15974 // v2i32 or(
15975 // v2i32 build_vector(
15976 // i32 extract_elt(%IdentitySrc, 0),
15977 // i32 0
15978 // ),
15979 // v2i32 build_vector(
15980 // i32 0,
15981 // i32 extract_elt(%IdentitySrc, 1)
15982 // ) )
15983 // =>
15984 // v2i32 %IdentitySrc
15985
15986 if (VT == MVT::v2i32 && LHS->getOpcode() == ISD::BUILD_VECTOR &&
15987 RHS->getOpcode() == ISD::BUILD_VECTOR) {
15988
15989 ConstantSDNode *LC = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15990 ConstantSDNode *RC = dyn_cast<ConstantSDNode>(RHS->getOperand(0));
15991
15992 // Test for and normalise build vectors.
15993 if (LC && RC && LC->getZExtValue() == 0 && RC->getZExtValue() == 0) {
15994
15995 // Get the extract_vector_element operands.
15996 SDValue LEVE = LHS->getOperand(0);
15997 SDValue REVE = RHS->getOperand(1);
15998
15999 if (LEVE->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
16001 // Check that different elements from the same vector are
16002 // extracted.
16003 if (LEVE->getOperand(0) == REVE->getOperand(0) &&
16004 LEVE->getOperand(1) != REVE->getOperand(1)) {
16005 SDValue IdentitySrc = LEVE.getOperand(0);
16006 return IdentitySrc;
16007 }
16008 }
16009 }
16010 }
16011
16012 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
16013 return SDValue();
16014
16015 // TODO: This could be a generic combine with a predicate for extracting the
16016 // high half of an integer being free.
16017
16018 // (or i64:x, (zero_extend i32:y)) ->
16019 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
16020 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
16021 RHS.getOpcode() != ISD::ZERO_EXTEND)
16022 std::swap(LHS, RHS);
16023
16024 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
16025 SDValue ExtSrc = RHS.getOperand(0);
16026 EVT SrcVT = ExtSrc.getValueType();
16027 if (SrcVT == MVT::i32) {
16028 SDLoc SL(N);
16029 auto [LowLHS, HiBits] = split64BitValue(LHS, DAG);
16030 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
16031
16032 DCI.AddToWorklist(LowOr.getNode());
16033 DCI.AddToWorklist(HiBits.getNode());
16034
16035 SDValue Vec =
16036 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, LowOr, HiBits);
16037 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
16038 }
16039 }
16040
16041 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
16042 if (CRHS) {
16043 if (SDValue Split = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
16044 N->getOperand(0), CRHS))
16045 return Split;
16046 }
16047
16048 return SDValue();
16049}
16050
16051SDValue SITargetLowering::performXorCombine(SDNode *N,
16052 DAGCombinerInfo &DCI) const {
16053 if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
16054 return RV;
16055
16056 SDValue LHS = N->getOperand(0);
16057 SDValue RHS = N->getOperand(1);
16058
16059 const ConstantSDNode *CRHS = isConstOrConstSplat(RHS);
16060 SelectionDAG &DAG = DCI.DAG;
16061
16062 EVT VT = N->getValueType(0);
16063 if (CRHS && VT == MVT::i64) {
16064 if (SDValue Split =
16065 splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
16066 return Split;
16067 }
16068
16069 // v2i32 (xor (vselect cc, x, y), K) ->
16070 // (v2i32 svelect cc, (xor x, K), (xor y, K)) This enables the xor to be
16071 // replaced with source modifiers when the select is lowered to CNDMASK.
16072 unsigned Opc = LHS.getOpcode();
16073 if (((Opc == ISD::VSELECT && VT == MVT::v2i32) ||
16074 (Opc == ISD::SELECT && VT == MVT::i64)) &&
16075 CRHS && CRHS->getAPIntValue().isSignMask()) {
16076 SDValue CC = LHS->getOperand(0);
16077 SDValue TRUE = LHS->getOperand(1);
16078 SDValue FALSE = LHS->getOperand(2);
16079 SDValue XTrue = DAG.getNode(ISD::XOR, SDLoc(N), VT, TRUE, RHS);
16080 SDValue XFalse = DAG.getNode(ISD::XOR, SDLoc(N), VT, FALSE, RHS);
16081 SDValue XSelect =
16082 DAG.getNode(ISD::VSELECT, SDLoc(N), VT, CC, XTrue, XFalse);
16083 return XSelect;
16084 }
16085
16086 // Make sure to apply the 64-bit constant splitting fold before trying to fold
16087 // fneg-like xors into 64-bit select.
16088 if (LHS.getOpcode() == ISD::SELECT && VT == MVT::i32) {
16089 // This looks like an fneg, try to fold as a source modifier.
16090 if (CRHS && CRHS->getAPIntValue().isSignMask() &&
16092 // xor (select c, a, b), 0x80000000 ->
16093 // bitcast (select c, (fneg (bitcast a)), (fneg (bitcast b)))
16094 SDLoc DL(N);
16095 SDValue CastLHS =
16096 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(1));
16097 SDValue CastRHS =
16098 DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(2));
16099 SDValue FNegLHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastLHS);
16100 SDValue FNegRHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastRHS);
16101 SDValue NewSelect = DAG.getNode(ISD::SELECT, DL, MVT::f32,
16102 LHS->getOperand(0), FNegLHS, FNegRHS);
16103 return DAG.getNode(ISD::BITCAST, DL, VT, NewSelect);
16104 }
16105 }
16106
16107 return SDValue();
16108}
16109
16110SDValue
16111SITargetLowering::performZeroOrAnyExtendCombine(SDNode *N,
16112 DAGCombinerInfo &DCI) const {
16113 if (!Subtarget->has16BitInsts() ||
16114 DCI.getDAGCombineLevel() < AfterLegalizeTypes)
16115 return SDValue();
16116
16117 EVT VT = N->getValueType(0);
16118 if (VT != MVT::i32)
16119 return SDValue();
16120
16121 SDValue Src = N->getOperand(0);
16122 if (Src.getValueType() != MVT::i16)
16123 return SDValue();
16124
16125 if (!Src->hasOneUse())
16126 return SDValue();
16127
16128 if (SDValue Ext = performExtendTruncShiftCombine(N, DCI))
16129 return Ext;
16130
16131 // TODO: We bail out below if SrcOffset is not in the first dword (>= 4). It's
16132 // possible we're missing out on some combine opportunities, but we'd need to
16133 // weigh the cost of extracting the byte from the upper dwords.
16134
16135 std::optional<ByteProvider<SDValue>> BP0 =
16136 calculateByteProvider(SDValue(N, 0), 0, 0, 0);
16137 if (!BP0 || BP0->SrcOffset >= 4 || !BP0->Src)
16138 return SDValue();
16139 SDValue V0 = *BP0->Src;
16140
16141 std::optional<ByteProvider<SDValue>> BP1 =
16142 calculateByteProvider(SDValue(N, 0), 1, 0, 1);
16143 if (!BP1 || BP1->SrcOffset >= 4 || !BP1->Src)
16144 return SDValue();
16145
16146 SDValue V1 = *BP1->Src;
16147
16148 if (V0 == V1)
16149 return SDValue();
16150
16151 SelectionDAG &DAG = DCI.DAG;
16152 SDLoc DL(N);
16153 uint32_t PermMask = 0x0c0c0c0c;
16154 if (V0) {
16155 V0 = getDWordFromOffset(DAG, DL, V0, /*DWordOffset=*/0);
16156 PermMask = (PermMask & ~0xFF) | (BP0->SrcOffset + 4);
16157 }
16158
16159 if (V1) {
16160 V1 = getDWordFromOffset(DAG, DL, V1, /*DWordOffset=*/0);
16161 PermMask = (PermMask & ~(0xFF << 8)) | (BP1->SrcOffset << 8);
16162 }
16163
16164 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, V0, V1,
16165 DAG.getConstant(PermMask, DL, MVT::i32));
16166}
16167
16168// zext (srl (trunc x), c) => and (srl x, c), lowbits
16169// aext (srl (trunc x), c) => and (srl x, c), lowbits
16170// sext (sra (trunc x), 8) => sext_inreg (srl x, 8), i8
16171SDValue
16172SITargetLowering::performExtendTruncShiftCombine(SDNode *N,
16173 DAGCombinerInfo &DCI) const {
16174 if (DCI.getDAGCombineLevel() < AfterLegalizeTypes)
16175 return SDValue();
16176
16177 const unsigned Opc = N->getOpcode();
16178 const bool IsSigned = Opc == ISD::SIGN_EXTEND;
16179 SDValue Src = N->getOperand(0);
16180 if (N->getValueType(0) != MVT::i32 || Src.getValueType() != MVT::i16 ||
16181 Src.getOpcode() != (IsSigned ? ISD::SRA : ISD::SRL) || !Src.hasOneUse() ||
16182 Src.getOperand(0).getOpcode() != ISD::TRUNCATE)
16183 return SDValue();
16184
16185 // A uniform i16 srl is promoted to i32 later and yields the same nodes.
16186 // Skip it so that the node order, and with it the schedule, stays the same.
16187 if (!IsSigned && !Src->isDivergent())
16188 return SDValue();
16189
16190 SDValue X = Src.getOperand(0).getOperand(0);
16191 auto *Shift = dyn_cast<ConstantSDNode>(Src.getOperand(1));
16192 if (X.getValueType() != MVT::i32 || !Shift || Shift->getZExtValue() == 0 ||
16193 Shift->getZExtValue() >= 16 || (IsSigned && Shift->getZExtValue() != 8))
16194 return SDValue();
16195
16196 SelectionDAG &DAG = DCI.DAG;
16197 SDLoc SL(N);
16198 const unsigned Width = 16 - Shift->getZExtValue();
16199 SDValue Srl = DAG.getNode(
16200 ISD::SRL, SL, MVT::i32, X,
16201 DAG.getShiftAmountConstant(Shift->getZExtValue(), MVT::i32, SL));
16202 if (IsSigned)
16203 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, Srl,
16204 DAG.getValueType(MVT::i8));
16205 return DAG.getNode(
16206 ISD::AND, SL, MVT::i32, Srl,
16207 DAG.getConstant(maskTrailingOnes<uint32_t>(Width), SL, MVT::i32));
16208}
16209
16210SDValue
16211SITargetLowering::performSignExtendInRegCombine(SDNode *N,
16212 DAGCombinerInfo &DCI) const {
16213 SDValue Src = N->getOperand(0);
16214 auto *VTSign = cast<VTSDNode>(N->getOperand(1));
16215
16216 // Combine s_buffer_load_u8 or s_buffer_load_u16 with sext and replace them
16217 // with s_buffer_load_i8 and s_buffer_load_i16 respectively.
16218 if (((Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_UBYTE &&
16219 VTSign->getVT() == MVT::i8) ||
16220 (Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_USHORT &&
16221 VTSign->getVT() == MVT::i16))) {
16222 assert(Subtarget->hasScalarSubwordLoads() &&
16223 "s_buffer_load_{u8, i8} are supported "
16224 "in GFX12 (or newer) architectures.");
16225 unsigned Opc = (Src.getOpcode() == AMDGPUISD::SBUFFER_LOAD_UBYTE)
16226 ? AMDGPUISD::SBUFFER_LOAD_BYTE
16227 : AMDGPUISD::SBUFFER_LOAD_SHORT;
16228 SDLoc DL(N);
16229 SDVTList ResList =
16230 DCI.DAG.getVTList(MVT::i32, Src.getOperand(0).getValueType());
16231 SDValue Ops[] = {
16232 Src.getOperand(0), // Chain
16233 Src.getOperand(1), // source register
16234 Src.getOperand(2), // offset
16235 Src.getOperand(3) // cachePolicy
16236 };
16237 auto *M = cast<MemSDNode>(Src);
16238 SDValue BufferLoad = DCI.DAG.getMemIntrinsicNode(
16239 Opc, DL, ResList, Ops, M->getMemoryVT(), M->getMemOperand());
16240 return DCI.DAG.getMergeValues({BufferLoad, BufferLoad.getValue(1)}, DL);
16241 }
16242 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
16243 VTSign->getVT() == MVT::i8) ||
16244 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
16245 VTSign->getVT() == MVT::i16)) &&
16246 Src.hasOneUse()) {
16247 auto *M = cast<MemSDNode>(Src);
16248 SDValue Ops[] = {Src.getOperand(0), // Chain
16249 Src.getOperand(1), // rsrc
16250 Src.getOperand(2), // vindex
16251 Src.getOperand(3), // voffset
16252 Src.getOperand(4), // soffset
16253 Src.getOperand(5), // offset
16254 Src.getOperand(6), Src.getOperand(7)};
16255 // replace with BUFFER_LOAD_BYTE/SHORT
16256 SDVTList ResList =
16257 DCI.DAG.getVTList(MVT::i32, Src.getOperand(0).getValueType());
16258 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE)
16259 ? AMDGPUISD::BUFFER_LOAD_BYTE
16260 : AMDGPUISD::BUFFER_LOAD_SHORT;
16261 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(
16262 Opc, SDLoc(N), ResList, Ops, M->getMemoryVT(), M->getMemOperand());
16263 return DCI.DAG.getMergeValues(
16264 {BufferLoadSignExt, BufferLoadSignExt.getValue(1)}, SDLoc(N));
16265 }
16266 return SDValue();
16267}
16268
16269SDValue SITargetLowering::performClassCombine(SDNode *N,
16270 DAGCombinerInfo &DCI) const {
16271 SelectionDAG &DAG = DCI.DAG;
16272 SDValue Mask = N->getOperand(1);
16273
16274 // fp_class x, 0 -> false
16275 if (isNullConstant(Mask))
16276 return DAG.getConstant(0, SDLoc(N), MVT::i1);
16277
16278 if (N->getOperand(0).isUndef())
16279 return DAG.getUNDEF(MVT::i1);
16280
16281 return SDValue();
16282}
16283
16284SDValue SITargetLowering::performRcpCombine(SDNode *N,
16285 DAGCombinerInfo &DCI) const {
16286 EVT VT = N->getValueType(0);
16287 SDValue N0 = N->getOperand(0);
16288
16289 if (N0.isUndef()) {
16290 return DCI.DAG.getConstantFP(APFloat::getQNaN(VT.getFltSemantics()),
16291 SDLoc(N), VT);
16292 }
16293
16294 // TODO: Could handle f32 + amdgcn.sqrt but probably never reaches here.
16295 if ((VT == MVT::f16 && N0.getOpcode() == ISD::FSQRT) &&
16296 N->getFlags().hasAllowContract() && N0->getFlags().hasAllowContract()) {
16297 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, N0.getOperand(0),
16298 N->getFlags());
16299 }
16300
16302}
16303
16305 SDNodeFlags UserFlags,
16306 unsigned MaxDepth) const {
16307 EVT VT = Op.getValueType();
16308 assert(VT.isFloatingPoint() &&
16309 "expected a floating-point value to query canonicality of");
16310 return isCanonicalized(DAG, Op, VT.getScalarType(), UserFlags, MaxDepth);
16311}
16312
16314 EVT QueryVT, SDNodeFlags UserFlags,
16315 unsigned MaxDepth) const {
16316 assert(QueryVT.isFloatingPoint() && !QueryVT.isVector() &&
16317 "QueryVT must be a floating-point scalar type");
16318 EVT VT = Op.getValueType();
16319 if (VT.isFloatingPoint() && VT.getScalarType() != QueryVT)
16320 return false;
16321
16322 unsigned Opcode = Op.getOpcode();
16323 if (Opcode == ISD::FCANONICALIZE)
16324 return true;
16325
16326 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
16327 const auto &F = CFP->getValueAPF();
16328 if (F.isNaN() && F.isSignaling())
16329 return false;
16330 if (!F.isDenormal())
16331 return true;
16332
16333 DenormalMode Mode =
16334 DAG.getMachineFunction().getDenormalMode(F.getSemantics());
16335 return Mode == DenormalMode::getIEEE();
16336 }
16337
16338 // If source is a result of another standard FP operation it is already in
16339 // canonical form.
16340 if (MaxDepth == 0)
16341 return false;
16342
16343 switch (Opcode) {
16344 // These will flush denorms if required.
16345 case ISD::FADD:
16346 case ISD::FSUB:
16347 case ISD::FMUL:
16348 case ISD::FCEIL:
16349 case ISD::FFLOOR:
16350 case ISD::FMA:
16351 case ISD::FMAD:
16352 case ISD::FSQRT:
16353 case ISD::FDIV:
16354 case ISD::FREM:
16355 case ISD::FP_ROUND:
16356 case ISD::FP_EXTEND:
16357 case ISD::FP16_TO_FP:
16358 case ISD::FP_TO_FP16:
16359 case ISD::BF16_TO_FP:
16360 case ISD::FP_TO_BF16:
16361 case ISD::FLDEXP:
16362 case AMDGPUISD::FMUL_LEGACY:
16363 case AMDGPUISD::FMAD_FTZ:
16364 case AMDGPUISD::RCP:
16365 case AMDGPUISD::RSQ:
16366 case AMDGPUISD::RSQ_CLAMP:
16367 case AMDGPUISD::RCP_LEGACY:
16368 case AMDGPUISD::RCP_IFLAG:
16369 case AMDGPUISD::LOG:
16370 case AMDGPUISD::EXP:
16371 case AMDGPUISD::DIV_SCALE:
16372 case AMDGPUISD::DIV_FMAS:
16373 case AMDGPUISD::DIV_FIXUP:
16374 case AMDGPUISD::FRACT:
16375 case AMDGPUISD::CVT_PKRTZ_F16_F32:
16376 case AMDGPUISD::CVT_F32_UBYTE0:
16377 case AMDGPUISD::CVT_F32_UBYTE1:
16378 case AMDGPUISD::CVT_F32_UBYTE2:
16379 case AMDGPUISD::CVT_F32_UBYTE3:
16380 case AMDGPUISD::FP_TO_FP16:
16381 case AMDGPUISD::SIN_HW:
16382 case AMDGPUISD::COS_HW:
16383 return true;
16384
16385 // It can/will be lowered or combined as a bit operation.
16386 // Need to check their input recursively to handle.
16387 case ISD::FNEG:
16388 case ISD::FABS:
16389 case ISD::FCOPYSIGN:
16390 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16391 MaxDepth - 1);
16392
16393 case ISD::AND:
16394 if (Op.getValueType() == MVT::i32) {
16395 // Be careful as we only know it is a bitcast floating point type. It
16396 // could be f32, v2f16, we have no way of knowing. Luckily the constant
16397 // value that we optimize for, which comes up in fp32 to bf16 conversions,
16398 // is valid to optimize for all types.
16399 if (auto *RHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16400 if (RHS->getZExtValue() == 0xffff0000) {
16401 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16402 MaxDepth - 1);
16403 }
16404 }
16405 }
16406 break;
16407
16408 case ISD::FSIN:
16409 case ISD::FCOS:
16410 case ISD::FSINCOS:
16411 return Op.getValueType().getScalarType() != MVT::f16;
16412
16413 case ISD::FMINNUM:
16414 case ISD::FMAXNUM:
16415 case ISD::FMINNUM_IEEE:
16416 case ISD::FMAXNUM_IEEE:
16417 case ISD::FMINIMUM:
16418 case ISD::FMAXIMUM:
16419 case ISD::FMINIMUMNUM:
16420 case ISD::FMAXIMUMNUM:
16421 case AMDGPUISD::CLAMP:
16422 case AMDGPUISD::FMED3:
16423 case AMDGPUISD::FMAX3:
16424 case AMDGPUISD::FMIN3:
16425 case AMDGPUISD::FMAXIMUM3:
16426 case AMDGPUISD::FMINIMUM3: {
16427 // FIXME: Shouldn't treat the generic operations different based these.
16428 // However, we aren't really required to flush the result from
16429 // minnum/maxnum..
16430
16431 // snans will be quieted, so we only need to worry about denormals.
16432 if (Subtarget->supportsMinMaxDenormModes() ||
16433 // FIXME: denormalsEnabledForType is broken for dynamic
16434 denormalsEnabledForType(DAG, Op.getValueType()))
16435 return true;
16436
16437 // Flushing may be required.
16438 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
16439 // targets need to check their input recursively.
16440
16441 // FIXME: Does this apply with clamp? It's implemented with max.
16442 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
16443 if (!isCanonicalized(DAG, Op.getOperand(I), QueryVT, UserFlags,
16444 MaxDepth - 1))
16445 return false;
16446 }
16447
16448 return true;
16449 }
16450 case ISD::SELECT: {
16451 return isCanonicalized(DAG, Op.getOperand(1), QueryVT, UserFlags,
16452 MaxDepth - 1) &&
16453 isCanonicalized(DAG, Op.getOperand(2), QueryVT, UserFlags,
16454 MaxDepth - 1);
16455 }
16456 case ISD::BUILD_VECTOR: {
16457 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
16458 SDValue SrcOp = Op.getOperand(i);
16459 if (!isCanonicalized(DAG, SrcOp, QueryVT, UserFlags, MaxDepth - 1))
16460 return false;
16461 }
16462
16463 return true;
16464 }
16467 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16468 MaxDepth - 1);
16469 }
16471 return isCanonicalized(DAG, Op.getOperand(0), QueryVT, UserFlags,
16472 MaxDepth - 1) &&
16473 isCanonicalized(DAG, Op.getOperand(1), QueryVT, UserFlags,
16474 MaxDepth - 1);
16475 }
16476 case ISD::POISON:
16477 return true;
16478 case ISD::UNDEF:
16479 // Could be anything.
16480 return false;
16481
16482 case ISD::BITCAST: {
16483 // Carry QueryVT through the bitcast unchanged. The top-of-function guard
16484 // rejects a source whose FP format differs from the consumed type, so a
16485 // value canonical in one FP format is not assumed canonical in another.
16486 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
16487 return isCanonicalized(DAG, Src, QueryVT, UserFlags, MaxDepth - 1);
16488 }
16489 case ISD::TRUNCATE: {
16490 // Hack round the mess we make when legalizing extract_vector_elt
16491 if (Op.getValueType() == MVT::i16) {
16492 SDValue TruncSrc = Op.getOperand(0);
16493 if (TruncSrc.getValueType() == MVT::i32 &&
16494 TruncSrc.getOpcode() == ISD::BITCAST &&
16495 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
16496 return isCanonicalized(DAG, TruncSrc.getOperand(0), QueryVT, UserFlags,
16497 MaxDepth - 1);
16498 }
16499 }
16500 return false;
16501 }
16503 unsigned IntrinsicID = Op.getConstantOperandVal(0);
16504 // TODO: Handle more intrinsics
16505 switch (IntrinsicID) {
16506 case Intrinsic::amdgcn_update_dpp: {
16507 enum UpdateDPPOperand {
16508 Old = 1,
16509 Src = 2,
16510 RowMask = 4,
16511 BankMask = 5,
16512 BoundCtrl = 6,
16513 };
16514
16515 if (QueryVT != MVT::f32 || (VT != MVT::i32 && VT != MVT::f32))
16516 return false;
16517
16518 SDValue SrcVal = Op.getOperand(Src);
16519 if (!isCanonicalized(DAG, SrcVal, QueryVT, UserFlags, MaxDepth - 1))
16520 return false;
16521
16522 if (Op.getConstantOperandVal(RowMask) == 0xf && // Enable all rows.
16523 Op.getConstantOperandVal(BankMask) == 0xf && // Enable all banks.
16524 Op.getConstantOperandVal(BoundCtrl) != 0) // Zero-fill OOB lanes.
16525 return true;
16526
16527 SDValue OldVal = Op.getOperand(Old);
16528 return OldVal == SrcVal ||
16529 isCanonicalized(DAG, OldVal, QueryVT, UserFlags, MaxDepth - 1);
16530 }
16531 case Intrinsic::amdgcn_cvt_pkrtz:
16532 case Intrinsic::amdgcn_cubeid:
16533 case Intrinsic::amdgcn_frexp_mant:
16534 case Intrinsic::amdgcn_fdot2:
16535 case Intrinsic::amdgcn_rcp:
16536 case Intrinsic::amdgcn_rsq:
16537 case Intrinsic::amdgcn_rsq_clamp:
16538 case Intrinsic::amdgcn_rcp_legacy:
16539 case Intrinsic::amdgcn_rsq_legacy:
16540 case Intrinsic::amdgcn_trig_preop:
16541 case Intrinsic::amdgcn_tanh:
16542 case Intrinsic::amdgcn_log:
16543 case Intrinsic::amdgcn_exp2:
16544 case Intrinsic::amdgcn_sqrt:
16545 return true;
16546 default:
16547 break;
16548 }
16549
16550 break;
16551 }
16552 default:
16553 break;
16554 }
16555
16556 // FIXME: denormalsEnabledForType is broken for dynamic
16557 return denormalsEnabledForType(DAG, Op.getValueType()) &&
16558 (UserFlags.hasNoNaNs() || DAG.isKnownNeverSNaN(Op));
16559}
16560
16562 unsigned MaxDepth) const {
16563 const MachineRegisterInfo &MRI = MF.getRegInfo();
16564 MachineInstr *MI = MRI.getVRegDef(Reg);
16565 unsigned Opcode = MI->getOpcode();
16566
16567 if (Opcode == AMDGPU::G_FCANONICALIZE)
16568 return true;
16569
16570 std::optional<FPValueAndVReg> FCR;
16571 // Constant splat (can be padded with undef) or scalar constant.
16573 if (FCR->Value.isSignaling())
16574 return false;
16575 if (!FCR->Value.isDenormal())
16576 return true;
16577
16578 DenormalMode Mode = MF.getDenormalMode(FCR->Value.getSemantics());
16579 return Mode == DenormalMode::getIEEE();
16580 }
16581
16582 if (MaxDepth == 0)
16583 return false;
16584
16585 switch (Opcode) {
16586 case AMDGPU::G_FADD:
16587 case AMDGPU::G_FSUB:
16588 case AMDGPU::G_FMUL:
16589 case AMDGPU::G_FCEIL:
16590 case AMDGPU::G_FFLOOR:
16591 case AMDGPU::G_FRINT:
16592 case AMDGPU::G_FNEARBYINT:
16593 case AMDGPU::G_INTRINSIC_FPTRUNC_ROUND:
16594 case AMDGPU::G_INTRINSIC_TRUNC:
16595 case AMDGPU::G_INTRINSIC_ROUNDEVEN:
16596 case AMDGPU::G_FMA:
16597 case AMDGPU::G_FMAD:
16598 case AMDGPU::G_FSQRT:
16599 case AMDGPU::G_FDIV:
16600 case AMDGPU::G_FREM:
16601 case AMDGPU::G_FPOW:
16602 case AMDGPU::G_FPEXT:
16603 case AMDGPU::G_FLOG:
16604 case AMDGPU::G_FLOG2:
16605 case AMDGPU::G_FLOG10:
16606 case AMDGPU::G_FPTRUNC:
16607 case AMDGPU::G_AMDGPU_RCP_IFLAG:
16608 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE0:
16609 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE1:
16610 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE2:
16611 case AMDGPU::G_AMDGPU_CVT_F32_UBYTE3:
16612 return true;
16613 case AMDGPU::G_FNEG:
16614 case AMDGPU::G_FABS:
16615 case AMDGPU::G_FCOPYSIGN:
16616 return isCanonicalized(MI->getOperand(1).getReg(), MF, MaxDepth - 1);
16617 case AMDGPU::G_FMINNUM:
16618 case AMDGPU::G_FMAXNUM:
16619 case AMDGPU::G_FMINNUM_IEEE:
16620 case AMDGPU::G_FMAXNUM_IEEE:
16621 case AMDGPU::G_FMINIMUM:
16622 case AMDGPU::G_FMAXIMUM:
16623 case AMDGPU::G_FMINIMUMNUM:
16624 case AMDGPU::G_FMAXIMUMNUM: {
16625 if (Subtarget->supportsMinMaxDenormModes() ||
16626 // FIXME: denormalsEnabledForType is broken for dynamic
16627 denormalsEnabledForType(MRI.getType(Reg), MF))
16628 return true;
16629
16630 [[fallthrough]];
16631 }
16632 case AMDGPU::G_BUILD_VECTOR:
16633 for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
16634 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
16635 return false;
16636 return true;
16637 case AMDGPU::G_INTRINSIC:
16638 case AMDGPU::G_INTRINSIC_CONVERGENT:
16639 switch (cast<GIntrinsic>(MI)->getIntrinsicID()) {
16640 case Intrinsic::amdgcn_update_dpp: {
16641 enum OperandIdx { Old = 2, Src, DppCtrl, RowMask, BankMask, BoundCtrl };
16642
16643 LLT Ty = MRI.getType(Reg);
16644 if (!Ty.isScalar() || Ty.getSizeInBits() != 32)
16645 return false;
16646
16647 Register SrcReg = MI->getOperand(Src).getReg();
16648 if (!isCanonicalized(SrcReg, MF, MaxDepth - 1))
16649 return false;
16650
16651 if (MI->getOperand(RowMask).getImm() == 0xf &&
16652 MI->getOperand(BankMask).getImm() == 0xf &&
16653 MI->getOperand(BoundCtrl).getImm() != 0)
16654 return true;
16655
16656 Register OldReg = MI->getOperand(Old).getReg();
16657 return OldReg == SrcReg || isCanonicalized(OldReg, MF, MaxDepth - 1);
16658 }
16659 case Intrinsic::amdgcn_fmul_legacy:
16660 case Intrinsic::amdgcn_fmad_ftz:
16661 case Intrinsic::amdgcn_sqrt:
16662 case Intrinsic::amdgcn_fmed3:
16663 case Intrinsic::amdgcn_sin:
16664 case Intrinsic::amdgcn_cos:
16665 case Intrinsic::amdgcn_log:
16666 case Intrinsic::amdgcn_exp2:
16667 case Intrinsic::amdgcn_log_clamp:
16668 case Intrinsic::amdgcn_rcp:
16669 case Intrinsic::amdgcn_rcp_legacy:
16670 case Intrinsic::amdgcn_rsq:
16671 case Intrinsic::amdgcn_rsq_clamp:
16672 case Intrinsic::amdgcn_rsq_legacy:
16673 case Intrinsic::amdgcn_div_scale:
16674 case Intrinsic::amdgcn_div_fmas:
16675 case Intrinsic::amdgcn_div_fixup:
16676 case Intrinsic::amdgcn_fract:
16677 case Intrinsic::amdgcn_cvt_pkrtz:
16678 case Intrinsic::amdgcn_cubeid:
16679 case Intrinsic::amdgcn_cubema:
16680 case Intrinsic::amdgcn_cubesc:
16681 case Intrinsic::amdgcn_cubetc:
16682 case Intrinsic::amdgcn_frexp_mant:
16683 case Intrinsic::amdgcn_fdot2:
16684 case Intrinsic::amdgcn_trig_preop:
16685 case Intrinsic::amdgcn_tanh:
16686 return true;
16687 default:
16688 break;
16689 }
16690
16691 [[fallthrough]];
16692 default:
16693 return false;
16694 }
16695
16696 llvm_unreachable("invalid operation");
16697}
16698
16699// Constant fold canonicalize.
16700SDValue SITargetLowering::getCanonicalConstantFP(SelectionDAG &DAG,
16701 const SDLoc &SL, EVT VT,
16702 const APFloat &C) const {
16703 // Flush denormals to 0 if not enabled.
16704 if (C.isDenormal()) {
16705 DenormalMode Mode =
16706 DAG.getMachineFunction().getDenormalMode(C.getSemantics());
16707 if (Mode == DenormalMode::getPreserveSign()) {
16708 return DAG.getConstantFP(
16709 APFloat::getZero(C.getSemantics(), C.isNegative()), SL, VT);
16710 }
16711
16712 if (Mode != DenormalMode::getIEEE())
16713 return SDValue();
16714 }
16715
16716 if (C.isNaN()) {
16717 if (C.isSignaling()) {
16718 // Quiet a signaling NaN.
16719 return DAG.getConstantFP(C.makeQuiet(), SL, VT);
16720 }
16721 }
16722
16723 // Already canonical.
16724 return DAG.getConstantFP(C, SL, VT);
16725}
16726
16728 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
16729}
16730
16731SDValue
16732SITargetLowering::performFCanonicalizeCombine(SDNode *N,
16733 DAGCombinerInfo &DCI) const {
16734 SelectionDAG &DAG = DCI.DAG;
16735 SDValue N0 = N->getOperand(0);
16736 EVT VT = N->getValueType(0);
16737
16738 // fcanonicalize undef -> qnan
16739 if (N0.isUndef()) {
16741 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
16742 }
16743
16744 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0))
16745 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
16746
16747 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
16748 // (fcanonicalize k)
16749 //
16750 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
16751
16752 // TODO: This could be better with wider vectors that will be split to v2f16,
16753 // and to consider uses since there aren't that many packed operations.
16754 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNumOperands() == 2 &&
16755 isTypeLegal(VT)) {
16756 SDLoc SL(N);
16757 SDValue NewElts[2];
16758 SDValue Lo = N0.getOperand(0);
16759 SDValue Hi = N0.getOperand(1);
16760 EVT EltVT = Lo.getValueType();
16761
16762 // Only apply this optimization if scalar canonicalize is legal for the
16763 // element type. Otherwise, scalarizing may require widening the scalar back
16764 // to a vector, adding overhead (e.g., bf16 has no scalar instructions).
16766 return SDValue();
16767
16769 for (unsigned I = 0; I != 2; ++I) {
16770 SDValue Op = N0.getOperand(I);
16771 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
16772 NewElts[I] =
16773 getCanonicalConstantFP(DAG, SL, EltVT, CFP->getValueAPF());
16774 } else if (Op.isUndef()) {
16775 // Handled below based on what the other operand is.
16776 NewElts[I] = Op;
16777 } else {
16778 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
16779 }
16780 }
16781
16782 // If one half is undef, and one is constant, prefer a splat vector.
16783 // Otherwise, convert the undef to 0.0 since that's cheaper to use and may
16784 // be free with a packed operation.
16785 if (NewElts[0].isUndef()) {
16786 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1])
16787 ? NewElts[1]
16788 : DAG.getConstantFP(0.0f, SL, EltVT);
16789 }
16790
16791 if (NewElts[1].isUndef()) {
16792 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0])
16793 ? NewElts[0]
16794 : DAG.getConstantFP(0.0f, SL, EltVT);
16795 }
16796
16797 return DAG.getBuildVector(VT, SL, NewElts);
16798 }
16799 }
16800
16801 return SDValue();
16802}
16803
16804static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
16805 switch (Opc) {
16806 case ISD::FMAXNUM:
16807 case ISD::FMAXNUM_IEEE:
16808 case ISD::FMAXIMUMNUM:
16809 return AMDGPUISD::FMAX3;
16810 case ISD::FMAXIMUM:
16811 return AMDGPUISD::FMAXIMUM3;
16812 case ISD::SMAX:
16813 return AMDGPUISD::SMAX3;
16814 case ISD::UMAX:
16815 return AMDGPUISD::UMAX3;
16816 case ISD::FMINNUM:
16817 case ISD::FMINNUM_IEEE:
16818 case ISD::FMINIMUMNUM:
16819 return AMDGPUISD::FMIN3;
16820 case ISD::FMINIMUM:
16821 return AMDGPUISD::FMINIMUM3;
16822 case ISD::SMIN:
16823 return AMDGPUISD::SMIN3;
16824 case ISD::UMIN:
16825 return AMDGPUISD::UMIN3;
16826 default:
16827 llvm_unreachable("Not a min/max opcode");
16828 }
16829}
16830
16831SDValue SITargetLowering::performIntMed3ImmCombine(SelectionDAG &DAG,
16832 const SDLoc &SL, SDValue Src,
16833 SDValue MinVal,
16834 SDValue MaxVal,
16835 bool Signed) const {
16836
16837 // med3 comes from
16838 // min(max(x, K0), K1), K0 < K1
16839 // max(min(x, K0), K1), K1 < K0
16840 //
16841 // "MinVal" and "MaxVal" respectively refer to the rhs of the
16842 // min/max op.
16843 ConstantSDNode *MinK = dyn_cast<ConstantSDNode>(MinVal);
16844 ConstantSDNode *MaxK = dyn_cast<ConstantSDNode>(MaxVal);
16845
16846 if (!MinK || !MaxK)
16847 return SDValue();
16848
16849 if (Signed) {
16850 if (MaxK->getAPIntValue().sge(MinK->getAPIntValue()))
16851 return SDValue();
16852 } else {
16853 if (MaxK->getAPIntValue().uge(MinK->getAPIntValue()))
16854 return SDValue();
16855 }
16856
16857 EVT VT = MinK->getValueType(0);
16858 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
16859 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16()))
16860 return DAG.getNode(Med3Opc, SL, VT, Src, MaxVal, MinVal);
16861
16862 // Note: we could also extend to i32 and use i32 med3 if i16 med3 is
16863 // not available, but this is unlikely to be profitable as constants
16864 // will often need to be materialized & extended, especially on
16865 // pre-GFX10 where VOP3 instructions couldn't take literal operands.
16866 return SDValue();
16867}
16868
16871 return C;
16872
16874 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
16875 return C;
16876 }
16877
16878 return nullptr;
16879}
16880
16881SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
16882 const SDLoc &SL, SDValue Op0,
16883 SDValue Op1,
16884 bool IsKnownNoNaNs) const {
16885 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
16886 if (!K1)
16887 return SDValue();
16888
16889 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
16890 if (!K0)
16891 return SDValue();
16892
16893 // Ordered >= (although NaN inputs should have folded away by now).
16894 if (K0->getValueAPF() > K1->getValueAPF())
16895 return SDValue();
16896
16897 // med3 with a nan input acts like
16898 // v_min_f32(v_min_f32(S0.f32, S1.f32), S2.f32)
16899 //
16900 // So the result depends on whether the IEEE mode bit is enabled or not with a
16901 // signaling nan input.
16902 // ieee=1
16903 // s0 snan: yields s2
16904 // s1 snan: yields s2
16905 // s2 snan: qnan
16906
16907 // s0 qnan: min(s1, s2)
16908 // s1 qnan: min(s0, s2)
16909 // s2 qnan: min(s0, s1)
16910
16911 // ieee=0
16912 // s0 snan: min(s1, s2)
16913 // s1 snan: min(s0, s2)
16914 // s2 snan: qnan
16915
16916 // s0 qnan: min(s1, s2)
16917 // s1 qnan: min(s0, s2)
16918 // s2 qnan: min(s0, s1)
16919 const MachineFunction &MF = DAG.getMachineFunction();
16920 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
16921
16922 // TODO: Check IEEE bit enabled. We can form fmed3 with IEEE=0 regardless of
16923 // whether the input is a signaling nan if op0 is fmaximum or fmaximumnum. We
16924 // can only form if op0 is fmaxnum_ieee if IEEE=1.
16925 EVT VT = Op0.getValueType();
16926 if (Info->getMode().DX10Clamp) {
16927 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
16928 // hardware fmed3 behavior converting to a min.
16929 // FIXME: Should this be allowing -0.0?
16930 if (K1->isOne() && K0->isPosZero())
16931 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
16932 }
16933
16934 // med3 for f16 is only available on gfx9+, and not available for v2f16.
16935 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
16936 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
16937 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
16938 // then give the other result, which is different from med3 with a NaN
16939 // input.
16940 SDValue Var = Op0.getOperand(0);
16941 if (!IsKnownNoNaNs && !DAG.isKnownNeverSNaN(Var))
16942 return SDValue();
16943
16944 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
16945
16946 if ((!K0->hasOneUse() || TII->isInlineConstant(K0->getValueAPF())) &&
16947 (!K1->hasOneUse() || TII->isInlineConstant(K1->getValueAPF()))) {
16948 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), Var,
16949 SDValue(K0, 0), SDValue(K1, 0));
16950 }
16951 }
16952
16953 return SDValue();
16954}
16955
16956/// \return true if the subtarget supports minimum3 and maximum3 with the given
16957/// base min/max opcode \p Opc for type \p VT.
16958static bool supportsMin3Max3(const GCNSubtarget &Subtarget, unsigned Opc,
16959 EVT VT) {
16960 switch (Opc) {
16961 case ISD::FMINNUM:
16962 case ISD::FMAXNUM:
16963 case ISD::FMINNUM_IEEE:
16964 case ISD::FMAXNUM_IEEE:
16965 case ISD::FMINIMUMNUM:
16966 case ISD::FMAXIMUMNUM:
16967 return (VT == MVT::f32) || (VT == MVT::f16 && Subtarget.hasMin3Max3_16()) ||
16968 (VT == MVT::v2f16 && Subtarget.hasMin3Max3PKF16());
16969 case ISD::FMINIMUM:
16970 case ISD::FMAXIMUM:
16971 return (VT == MVT::f32 && Subtarget.hasMinimum3Maximum3F32()) ||
16972 (VT == MVT::f16 && Subtarget.hasMinimum3Maximum3F16()) ||
16973 (VT == MVT::v2f16 && Subtarget.hasMinimum3Maximum3PKF16());
16974 case ISD::SMAX:
16975 case ISD::SMIN:
16976 case ISD::UMAX:
16977 case ISD::UMIN:
16978 return (VT == MVT::i32) || (VT == MVT::i16 && Subtarget.hasMin3Max3_16());
16979 default:
16980 return false;
16981 }
16982
16983 llvm_unreachable("not a min/max opcode");
16984}
16985
16986SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
16987 DAGCombinerInfo &DCI) const {
16988 SelectionDAG &DAG = DCI.DAG;
16989
16990 EVT VT = N->getValueType(0);
16991 unsigned Opc = N->getOpcode();
16992 SDValue Op0 = N->getOperand(0);
16993 SDValue Op1 = N->getOperand(1);
16994
16995 // Only do this if the inner op has one use since this will just increases
16996 // register pressure for no benefit.
16997
16998 if (supportsMin3Max3(*Subtarget, Opc, VT)) {
16999 auto IsTreeWithCombinableChildren = [Opc](SDValue Op) {
17000 return (Op.getOperand(0).getOpcode() == Opc &&
17001 Op.getOperand(0).hasOneUse()) ||
17002 (Op.getOperand(1).getOpcode() == Opc &&
17003 Op.getOperand(1).hasOneUse());
17004 };
17005
17006 bool CanTreeCombineApply = Op0.getOpcode() == Opc && Op0.hasOneUse() &&
17007 Op1.getOpcode() == Opc && Op1.hasOneUse();
17008 bool HasCombinableTreeChild =
17009 CanTreeCombineApply && (IsTreeWithCombinableChildren(Op0) ||
17010 IsTreeWithCombinableChildren(Op1));
17011
17012 // Tree reduction: when both operands are the same min/max op, restructure
17013 // to keep a 2-op node on top so higher tree levels can still combine.
17014 //
17015 // max(max(a, b), max(c, d)) -> max(max3(a, b, c), d)
17016 // min(min(a, b), min(c, d)) -> min(min3(a, b, c), d)
17017 //
17018 // Defer when either inner op is a tree node with combinable children.
17019 if (CanTreeCombineApply && !HasCombinableTreeChild) {
17020 SDLoc DL(N);
17021 // Keep the flags that are common to all three nodes. In particular
17022 // dropping nnan would pessimize the lowering of the new 2-op node.
17023 SDNodeFlags Flags = N->getFlags() & Op0->getFlags() & Op1->getFlags();
17024 SDValue Inner = DAG.getNode(
17026 {Op0.getOperand(0), Op0.getOperand(1), Op1.getOperand(0)}, Flags);
17027 return DAG.getNode(Opc, DL, VT, Inner, Op1.getOperand(1), Flags);
17028 }
17029
17030 // max(max(a, b), c) -> max3(a, b, c)
17031 // min(min(a, b), c) -> min3(a, b, c)
17032 // Deferred when Op0 is a tree node with combinable children.
17033 if (Op0.getOpcode() == Opc && Op0.hasOneUse() && !HasCombinableTreeChild) {
17034 SDLoc DL(N);
17035 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), DL, N->getValueType(0),
17036 {Op0.getOperand(0), Op0.getOperand(1), Op1},
17037 N->getFlags() & Op0->getFlags());
17038 }
17039
17040 // Try commuted.
17041 // max(a, max(b, c)) -> max3(a, b, c)
17042 // min(a, min(b, c)) -> min3(a, b, c)
17043 // Deferred when Op1 is a tree node with combinable children.
17044 if (Op1.getOpcode() == Opc && Op1.hasOneUse() && !HasCombinableTreeChild) {
17045 SDLoc DL(N);
17046 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), DL, N->getValueType(0),
17047 {Op0, Op1.getOperand(0), Op1.getOperand(1)},
17048 N->getFlags() & Op1->getFlags());
17049 }
17050 }
17051
17052 // umin(sffbh(x), bitwidth) -> sffbh(x) if x is known to be not 0 or -1.
17053 SDValue FfbhSrc;
17054 uint64_t Clamp = 0;
17055 if (Opc == ISD::UMIN &&
17056 sd_match(Op0,
17058 sd_match(Op1, m_ConstInt(Clamp))) {
17059 unsigned BitWidth = FfbhSrc.getValueType().getScalarSizeInBits();
17060 if (Clamp >= BitWidth) {
17061 KnownBits Known = DAG.computeKnownBits(FfbhSrc);
17062 if (Known.isNonZero() && Known.Zero.getBoolValue())
17063 return Op0;
17064 }
17065 }
17066
17067 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
17068 // max(min(x, K0), K1), K1 < K0 -> med3(x, K1, K0)
17069 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
17070 if (SDValue Med3 = performIntMed3ImmCombine(
17071 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), true))
17072 return Med3;
17073 }
17074 if (Opc == ISD::SMAX && Op0.getOpcode() == ISD::SMIN && Op0.hasOneUse()) {
17075 if (SDValue Med3 = performIntMed3ImmCombine(
17076 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, true))
17077 return Med3;
17078 }
17079
17080 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
17081 if (SDValue Med3 = performIntMed3ImmCombine(
17082 DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), false))
17083 return Med3;
17084 }
17085 if (Opc == ISD::UMAX && Op0.getOpcode() == ISD::UMIN && Op0.hasOneUse()) {
17086 if (SDValue Med3 = performIntMed3ImmCombine(
17087 DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, false))
17088 return Med3;
17089 }
17090
17091 // if !is_snan(x):
17092 // fminnum(fmaxnum(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17093 // fminnum_ieee(fmaxnum_ieee(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17094 // fminnumnum(fmaxnumnum(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17095 // fmin_legacy(fmax_legacy(x, K0), K1), K0 < K1 -> fmed3(x, K0, K1)
17096 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
17099 (Opc == AMDGPUISD::FMIN_LEGACY &&
17100 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
17101 (VT == MVT::f32 || VT == MVT::f64 ||
17102 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
17103 (VT == MVT::bf16 && Subtarget->hasBF16PackedInsts()) ||
17104 (VT == MVT::v2bf16 && Subtarget->hasBF16PackedInsts()) ||
17105 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
17106 Op0.hasOneUse()) {
17107 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1,
17108 N->getFlags().hasNoNaNs()))
17109 return Res;
17110 }
17111
17112 // Prefer fminnum_ieee over fminimum. For gfx950, minimum/maximum are legal
17113 // for some types, but at a higher cost since it's implemented with a 3
17114 // operand form.
17115 const SDNodeFlags Flags = N->getFlags();
17116 if ((Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM) && Flags.hasNoNaNs() &&
17117 !Subtarget->hasIEEEMinimumMaximumInsts() &&
17119 unsigned NewOpc =
17121 return DAG.getNode(NewOpc, SDLoc(N), VT, Op0, Op1, Flags);
17122 }
17123
17124 return SDValue();
17125}
17126
17130 // FIXME: Should this be allowing -0.0?
17131 return (CA->isPosZero() && CB->isOne()) ||
17132 (CA->isOne() && CB->isPosZero());
17133 }
17134 }
17135
17136 return false;
17137}
17138
17139// FIXME: Should only worry about snans for version with chain.
17140SDValue SITargetLowering::performFMed3Combine(SDNode *N,
17141 DAGCombinerInfo &DCI) const {
17142 EVT VT = N->getValueType(0);
17143 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
17144 // NaNs. With a NaN input, the order of the operands may change the result.
17145
17146 SelectionDAG &DAG = DCI.DAG;
17147 SDLoc SL(N);
17148
17149 SDValue Src0 = N->getOperand(0);
17150 SDValue Src1 = N->getOperand(1);
17151 SDValue Src2 = N->getOperand(2);
17152
17153 if (isClampZeroToOne(Src0, Src1)) {
17154 // const_a, const_b, x -> clamp is safe in all cases including signaling
17155 // nans.
17156 // FIXME: Should this be allowing -0.0?
17157 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
17158 }
17159
17160 const MachineFunction &MF = DAG.getMachineFunction();
17161 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
17162
17163 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
17164 // handling no dx10-clamp?
17165 if (Info->getMode().DX10Clamp) {
17166 // If NaNs is clamped to 0, we are free to reorder the inputs.
17167
17168 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
17169 std::swap(Src0, Src1);
17170
17171 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
17172 std::swap(Src1, Src2);
17173
17174 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
17175 std::swap(Src0, Src1);
17176
17177 if (isClampZeroToOne(Src1, Src2))
17178 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
17179 }
17180
17181 return SDValue();
17182}
17183
17184SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
17185 DAGCombinerInfo &DCI) const {
17186 SDValue Src0 = N->getOperand(0);
17187 SDValue Src1 = N->getOperand(1);
17188 if (Src0.isUndef() && Src1.isUndef())
17189 return DCI.DAG.getUNDEF(N->getValueType(0));
17190 return SDValue();
17191}
17192
17193/// V_CVT_SCALEF32_* conversions to a narrow format only read the exponent
17194/// field of their f32 scale operand.
17195SDValue
17196SITargetLowering::performExponentOnlyScaleCombine(SDNode *N,
17197 DAGCombinerInfo &DCI) const {
17198 std::optional<unsigned> ScaleArgIdx =
17199 AMDGPU::getExponentOnlyScaleArgIdx(N->getConstantOperandVal(0));
17200 if (!ScaleArgIdx)
17201 return SDValue();
17202
17203 // Operand 0 is the intrinsic ID.
17204 unsigned OpIdx = *ScaleArgIdx + 1;
17205 SelectionDAG &DAG = DCI.DAG;
17206 SDValue Scale = N->getOperand(OpIdx);
17208
17209 if (SDValue DemandedScale =
17210 SimplifyMultipleUseDemandedBits(Scale, Demanded, DAG)) {
17211 SmallVector<SDValue> Ops(N->ops());
17212 Ops[OpIdx] = DemandedScale;
17213 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getVTList(), Ops);
17214 }
17215
17216 if (SimplifyDemandedBits(Scale, Demanded, DCI))
17217 return SDValue(N, 0);
17218
17219 return SDValue();
17220}
17221
17222// Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
17223// expanded into a set of cmp/select instructions.
17225 unsigned NumElem,
17226 bool IsDivergentIdx,
17227 const GCNSubtarget *Subtarget) {
17228 if (Subtarget->getCLOpts().use_divergent_register_indexing)
17229 return false;
17230
17231 unsigned VecSize = EltSize * NumElem;
17232
17233 // Sub-dword vectors of size 2 dword or less have better implementation.
17234 if (VecSize <= 64 && EltSize < 32)
17235 return false;
17236
17237 // Always expand the rest of sub-dword instructions, otherwise it will be
17238 // lowered via memory.
17239 if (EltSize < 32)
17240 return true;
17241
17242 // Always do this if var-idx is divergent, otherwise it will become a loop.
17243 if (IsDivergentIdx)
17244 return true;
17245
17246 // Large vectors would yield too many compares and v_cndmask_b32 instructions.
17247 unsigned NumInsts = NumElem /* Number of compares */ +
17248 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
17249
17250 // On some architectures (GFX9) movrel is not available and it's better
17251 // to expand.
17252 if (Subtarget->useVGPRIndexMode())
17253 return NumInsts <= 16;
17254
17255 // If movrel is available, use it instead of expanding for vector of 8
17256 // elements.
17257 if (Subtarget->hasMovrel())
17258 return NumInsts <= 15;
17259
17260 return true;
17261}
17262
17264 SDValue Idx = N->getOperand(N->getNumOperands() - 1);
17265 if (isa<ConstantSDNode>(Idx))
17266 return false;
17267
17268 SDValue Vec = N->getOperand(0);
17269 EVT VecVT = Vec.getValueType();
17270 EVT EltVT = VecVT.getVectorElementType();
17271 unsigned EltSize = EltVT.getSizeInBits();
17272 unsigned NumElem = VecVT.getVectorNumElements();
17273
17275 EltSize, NumElem, Idx->isDivergent(), getSubtarget());
17276}
17277
17278SDValue
17279SITargetLowering::performExtractVectorEltCombine(SDNode *N,
17280 DAGCombinerInfo &DCI) const {
17281 SDValue Vec = N->getOperand(0);
17282 SelectionDAG &DAG = DCI.DAG;
17283
17284 EVT VecVT = Vec.getValueType();
17285 EVT VecEltVT = VecVT.getVectorElementType();
17286 EVT ResVT = N->getValueType(0);
17287
17288 unsigned VecSize = VecVT.getSizeInBits();
17289 unsigned VecEltSize = VecEltVT.getSizeInBits();
17290
17291 if ((Vec.getOpcode() == ISD::FNEG || Vec.getOpcode() == ISD::FABS) &&
17293 SDLoc SL(N);
17294 SDValue Idx = N->getOperand(1);
17295 SDValue Elt =
17296 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec.getOperand(0), Idx);
17297 return DAG.getNode(Vec.getOpcode(), SL, ResVT, Elt);
17298 }
17299
17300 // (extract_vector_element (and {y0, y1}, (build_vector 0x1f, 0x1f)), index)
17301 // -> (and (extract_vector_element {y0, y1}, index), 0x1f)
17302 // There are optimisations to transform 64-bit shifts into 32-bit shifts
17303 // depending on the shift operand. See e.g. performSraCombine().
17304 // This combine ensures that the optimisation is compatible with v2i32
17305 // legalised AND.
17306 if (VecVT == MVT::v2i32 && Vec->getOpcode() == ISD::AND &&
17307 Vec->getOperand(1)->getOpcode() == ISD::BUILD_VECTOR) {
17308
17310 if (!C || C->getZExtValue() != 0x1f)
17311 return SDValue();
17312
17313 SDLoc SL(N);
17314 SDValue AndMask = DAG.getConstant(0x1f, SL, MVT::i32);
17315 SDValue EVE = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32,
17316 Vec->getOperand(0), N->getOperand(1));
17317 SDValue A = DAG.getNode(ISD::AND, SL, MVT::i32, EVE, AndMask);
17318 DAG.ReplaceAllUsesWith(N, A.getNode());
17319 }
17320
17321 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
17322 // =>
17323 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
17324 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
17325 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
17326 if (Vec.hasOneUse() && DCI.isBeforeLegalize() && VecEltVT == ResVT) {
17327 SDLoc SL(N);
17328 SDValue Idx = N->getOperand(1);
17329 unsigned Opc = Vec.getOpcode();
17330
17331 switch (Opc) {
17332 default:
17333 break;
17334 // TODO: Support other binary operations.
17335 case ISD::FADD:
17336 case ISD::FSUB:
17337 case ISD::FMUL:
17338 case ISD::ADD:
17339 case ISD::UMIN:
17340 case ISD::UMAX:
17341 case ISD::SMIN:
17342 case ISD::SMAX:
17343 case ISD::FMAXNUM:
17344 case ISD::FMINNUM:
17345 case ISD::FMAXNUM_IEEE:
17346 case ISD::FMINNUM_IEEE:
17347 case ISD::FMAXIMUM:
17348 case ISD::FMINIMUM: {
17349 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
17350 Vec.getOperand(0), Idx);
17351 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
17352 Vec.getOperand(1), Idx);
17353
17354 DCI.AddToWorklist(Elt0.getNode());
17355 DCI.AddToWorklist(Elt1.getNode());
17356 return DAG.getNode(Opc, SL, ResVT, Elt0, Elt1, Vec->getFlags());
17357 }
17358 }
17359 }
17360
17361 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
17363 SDLoc SL(N);
17364 SDValue Idx = N->getOperand(1);
17365 SDValue V;
17366 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
17367 SDValue IC = DAG.getVectorIdxConstant(I, SL);
17368 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec, IC);
17369 if (I == 0)
17370 V = Elt;
17371 else
17372 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
17373 }
17374 return V;
17375 }
17376
17377 // EXTRACT_VECTOR_ELT (v2i32 bitcast (i64/f64:k), Idx)
17378 // =>
17379 // i32:Lo(k) if Idx == 0, or
17380 // i32:Hi(k) if Idx == 1
17381 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
17382 if (Vec.getOpcode() == ISD::BITCAST && VecVT == MVT::v2i32 && Idx) {
17383 SDLoc SL(N);
17384 SDValue PeekThrough = Vec.getOperand(0);
17385 auto *KImm = dyn_cast<ConstantSDNode>(PeekThrough);
17386 if (KImm && KImm->getValueType(0).getSizeInBits() == 64) {
17387 uint64_t KImmValue = KImm->getZExtValue();
17388 return DAG.getConstant(
17389 (KImmValue >> (32 * Idx->getZExtValue())) & 0xffffffff, SL, MVT::i32);
17390 }
17391 auto *KFPImm = dyn_cast<ConstantFPSDNode>(PeekThrough);
17392 if (KFPImm && KFPImm->getValueType(0).getSizeInBits() == 64) {
17393 uint64_t KFPImmValue =
17394 KFPImm->getValueAPF().bitcastToAPInt().getZExtValue();
17395 return DAG.getConstant((KFPImmValue >> (32 * Idx->getZExtValue())) &
17396 0xffffffff,
17397 SL, MVT::i32);
17398 }
17399 }
17400
17401 if (!DCI.isBeforeLegalize())
17402 return SDValue();
17403
17404 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
17405 // elements. This exposes more load reduction opportunities by replacing
17406 // multiple small extract_vector_elements with a single 32-bit extract.
17407 if (isa<MemSDNode>(Vec) && VecEltSize <= 16 && VecEltVT.isByteSized() &&
17408 VecSize > 32 && VecSize % 32 == 0 && Idx) {
17409 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
17410
17411 unsigned BitIndex = Idx->getZExtValue() * VecEltSize;
17412 unsigned EltIdx = BitIndex / 32;
17413 unsigned LeftoverBitIdx = BitIndex % 32;
17414 SDLoc SL(N);
17415
17416 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
17417 DCI.AddToWorklist(Cast.getNode());
17418
17419 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
17420 DAG.getConstant(EltIdx, SL, MVT::i32));
17421 DCI.AddToWorklist(Elt.getNode());
17422 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
17423 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
17424 DCI.AddToWorklist(Srl.getNode());
17425
17426 EVT VecEltAsIntVT = VecEltVT.changeTypeToInteger();
17427 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VecEltAsIntVT, Srl);
17428 DCI.AddToWorklist(Trunc.getNode());
17429
17430 if (VecEltVT == ResVT) {
17431 return DAG.getNode(ISD::BITCAST, SL, VecEltVT, Trunc);
17432 }
17433
17434 assert(ResVT.isScalarInteger());
17435 return DAG.getAnyExtOrTrunc(Trunc, SL, ResVT);
17436 }
17437
17438 return SDValue();
17439}
17440
17441SDValue
17442SITargetLowering::performInsertVectorEltCombine(SDNode *N,
17443 DAGCombinerInfo &DCI) const {
17444 SDValue Vec = N->getOperand(0);
17445 SDValue Idx = N->getOperand(2);
17446 EVT VecVT = Vec.getValueType();
17447 EVT EltVT = VecVT.getVectorElementType();
17448
17449 // INSERT_VECTOR_ELT (<n x e>, var-idx)
17450 // => BUILD_VECTOR n x select (e, const-idx)
17451 // 16-bit elements are left to lowerINSERT_VECTOR_ELT, which is cheaper.
17453 (EltVT.getSizeInBits() == 16 &&
17455 return SDValue();
17456
17457 SelectionDAG &DAG = DCI.DAG;
17458 SDLoc SL(N);
17459 SDValue Ins = N->getOperand(1);
17460 EVT IdxVT = Idx.getValueType();
17461
17463 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
17464 SDValue IC = DAG.getConstant(I, SL, IdxVT);
17465 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
17466 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
17467 Ops.push_back(V);
17468 }
17469
17470 return DAG.getBuildVector(VecVT, SL, Ops);
17471}
17472
17473/// Return the source of an fp_extend from f16 to f32, or a converted FP
17474/// constant.
17476 if (Src.getOpcode() == ISD::FP_EXTEND &&
17477 Src.getOperand(0).getValueType() == MVT::f16) {
17478 return Src.getOperand(0);
17479 }
17480
17481 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Src)) {
17482 APFloat Val = CFP->getValueAPF();
17483 bool LosesInfo = true;
17485 if (!LosesInfo)
17486 return DAG.getConstantFP(Val, SDLoc(Src), MVT::f16);
17487 }
17488
17489 return SDValue();
17490}
17491
17492SDValue SITargetLowering::performFPRoundCombine(SDNode *N,
17493 DAGCombinerInfo &DCI) const {
17494 assert(Subtarget->has16BitInsts() && !Subtarget->hasMed3_16() &&
17495 "combine only useful on gfx8");
17496
17497 SDValue TruncSrc = N->getOperand(0);
17498 EVT VT = N->getValueType(0);
17499 if (VT != MVT::f16)
17500 return SDValue();
17501
17502 if (TruncSrc.getOpcode() != AMDGPUISD::FMED3 ||
17503 TruncSrc.getValueType() != MVT::f32 || !TruncSrc.hasOneUse())
17504 return SDValue();
17505
17506 SelectionDAG &DAG = DCI.DAG;
17507 SDLoc SL(N);
17508
17509 // Optimize f16 fmed3 pattern performed on f32. On gfx8 there is no f16 fmed3,
17510 // and expanding it with min/max saves 1 instruction vs. casting to f32 and
17511 // casting back.
17512
17513 // fptrunc (f32 (fmed3 (fpext f16:a, fpext f16:b, fpext f16:c))) =>
17514 // fmin(fmax(a, b), fmax(fmin(a, b), c))
17515 SDValue A = strictFPExtFromF16(DAG, TruncSrc.getOperand(0));
17516 if (!A)
17517 return SDValue();
17518
17519 SDValue B = strictFPExtFromF16(DAG, TruncSrc.getOperand(1));
17520 if (!B)
17521 return SDValue();
17522
17523 SDValue C = strictFPExtFromF16(DAG, TruncSrc.getOperand(2));
17524 if (!C)
17525 return SDValue();
17526
17527 // This changes signaling nan behavior. If an input is a signaling nan, it
17528 // would have been quieted by the fpext originally. We don't care because
17529 // these are unconstrained ops. If we needed to insert quieting canonicalizes
17530 // we would be worse off than just doing the promotion.
17531 SDValue A1 = DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, A, B);
17532 SDValue B1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A, B);
17533 SDValue C1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A1, C);
17534 return DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, B1, C1);
17535}
17536
17537unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
17538 const SDNode *N0,
17539 const SDNode *N1) const {
17540 EVT VT = N0->getValueType(0);
17541
17542 // Only do this if we are not trying to support denormals. v_mad_f32 does not
17543 // support denormals ever.
17544 if (((VT == MVT::f32 &&
17546 (VT == MVT::f16 && Subtarget->hasMadF16() &&
17549 return ISD::FMAD;
17550
17551 if (N0->getFlags().hasAllowContract() && N1->getFlags().hasAllowContract() &&
17553 return ISD::FMA;
17554 }
17555
17556 return 0;
17557}
17558
17559// For a reassociatable opcode perform:
17560// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
17561SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
17562 SelectionDAG &DAG) const {
17563 EVT VT = N->getValueType(0);
17564 if (VT != MVT::i32 && VT != MVT::i64)
17565 return SDValue();
17566
17567 if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
17568 return SDValue();
17569
17570 unsigned Opc = N->getOpcode();
17571 SDValue Op0 = N->getOperand(0);
17572 SDValue Op1 = N->getOperand(1);
17573
17574 if (!(Op0->isDivergent() ^ Op1->isDivergent()))
17575 return SDValue();
17576
17577 if (Op0->isDivergent())
17578 std::swap(Op0, Op1);
17579
17580 if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
17581 return SDValue();
17582
17583 SDValue Op2 = Op1.getOperand(1);
17584 Op1 = Op1.getOperand(0);
17585 if (!(Op1->isDivergent() ^ Op2->isDivergent()))
17586 return SDValue();
17587
17588 if (Op1->isDivergent())
17589 std::swap(Op1, Op2);
17590
17591 SDLoc SL(N);
17592 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
17593 return DAG.getNode(Opc, SL, VT, Add1, Op2);
17594}
17595
17596static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, EVT VT,
17597 SDValue N0, SDValue N1, SDValue N2, bool Signed) {
17599 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
17600 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
17601 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
17602}
17603
17604// Fold
17605// y = lshr i64 x, 32
17606// res = add (mul i64 y, Const), x where "Const" is a 64-bit constant
17607// with Const.hi == -1
17608// To
17609// res = mad_u64_u32 y.lo ,Const.lo, x.lo
17611 SDValue MulLHS, SDValue MulRHS,
17612 SDValue AddRHS) {
17613 if (MulRHS.getOpcode() == ISD::SRL)
17614 std::swap(MulLHS, MulRHS);
17615
17616 if (MulLHS.getValueType() != MVT::i64 || MulLHS.getOpcode() != ISD::SRL)
17617 return SDValue();
17618
17619 ConstantSDNode *ShiftVal = dyn_cast<ConstantSDNode>(MulLHS.getOperand(1));
17620 if (!ShiftVal || ShiftVal->getAsZExtVal() != 32 ||
17621 MulLHS.getOperand(0) != AddRHS)
17622 return SDValue();
17623
17625 if (!Const || Hi_32(Const->getZExtValue()) != uint32_t(-1))
17626 return SDValue();
17627
17628 SDValue ConstMul =
17629 DAG.getConstant(Lo_32(Const->getZExtValue()), SL, MVT::i32);
17630 return getMad64_32(DAG, SL, MVT::i64,
17631 DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS), ConstMul,
17632 DAG.getZeroExtendInReg(AddRHS, SL, MVT::i32), false);
17633}
17634
17635// Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
17636// multiplies, if any.
17637//
17638// Full 64-bit multiplies that feed into an addition are lowered here instead
17639// of using the generic expansion. The generic expansion ends up with
17640// a tree of ADD nodes that prevents us from using the "add" part of the
17641// MAD instruction. The expansion produced here results in a chain of ADDs
17642// instead of a tree.
17643SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
17644 DAGCombinerInfo &DCI) const {
17645 assert(N->isAnyAdd());
17646
17647 SelectionDAG &DAG = DCI.DAG;
17648 EVT VT = N->getValueType(0);
17649 SDLoc SL(N);
17650 SDValue LHS = N->getOperand(0);
17651 SDValue RHS = N->getOperand(1);
17652
17653 if (VT.isVector())
17654 return SDValue();
17655
17656 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
17657 // result in scalar registers for uniform values.
17658 if (!N->isDivergent() && Subtarget->hasSMulHi())
17659 return SDValue();
17660
17661 unsigned NumBits = VT.getScalarSizeInBits();
17662 if (NumBits <= 32 || NumBits > 64)
17663 return SDValue();
17664
17665 if (LHS.getOpcode() != ISD::MUL) {
17666 assert(RHS.getOpcode() == ISD::MUL);
17667 std::swap(LHS, RHS);
17668 }
17669
17670 // Avoid the fold if it would unduly increase the number of multiplies due to
17671 // multiple uses, except on hardware with full-rate multiply-add (which is
17672 // part of full-rate 64-bit ops).
17673 if (!Subtarget->hasFullRate64Ops()) {
17674 unsigned NumUsers = 0;
17675 for (SDNode *User : LHS->users()) {
17676 // There is a use that does not feed into addition, so the multiply can't
17677 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
17678 if (!User->isAnyAdd())
17679 return SDValue();
17680
17681 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
17682 // MUL + 3xADD + 3xADDC over 3xMAD.
17683 ++NumUsers;
17684 if (NumUsers >= 3)
17685 return SDValue();
17686 }
17687 }
17688
17689 SDValue MulLHS = LHS.getOperand(0);
17690 SDValue MulRHS = LHS.getOperand(1);
17691 SDValue AddRHS = RHS;
17692
17693 if (SDValue FoldedMAD = tryFoldMADwithSRL(DAG, SL, MulLHS, MulRHS, AddRHS))
17694 return FoldedMAD;
17695
17696 // Always check whether operands are small unsigned values, since that
17697 // knowledge is useful in more cases. Check for small signed values only if
17698 // doing so can unlock a shorter code sequence.
17699 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
17700 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
17701
17702 bool MulSignedLo = false;
17703 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
17704 MulSignedLo =
17705 numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32;
17706 }
17707
17708 // The operands and final result all have the same number of bits. If
17709 // operands need to be extended, they can be extended with garbage. The
17710 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
17711 // truncated away in the end.
17712 if (VT != MVT::i64) {
17713 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
17714 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
17715 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
17716 }
17717
17718 // The basic code generated is conceptually straightforward. Pseudo code:
17719 //
17720 // accum = mad_64_32 lhs.lo, rhs.lo, accum
17721 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
17722 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
17723 //
17724 // The second and third lines are optional, depending on whether the factors
17725 // are {sign,zero}-extended or not.
17726 //
17727 // The actual DAG is noisier than the pseudo code, but only due to
17728 // instructions that disassemble values into low and high parts, and
17729 // assemble the final result.
17730 SDValue One = DAG.getConstant(1, SL, MVT::i32);
17731
17732 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
17733 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
17734 SDValue Accum =
17735 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
17736
17737 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
17738 auto [AccumLo, AccumHi] = DAG.SplitScalar(Accum, SL, MVT::i32, MVT::i32);
17739
17740 if (!MulLHSUnsigned32) {
17741 auto MulLHSHi =
17742 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
17743 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
17744 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
17745 }
17746
17747 if (!MulRHSUnsigned32) {
17748 auto MulRHSHi =
17749 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
17750 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
17751 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
17752 }
17753
17754 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
17755 Accum = DAG.getBitcast(MVT::i64, Accum);
17756 }
17757
17758 if (VT != MVT::i64)
17759 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
17760 return Accum;
17761}
17762
17763SDValue
17764SITargetLowering::foldAddSub64WithZeroLowBitsTo32(SDNode *N,
17765 DAGCombinerInfo &DCI) const {
17766 SDValue RHS = N->getOperand(1);
17767 auto *CRHS = dyn_cast<ConstantSDNode>(RHS);
17768 if (!CRHS)
17769 return SDValue();
17770
17771 // TODO: Worth using computeKnownBits? Maybe expensive since it's so
17772 // common.
17773 uint64_t Val = CRHS->getZExtValue();
17774 if (countr_zero(Val) >= 32) {
17775 SelectionDAG &DAG = DCI.DAG;
17776 SDLoc SL(N);
17777 SDValue LHS = N->getOperand(0);
17778
17779 // Avoid carry machinery if we know the low half of the add does not
17780 // contribute to the final result.
17781 //
17782 // add i64:x, K if computeTrailingZeros(K) >= 32
17783 // => build_pair (add x.hi, K.hi), x.lo
17784
17785 // Breaking the 64-bit add here with this strange constant is unlikely
17786 // to interfere with addressing mode patterns.
17787
17788 SDValue Hi = getHiHalf64(LHS, DAG);
17789 SDValue ConstHi32 = DAG.getConstant(Hi_32(Val), SL, MVT::i32);
17790 unsigned Opcode = N->getOpcode();
17791 if (Opcode == ISD::PTRADD)
17792 Opcode = ISD::ADD;
17793 SDValue AddHi =
17794 DAG.getNode(Opcode, SL, MVT::i32, Hi, ConstHi32, N->getFlags());
17795
17796 SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
17797 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64, Lo, AddHi);
17798 }
17799
17800 return SDValue();
17801}
17802
17803// Collect the ultimate src of each of the mul node's operands, and confirm
17804// each operand is 8 bytes.
17805static std::optional<ByteProvider<SDValue>>
17806handleMulOperand(const SDValue &MulOperand) {
17807 auto Byte0 = calculateByteProvider(MulOperand, 0, 0);
17808 if (!Byte0 || Byte0->isConstantZero()) {
17809 return std::nullopt;
17810 }
17811 auto Byte1 = calculateByteProvider(MulOperand, 1, 0);
17812 if (Byte1 && !Byte1->isConstantZero()) {
17813 return std::nullopt;
17814 }
17815 return Byte0;
17816}
17817
17818static unsigned addPermMasks(unsigned First, unsigned Second) {
17819 unsigned FirstCs = First & 0x0c0c0c0c;
17820 unsigned SecondCs = Second & 0x0c0c0c0c;
17821 unsigned FirstNoCs = First & ~0x0c0c0c0c;
17822 unsigned SecondNoCs = Second & ~0x0c0c0c0c;
17823
17824 assert((FirstCs & 0xFF) | (SecondCs & 0xFF));
17825 assert((FirstCs & 0xFF00) | (SecondCs & 0xFF00));
17826 assert((FirstCs & 0xFF0000) | (SecondCs & 0xFF0000));
17827 assert((FirstCs & 0xFF000000) | (SecondCs & 0xFF000000));
17828
17829 return (FirstNoCs | SecondNoCs) | (FirstCs & SecondCs);
17830}
17831
17832struct DotSrc {
17834 int64_t PermMask;
17836};
17837
17841 SmallVectorImpl<DotSrc> &Src1s, int Step) {
17842
17843 assert(Src0.Src.has_value() && Src1.Src.has_value());
17844 // Src0s and Src1s are empty, just place arbitrarily.
17845 if (Step == 0) {
17846 Src0s.push_back({*Src0.Src, ((Src0.SrcOffset % 4) << 24) + 0x0c0c0c,
17847 Src0.SrcOffset / 4});
17848 Src1s.push_back({*Src1.Src, ((Src1.SrcOffset % 4) << 24) + 0x0c0c0c,
17849 Src1.SrcOffset / 4});
17850 return;
17851 }
17852
17853 for (int BPI = 0; BPI < 2; BPI++) {
17854 std::pair<ByteProvider<SDValue>, ByteProvider<SDValue>> BPP = {Src0, Src1};
17855 if (BPI == 1) {
17856 BPP = {Src1, Src0};
17857 }
17858 unsigned ZeroMask = 0x0c0c0c0c;
17859 unsigned FMask = 0xFF << (8 * (3 - Step));
17860
17861 unsigned FirstMask =
17862 (BPP.first.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask);
17863 unsigned SecondMask =
17864 (BPP.second.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask);
17865 // Attempt to find Src vector which contains our SDValue, if so, add our
17866 // perm mask to the existing one. If we are unable to find a match for the
17867 // first SDValue, attempt to find match for the second.
17868 int FirstGroup = -1;
17869 for (int I = 0; I < 2; I++) {
17870 SmallVectorImpl<DotSrc> &Srcs = I == 0 ? Src0s : Src1s;
17871 auto MatchesFirst = [&BPP](DotSrc &IterElt) {
17872 return IterElt.SrcOp == *BPP.first.Src &&
17873 (IterElt.DWordOffset == (BPP.first.SrcOffset / 4));
17874 };
17875
17876 auto *Match = llvm::find_if(Srcs, MatchesFirst);
17877 if (Match != Srcs.end()) {
17878 Match->PermMask = addPermMasks(FirstMask, Match->PermMask);
17879 FirstGroup = I;
17880 break;
17881 }
17882 }
17883 if (FirstGroup != -1) {
17884 SmallVectorImpl<DotSrc> &Srcs = FirstGroup == 1 ? Src0s : Src1s;
17885 auto MatchesSecond = [&BPP](DotSrc &IterElt) {
17886 return IterElt.SrcOp == *BPP.second.Src &&
17887 (IterElt.DWordOffset == (BPP.second.SrcOffset / 4));
17888 };
17889 auto *Match = llvm::find_if(Srcs, MatchesSecond);
17890 if (Match != Srcs.end()) {
17891 Match->PermMask = addPermMasks(SecondMask, Match->PermMask);
17892 } else
17893 Srcs.push_back({*BPP.second.Src, SecondMask, BPP.second.SrcOffset / 4});
17894 return;
17895 }
17896 }
17897
17898 // If we have made it here, then we could not find a match in Src0s or Src1s
17899 // for either Src0 or Src1, so just place them arbitrarily.
17900
17901 unsigned ZeroMask = 0x0c0c0c0c;
17902 unsigned FMask = 0xFF << (8 * (3 - Step));
17903
17904 Src0s.push_back(
17905 {*Src0.Src,
17906 ((Src0.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask)),
17907 Src0.SrcOffset / 4});
17908 Src1s.push_back(
17909 {*Src1.Src,
17910 ((Src1.SrcOffset % 4) << (8 * (3 - Step)) | (ZeroMask & ~FMask)),
17911 Src1.SrcOffset / 4});
17912}
17913
17915 SmallVectorImpl<DotSrc> &Srcs, bool IsSigned,
17916 bool IsAny) {
17917
17918 // If we just have one source, just permute it accordingly.
17919 if (Srcs.size() == 1) {
17920 auto *Elt = Srcs.begin();
17921 auto EltOp = getDWordFromOffset(DAG, SL, Elt->SrcOp, Elt->DWordOffset);
17922
17923 // v_perm will produce the original value
17924 if (Elt->PermMask == 0x3020100)
17925 return EltOp;
17926
17927 return DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltOp, EltOp,
17928 DAG.getConstant(Elt->PermMask, SL, MVT::i32));
17929 }
17930
17931 auto *FirstElt = Srcs.begin();
17932 auto *SecondElt = std::next(FirstElt);
17933
17935
17936 // If we have multiple sources in the chain, combine them via perms (using
17937 // calculated perm mask) and Ors.
17938 while (true) {
17939 auto FirstMask = FirstElt->PermMask;
17940 auto SecondMask = SecondElt->PermMask;
17941
17942 unsigned FirstCs = FirstMask & 0x0c0c0c0c;
17943 unsigned FirstPlusFour = FirstMask | 0x04040404;
17944 // 0x0c + 0x04 = 0x10, so anding with 0x0F will produced 0x00 for any
17945 // original 0x0C.
17946 FirstMask = (FirstPlusFour & 0x0F0F0F0F) | FirstCs;
17947
17948 auto PermMask = addPermMasks(FirstMask, SecondMask);
17949 auto FirstVal =
17950 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
17951 auto SecondVal =
17952 getDWordFromOffset(DAG, SL, SecondElt->SrcOp, SecondElt->DWordOffset);
17953
17954 Perms.push_back(DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, FirstVal,
17955 SecondVal,
17956 DAG.getConstant(PermMask, SL, MVT::i32)));
17957
17958 FirstElt = std::next(SecondElt);
17959 if (FirstElt == Srcs.end())
17960 break;
17961
17962 SecondElt = std::next(FirstElt);
17963 // If we only have a FirstElt, then just combine that into the cumulative
17964 // source node.
17965 if (SecondElt == Srcs.end()) {
17966 auto EltOp =
17967 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
17968
17969 Perms.push_back(
17970 DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltOp, EltOp,
17971 DAG.getConstant(FirstElt->PermMask, SL, MVT::i32)));
17972 break;
17973 }
17974 }
17975
17976 assert(Perms.size() == 1 || Perms.size() == 2);
17977 return Perms.size() == 2
17978 ? DAG.getNode(ISD::OR, SL, MVT::i32, Perms[0], Perms[1])
17979 : Perms[0];
17980}
17981
17982static void fixMasks(SmallVectorImpl<DotSrc> &Srcs, unsigned ChainLength) {
17983 for (auto &[EntryVal, EntryMask, EntryOffset] : Srcs) {
17984 EntryMask = EntryMask >> ((4 - ChainLength) * 8);
17985 auto ZeroMask = ChainLength == 2 ? 0x0c0c0000 : 0x0c000000;
17986 EntryMask += ZeroMask;
17987 }
17988}
17989
17990static bool isMul(const SDValue Op) {
17991 auto Opcode = Op.getOpcode();
17992
17993 return (Opcode == ISD::MUL || Opcode == AMDGPUISD::MUL_U24 ||
17994 Opcode == AMDGPUISD::MUL_I24);
17995}
17996
17997static std::optional<bool>
17999 ByteProvider<SDValue> &Src1, const SDValue &S0Op,
18000 const SDValue &S1Op, const SelectionDAG &DAG) {
18001 // If we both ops are i8s (pre legalize-dag), then the signedness semantics
18002 // of the dot4 is irrelevant.
18003 if (S0Op.getValueSizeInBits() == 8 && S1Op.getValueSizeInBits() == 8)
18004 return false;
18005
18006 auto Known0 = DAG.computeKnownBits(S0Op, 0);
18007 bool S0IsUnsigned = Known0.countMinLeadingZeros() > 0;
18008 bool S0IsSigned = Known0.countMinLeadingOnes() > 0;
18009 auto Known1 = DAG.computeKnownBits(S1Op, 0);
18010 bool S1IsUnsigned = Known1.countMinLeadingZeros() > 0;
18011 bool S1IsSigned = Known1.countMinLeadingOnes() > 0;
18012
18013 assert(!(S0IsUnsigned && S0IsSigned));
18014 assert(!(S1IsUnsigned && S1IsSigned));
18015
18016 // There are 9 possible permutations of
18017 // {S0IsUnsigned, S0IsSigned, S1IsUnsigned, S1IsSigned}
18018
18019 // In two permutations, the sign bits are known to be the same for both Ops,
18020 // so simply return Signed / Unsigned corresponding to the MSB
18021
18022 if ((S0IsUnsigned && S1IsUnsigned) || (S0IsSigned && S1IsSigned))
18023 return S0IsSigned;
18024
18025 // In another two permutations, the sign bits are known to be opposite. In
18026 // this case return std::nullopt to indicate a bad match.
18027
18028 if ((S0IsUnsigned && S1IsSigned) || (S0IsSigned && S1IsUnsigned))
18029 return std::nullopt;
18030
18031 // In the remaining five permutations, we don't know the value of the sign
18032 // bit for at least one Op. Since we have a valid ByteProvider, we know that
18033 // the upper bits must be extension bits. Thus, the only ways for the sign
18034 // bit to be unknown is if it was sign extended from unknown value, or if it
18035 // was any extended. In either case, it is correct to use the signed
18036 // version of the signedness semantics of dot4
18037
18038 // In two of such permutations, we known the sign bit is set for
18039 // one op, and the other is unknown. It is okay to used signed version of
18040 // dot4.
18041 if ((S0IsSigned && !(S1IsSigned || S1IsUnsigned)) ||
18042 ((S1IsSigned && !(S0IsSigned || S0IsUnsigned))))
18043 return true;
18044
18045 // In one such permutation, we don't know either of the sign bits. It is okay
18046 // to used the signed version of dot4.
18047 if ((!(S1IsSigned || S1IsUnsigned) && !(S0IsSigned || S0IsUnsigned)))
18048 return true;
18049
18050 // In two of such permutations, we known the sign bit is unset for
18051 // one op, and the other is unknown. Return std::nullopt to indicate a
18052 // bad match.
18053 if ((S0IsUnsigned && !(S1IsSigned || S1IsUnsigned)) ||
18054 ((S1IsUnsigned && !(S0IsSigned || S0IsUnsigned))))
18055 return std::nullopt;
18056
18057 llvm_unreachable("Fully covered condition");
18058}
18059
18060SDValue SITargetLowering::performAddCombine(SDNode *N,
18061 DAGCombinerInfo &DCI) const {
18062 SelectionDAG &DAG = DCI.DAG;
18063 EVT VT = N->getValueType(0);
18064 SDLoc SL(N);
18065 SDValue LHS = N->getOperand(0);
18066 SDValue RHS = N->getOperand(1);
18067
18068 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
18069 if (Subtarget->hasMad64_32()) {
18070 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
18071 return Folded;
18072 }
18073 }
18074
18075 if (SDValue V = reassociateScalarOps(N, DAG)) {
18076 return V;
18077 }
18078
18079 if (VT == MVT::i64) {
18080 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18081 return Folded;
18082 }
18083
18084 // dot4 produces a 32-bit result, so a wider VT can't be folded.
18085 if (!VT.isVector() && VT.getSizeInBits() <= 32 &&
18086 (isMul(LHS) || isMul(RHS)) && Subtarget->hasDot7Insts() &&
18087 (Subtarget->hasDot1Insts() || Subtarget->hasDot8Insts())) {
18088 SDValue TempNode(N, 0);
18089 std::optional<bool> IsSigned;
18093
18094 // Match the v_dot4 tree, while collecting src nodes.
18095 int ChainLength = 0;
18096 for (int I = 0; I < 4; I++) {
18097 auto MulIdx = isMul(LHS) ? 0 : isMul(RHS) ? 1 : -1;
18098 if (MulIdx == -1)
18099 break;
18100 auto Src0 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(0));
18101 if (!Src0)
18102 break;
18103 auto Src1 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(1));
18104 if (!Src1)
18105 break;
18106
18107 auto IterIsSigned = checkDot4MulSignedness(
18108 TempNode->getOperand(MulIdx), *Src0, *Src1,
18109 TempNode->getOperand(MulIdx)->getOperand(0),
18110 TempNode->getOperand(MulIdx)->getOperand(1), DAG);
18111 if (!IterIsSigned)
18112 break;
18113 if (!IsSigned)
18114 IsSigned = *IterIsSigned;
18115 if (*IterIsSigned != *IsSigned)
18116 break;
18117 placeSources(*Src0, *Src1, Src0s, Src1s, I);
18118 auto AddIdx = 1 - MulIdx;
18119 // Allow the special case where add (add (mul24, 0), mul24) became ->
18120 // add (mul24, mul24).
18121 if (I == 2 && isMul(TempNode->getOperand(AddIdx))) {
18122 Src2s.push_back(TempNode->getOperand(AddIdx));
18123 auto Src0 =
18124 handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(0));
18125 if (!Src0)
18126 break;
18127 auto Src1 =
18128 handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(1));
18129 if (!Src1)
18130 break;
18131 auto IterIsSigned = checkDot4MulSignedness(
18132 TempNode->getOperand(AddIdx), *Src0, *Src1,
18133 TempNode->getOperand(AddIdx)->getOperand(0),
18134 TempNode->getOperand(AddIdx)->getOperand(1), DAG);
18135 if (!IterIsSigned)
18136 break;
18137 assert(IsSigned);
18138 if (*IterIsSigned != *IsSigned)
18139 break;
18140 placeSources(*Src0, *Src1, Src0s, Src1s, I + 1);
18141 Src2s.push_back(DAG.getConstant(0, SL, MVT::i32));
18142 ChainLength = I + 2;
18143 break;
18144 }
18145
18146 TempNode = TempNode->getOperand(AddIdx);
18147 Src2s.push_back(TempNode);
18148 ChainLength = I + 1;
18149 // The loop body treats TempNode's operands as addends.
18150 if (TempNode.getOpcode() != ISD::ADD)
18151 break;
18152 LHS = TempNode->getOperand(0);
18153 RHS = TempNode->getOperand(1);
18154 }
18155
18156 if (ChainLength < 2)
18157 return SDValue();
18158
18159 // Masks were constructed with assumption that we would find a chain of
18160 // length 4. If not, then we need to 0 out the MSB bits (via perm mask of
18161 // 0x0c) so they do not affect dot calculation.
18162 if (ChainLength < 4) {
18163 fixMasks(Src0s, ChainLength);
18164 fixMasks(Src1s, ChainLength);
18165 }
18166
18167 SDValue Src0, Src1;
18168
18169 // If we are just using a single source for both, and have permuted the
18170 // bytes consistently, we can just use the sources without permuting
18171 // (commutation).
18172 bool UseOriginalSrc = false;
18173 if (ChainLength == 4 && Src0s.size() == 1 && Src1s.size() == 1 &&
18174 Src0s.begin()->PermMask == Src1s.begin()->PermMask &&
18175 Src0s.begin()->SrcOp.getValueSizeInBits() >= 32 &&
18176 Src1s.begin()->SrcOp.getValueSizeInBits() >= 32) {
18177 SmallVector<unsigned, 4> SrcBytes;
18178 auto Src0Mask = Src0s.begin()->PermMask;
18179 SrcBytes.push_back((Src0Mask >> 24) & 0xFF);
18180 bool UniqueEntries = true;
18181 for (auto I = 1; I < 4; I++) {
18182 auto NextByte = (Src0Mask >> ((3 - I) * 8)) & 0xFF;
18183
18184 if (is_contained(SrcBytes, NextByte)) {
18185 UniqueEntries = false;
18186 break;
18187 }
18188 SrcBytes.push_back(NextByte);
18189 }
18190
18191 if (UniqueEntries) {
18192 UseOriginalSrc = true;
18193
18194 auto *FirstElt = Src0s.begin();
18195 auto FirstEltOp =
18196 getDWordFromOffset(DAG, SL, FirstElt->SrcOp, FirstElt->DWordOffset);
18197
18198 auto *SecondElt = Src1s.begin();
18199 auto SecondEltOp = getDWordFromOffset(DAG, SL, SecondElt->SrcOp,
18200 SecondElt->DWordOffset);
18201
18202 Src0 = DAG.getBitcastedAnyExtOrTrunc(FirstEltOp, SL,
18203 MVT::getIntegerVT(32));
18204 Src1 = DAG.getBitcastedAnyExtOrTrunc(SecondEltOp, SL,
18205 MVT::getIntegerVT(32));
18206 }
18207 }
18208
18209 if (!UseOriginalSrc) {
18210 Src0 = resolveSources(DAG, SL, Src0s, false, true);
18211 Src1 = resolveSources(DAG, SL, Src1s, false, true);
18212 }
18213
18214 assert(IsSigned);
18215 SDValue Src2 =
18216 DAG.getExtOrTrunc(*IsSigned, Src2s[ChainLength - 1], SL, MVT::i32);
18217
18218 SDValue IID = DAG.getTargetConstant(*IsSigned ? Intrinsic::amdgcn_sdot4
18219 : Intrinsic::amdgcn_udot4,
18220 SL, MVT::i64);
18221
18222 assert(!VT.isVector());
18223 auto Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32, IID, Src0,
18224 Src1, Src2, DAG.getTargetConstant(0, SL, MVT::i1));
18225
18226 return DAG.getExtOrTrunc(*IsSigned, Dot, SL, VT);
18227 }
18228
18229 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
18230 return SDValue();
18231
18232 // add x, zext (setcc) => uaddo_carry x, 0, setcc
18233 // add x, sext (setcc) => usubo_carry x, 0, setcc
18234 unsigned Opc = LHS.getOpcode();
18237 std::swap(RHS, LHS);
18238
18239 Opc = RHS.getOpcode();
18240 switch (Opc) {
18241 default:
18242 break;
18243 case ISD::ZERO_EXTEND:
18244 case ISD::SIGN_EXTEND:
18245 case ISD::ANY_EXTEND: {
18246 auto Cond = RHS.getOperand(0);
18247 // If this won't be a real VOPC output, we would still need to insert an
18248 // extra instruction anyway.
18249 if (!isBoolSGPR(Cond))
18250 break;
18251 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
18252 SDValue Args[] = {LHS, DAG.getConstant(0, SL, MVT::i32), Cond};
18254 return DAG.getNode(Opc, SL, VTList, Args);
18255 }
18256 case ISD::UADDO_CARRY: {
18257 // add x, (uaddo_carry y, 0, cc) => uaddo_carry x, y, cc
18258 if (!isNullConstant(RHS.getOperand(1)))
18259 break;
18260 SDValue Args[] = {LHS, RHS.getOperand(0), RHS.getOperand(2)};
18261 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), RHS->getVTList(), Args);
18262 }
18263 }
18264 return SDValue();
18265}
18266
18267SDValue SITargetLowering::performPtrAddCombine(SDNode *N,
18268 DAGCombinerInfo &DCI) const {
18269 SelectionDAG &DAG = DCI.DAG;
18270 SDLoc DL(N);
18271 EVT VT = N->getValueType(0);
18272 SDValue N0 = N->getOperand(0);
18273 SDValue N1 = N->getOperand(1);
18274
18275 // The following folds transform PTRADDs into regular arithmetic in cases
18276 // where the PTRADD wouldn't be folded as an immediate offset into memory
18277 // instructions anyway. They are target-specific in that other targets might
18278 // prefer to not lose information about the pointer arithmetic.
18279
18280 // Fold (ptradd x, shl(0 - v, k)) -> sub(x, shl(v, k)).
18281 // Adapted from DAGCombiner::visitADDLikeCommutative.
18282 SDValue V, K;
18283 if (sd_match(N1, m_Shl(m_Neg(m_Value(V)), m_Value(K)))) {
18284 SDNodeFlags ShlFlags = N1->getFlags();
18285 // If the original shl is NUW and NSW, the first k+1 bits of 0-v are all 0,
18286 // so v is either 0 or the first k+1 bits of v are all 1 -> NSW can be
18287 // preserved.
18288 SDNodeFlags NewShlFlags =
18289 ShlFlags.hasNoUnsignedWrap() && ShlFlags.hasNoSignedWrap()
18291 : SDNodeFlags();
18292 SDValue Inner = DAG.getNode(ISD::SHL, DL, VT, V, K, NewShlFlags);
18293 DCI.AddToWorklist(Inner.getNode());
18294 return DAG.getNode(ISD::SUB, DL, VT, N0, Inner);
18295 }
18296
18297 // Fold into Mad64 if the right-hand side is a MUL. Analogous to a fold in
18298 // performAddCombine.
18299 if (N1.getOpcode() == ISD::MUL) {
18300 if (Subtarget->hasMad64_32()) {
18301 if (SDValue Folded = tryFoldToMad64_32(N, DCI))
18302 return Folded;
18303 }
18304 }
18305
18306 // If the 32 low bits of the constant are all zero, there is nothing to fold
18307 // into an immediate offset, so it's better to eliminate the unnecessary
18308 // addition for the lower 32 bits than to preserve the PTRADD.
18309 // Analogous to a fold in performAddCombine.
18310 if (VT == MVT::i64) {
18311 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18312 return Folded;
18313 }
18314
18315 if (N1.getOpcode() != ISD::ADD || !N1.hasOneUse())
18316 return SDValue();
18317
18318 SDValue X = N0;
18319 SDValue Y = N1.getOperand(0);
18320 SDValue Z = N1.getOperand(1);
18321 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
18322 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
18323
18324 if (!YIsConstant && !ZIsConstant && !X->isDivergent() &&
18325 Y->isDivergent() != Z->isDivergent()) {
18326 // Reassociate (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if x and
18327 // y are uniform and z isn't.
18328 // Reassociate (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if x and
18329 // z are uniform and y isn't.
18330 // The goal is to push uniform operands up in the computation, so that they
18331 // can be handled with scalar operations. We can't use reassociateScalarOps
18332 // for this since it requires two identical commutative operations to
18333 // reassociate.
18334 if (Y->isDivergent())
18335 std::swap(Y, Z);
18336 // If both additions in the original were NUW, reassociation preserves that.
18337 SDNodeFlags ReassocFlags =
18338 (N->getFlags() & N1->getFlags()) & SDNodeFlags::NoUnsignedWrap;
18339 SDValue UniformInner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
18340 DCI.AddToWorklist(UniformInner.getNode());
18341 return DAG.getMemBasePlusOffset(UniformInner, Z, DL, ReassocFlags);
18342 }
18343
18344 return SDValue();
18345}
18346
18347static bool isCtlzOpc(unsigned Opc) {
18348 return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_POISON;
18349}
18350
18351SDValue SITargetLowering::performSubCombine(SDNode *N,
18352 DAGCombinerInfo &DCI) const {
18353 SelectionDAG &DAG = DCI.DAG;
18354 EVT VT = N->getValueType(0);
18355
18356 if (VT == MVT::i64) {
18357 if (SDValue Folded = foldAddSub64WithZeroLowBitsTo32(N, DCI))
18358 return Folded;
18359 }
18360
18361 if (VT != MVT::i32)
18362 return SDValue();
18363
18364 SDLoc SL(N);
18365 SDValue LHS = N->getOperand(0);
18366 SDValue RHS = N->getOperand(1);
18367
18368 // sub x, zext (setcc) => usubo_carry x, 0, setcc
18369 // sub x, sext (setcc) => uaddo_carry x, 0, setcc
18370 unsigned Opc = RHS.getOpcode();
18371 switch (Opc) {
18372 default:
18373 break;
18374 case ISD::ZERO_EXTEND:
18375 case ISD::SIGN_EXTEND:
18376 case ISD::ANY_EXTEND: {
18377 auto Cond = RHS.getOperand(0);
18378 // If this won't be a real VOPC output, we would still need to insert an
18379 // extra instruction anyway.
18380 if (!isBoolSGPR(Cond))
18381 break;
18382 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
18383 SDValue Args[] = {LHS, DAG.getConstant(0, SL, MVT::i32), Cond};
18385 return DAG.getNode(Opc, SL, VTList, Args);
18386 }
18387 }
18388
18389 if (LHS.getOpcode() == ISD::USUBO_CARRY) {
18390 // sub (usubo_carry x, 0, cc), y => usubo_carry x, y, cc
18391 if (!isNullConstant(LHS.getOperand(1)))
18392 return SDValue();
18393 SDValue Args[] = {LHS.getOperand(0), RHS, LHS.getOperand(2)};
18394 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), LHS->getVTList(), Args);
18395 }
18396
18397 // sub (ctlz (xor x, (sra x, 31))), 1 -> ctls x.
18398 if (isOneConstant(RHS) && isCtlzOpc(LHS.getOpcode())) {
18399 SDValue CtlzSrc = LHS.getOperand(0);
18400 // Check for xor x, (sra x, 31) pattern.
18401 if (CtlzSrc.getOpcode() == ISD::XOR) {
18402 SDValue X = CtlzSrc.getOperand(0);
18403 SDValue SignExt = CtlzSrc.getOperand(1);
18404 // Try both ordering of XOR operands.
18405 if (SignExt.getOpcode() != ISD::SRA)
18406 std::swap(X, SignExt);
18407 if (SignExt.getOpcode() == ISD::SRA && SignExt.getOperand(0) == X) {
18408 ConstantSDNode *ShiftAmt =
18410 unsigned BitWidth = X.getValueType().getScalarSizeInBits();
18411 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1)
18412 return DAG.getNode(ISD::CTLS, SL, VT, X);
18413 }
18414 }
18415 }
18416
18417 return SDValue();
18418}
18419
18421 unsigned NumLiveUses = 0;
18422 for (SDUse &U : Op->uses()) {
18423 if (U.getResNo() != Op.getResNo() || U.getUser()->use_empty())
18424 continue;
18425 if (++NumLiveUses > 1)
18426 return false;
18427 }
18428 return NumLiveUses == 1;
18429}
18430
18432 // neg is a source modifier as well, so look through it.
18433 if (Op.getOpcode() == ISD::FNEG) {
18434 if (!hasOneLiveUse(Op))
18435 return false;
18436 Op = Op.getOperand(0);
18437 }
18438 return Op.getOpcode() == ISD::FABS && hasOneLiveUse(Op);
18439}
18440
18441// Return true if every element of \p Op is an fabs, which would be a free
18442// source modifier if \p Op were consumed by scalar instructions. Each fabs must
18443// have no other live user, otherwise the abs has to be materialized anyway.
18445 if (isSingleUseFAbs(Op))
18446 return true;
18447
18448 if (Op.getOpcode() == ISD::FNEG) {
18449 if (!hasOneLiveUse(Op))
18450 return false;
18451 Op = Op.getOperand(0);
18452 }
18453
18454 if (Op.getOpcode() != ISD::BUILD_VECTOR || !hasOneLiveUse(Op))
18455 return false;
18456
18457 return all_of(Op->op_values(), isSingleUseFAbs);
18458}
18459
18460// Packed math has no abs source modifier, so an fabs feeding one costs a real
18461// and per element. Scalarizing lets the abs fold back into a source modifier.
18462SDValue
18463SITargetLowering::splitPackedMathWithFAbsSource(SDNode *N,
18464 DAGCombinerInfo &DCI) const {
18465 EVT VT = N->getValueType(0);
18466 // Only natively packed 32/64-bit FP types: a packed f16 fabs is a single and,
18467 // and integer min/max shares this combine entry.
18468 if (!VT.isVector() || !VT.isFloatingPoint() ||
18469 VT.getScalarSizeInBits() < 32 || !isOperationLegal(N->getOpcode(), VT))
18470 return SDValue();
18471
18472 if (none_of(N->op_values(), isBuiltFromFAbs))
18473 return SDValue();
18474
18475 return DCI.DAG.UnrollVectorOp(N);
18476}
18477
18478SDValue SITargetLowering::performFAddCombine(SDNode *N,
18479 DAGCombinerInfo &DCI) const {
18480 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
18481 return SDValue();
18482
18483 SelectionDAG &DAG = DCI.DAG;
18484 EVT VT = N->getValueType(0);
18485
18486 SDLoc SL(N);
18487 SDValue LHS = N->getOperand(0);
18488 SDValue RHS = N->getOperand(1);
18489
18490 // These should really be instruction patterns, but writing patterns with
18491 // source modifiers is a pain.
18492
18493 // fadd (fadd (a, a), b) -> mad 2.0, a, b
18494 if (LHS.getOpcode() == ISD::FADD) {
18495 SDValue A = LHS.getOperand(0);
18496 if (A == LHS.getOperand(1)) {
18497 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
18498 if (FusedOp != 0) {
18499 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18500 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
18501 }
18502 }
18503 }
18504
18505 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
18506 if (RHS.getOpcode() == ISD::FADD) {
18507 SDValue A = RHS.getOperand(0);
18508 if (A == RHS.getOperand(1)) {
18509 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
18510 if (FusedOp != 0) {
18511 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18512 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
18513 }
18514 }
18515 }
18516
18517 return SDValue();
18518}
18519
18520SDValue SITargetLowering::performFSubCombine(SDNode *N,
18521 DAGCombinerInfo &DCI) const {
18522 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
18523 return SDValue();
18524
18525 SelectionDAG &DAG = DCI.DAG;
18526 SDLoc SL(N);
18527 EVT VT = N->getValueType(0);
18528 assert(!VT.isVector());
18529
18530 // Try to get the fneg to fold into the source modifier. This undoes generic
18531 // DAG combines and folds them into the mad.
18532 //
18533 // Only do this if we are not trying to support denormals. v_mad_f32 does
18534 // not support denormals ever.
18535 SDValue LHS = N->getOperand(0);
18536 SDValue RHS = N->getOperand(1);
18537 if (LHS.getOpcode() == ISD::FADD) {
18538 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
18539 SDValue A = LHS.getOperand(0);
18540 if (A == LHS.getOperand(1)) {
18541 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
18542 if (FusedOp != 0) {
18543 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
18544 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
18545
18546 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
18547 }
18548 }
18549 }
18550
18551 if (RHS.getOpcode() == ISD::FADD) {
18552 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
18553
18554 SDValue A = RHS.getOperand(0);
18555 if (A == RHS.getOperand(1)) {
18556 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
18557 if (FusedOp != 0) {
18558 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
18559 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
18560 }
18561 }
18562 }
18563
18564 return SDValue();
18565}
18566
18567SDValue SITargetLowering::performFDivCombine(SDNode *N,
18568 DAGCombinerInfo &DCI) const {
18569 SelectionDAG &DAG = DCI.DAG;
18570 SDLoc SL(N);
18571 EVT VT = N->getValueType(0);
18572
18573 if (VT != MVT::f16 && VT != MVT::bf16)
18574 return SDValue();
18575
18576 SDValue LHS = N->getOperand(0);
18577 SDValue RHS = N->getOperand(1);
18578
18579 SDNodeFlags Flags = N->getFlags();
18580 SDNodeFlags RHSFlags = RHS->getFlags();
18581 if (!Flags.hasAllowContract() || !RHSFlags.hasAllowContract() ||
18582 !RHS->hasOneUse())
18583 return SDValue();
18584
18585 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
18586 bool IsNegative = false;
18587 if (CLHS->isOne() || (IsNegative = CLHS->isMinusOne())) {
18588 // fdiv contract 1.0, (sqrt contract x) -> rsq
18589 // fdiv contract -1.0, (sqrt contract x) -> fneg(rsq)
18590 if (RHS.getOpcode() == ISD::FSQRT) {
18591 // TODO: Or in RHS flags, somehow missing from SDNodeFlags
18592 SDValue SqrtOp = RHS.getOperand(0);
18593 SDValue Rsq;
18594 if (isOperationLegal(ISD::FSQRT, VT)) {
18595 // fsqrt legality correlates to rsq availability of the same type.
18596 Rsq = DAG.getNode(AMDGPUISD::RSQ, SL, VT, SqrtOp, Flags);
18597 } else if (VT == MVT::f16) {
18598 // Targets without 16-bit instructions (gfx6/gfx7) have no f16 rsq,
18599 // but v_rsq_f32 is more than accurate enough for f16. Unlike bf16,
18600 // every f16 value (including denormals) extends to a normal f32, and
18601 // an f16 rsq result is never denormal, so the f32 reciprocal square
18602 // root needs no denormal handling. Compute it in f32 and round back.
18603 SDValue Ext =
18604 DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, SqrtOp, Flags);
18605 SDValue F32Rsq =
18606 DAG.getNode(AMDGPUISD::RSQ, SL, MVT::f32, Ext, Flags);
18607 Rsq = DAG.getNode(ISD::FP_ROUND, SL, VT, F32Rsq,
18608 DAG.getTargetConstant(0, SL, MVT::i32), Flags);
18609 } else {
18610 // bf16 shares f32's exponent range, so bf16 denormals would extend to
18611 // f32 denormals that v_rsq_f32 does not handle. Leave it expanded.
18612 return SDValue();
18613 }
18614 return IsNegative ? DAG.getNode(ISD::FNEG, SL, VT, Rsq, Flags) : Rsq;
18615 }
18616 }
18617 }
18618
18619 return SDValue();
18620}
18621
18622SDValue SITargetLowering::performFMulCombine(SDNode *N,
18623 DAGCombinerInfo &DCI) const {
18624 SelectionDAG &DAG = DCI.DAG;
18625 EVT VT = N->getValueType(0);
18626 EVT ScalarVT = VT.getScalarType();
18627 EVT IntVT = VT.changeElementType(*DAG.getContext(), MVT::i32);
18628
18629 if (SDValue V = performFMulExpCombine(N, DCI))
18630 return V;
18631
18632 if (!N->isDivergent() && getSubtarget()->hasSALUFloatInsts() &&
18633 (ScalarVT == MVT::f32 || ScalarVT == MVT::f16)) {
18634 // Prefer to use s_mul_f16/f32 instead of v_ldexp_f16/f32.
18635 return SDValue();
18636 }
18637
18638 SDValue LHS = N->getOperand(0);
18639 SDValue RHS = N->getOperand(1);
18640
18641 // It is cheaper to realize i32 inline constants as compared against
18642 // materializing f16 or f64 (or even non-inline f32) values,
18643 // possible via ldexp usage, as shown below :
18644 //
18645 // Given : A = 2^a & B = 2^b ; where a and b are integers.
18646 // fmul x, (select y, A, B) -> ldexp( x, (select i32 y, a, b) )
18647 // fmul x, (select y, -A, -B) -> ldexp( (fneg x), (select i32 y, a, b) )
18648 if ((ScalarVT == MVT::f64 || ScalarVT == MVT::f32 || ScalarVT == MVT::f16) &&
18649 (RHS.hasOneUse() && RHS.getOpcode() == ISD::SELECT)) {
18650 const ConstantFPSDNode *TrueNode = isConstOrConstSplatFP(RHS.getOperand(1));
18651 if (!TrueNode)
18652 return SDValue();
18653 const ConstantFPSDNode *FalseNode =
18654 isConstOrConstSplatFP(RHS.getOperand(2));
18655 if (!FalseNode)
18656 return SDValue();
18657
18658 if (TrueNode->isNegative() != FalseNode->isNegative())
18659 return SDValue();
18660
18661 // For f32, only non-inline constants should be transformed.
18662 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
18663 if (ScalarVT == MVT::f32 &&
18664 TII->isInlineConstant(TrueNode->getValueAPF()) &&
18665 TII->isInlineConstant(FalseNode->getValueAPF()))
18666 return SDValue();
18667
18668 int TrueNodeExpVal = TrueNode->getValueAPF().getExactLog2Abs();
18669 if (TrueNodeExpVal == INT_MIN)
18670 return SDValue();
18671 int FalseNodeExpVal = FalseNode->getValueAPF().getExactLog2Abs();
18672 if (FalseNodeExpVal == INT_MIN)
18673 return SDValue();
18674
18675 SDLoc SL(N);
18676 SDValue SelectNode =
18677 DAG.getNode(ISD::SELECT, SL, IntVT, RHS.getOperand(0),
18678 DAG.getSignedConstant(TrueNodeExpVal, SL, IntVT),
18679 DAG.getSignedConstant(FalseNodeExpVal, SL, IntVT));
18680
18681 LHS = TrueNode->isNegative()
18682 ? DAG.getNode(ISD::FNEG, SL, VT, LHS, LHS->getFlags())
18683 : LHS;
18684
18685 return DAG.getNode(ISD::FLDEXP, SL, VT, LHS, SelectNode, N->getFlags());
18686 }
18687
18688 return SDValue();
18689}
18690
18691// Fold a constant scale into the exponent, where it merges into an fma:
18692// fmul (fexp2 (fmul a, b)), C -> fexp2 (fma a, b, log2(C))
18693// fmul (fexp x), C -> fexp2 (fma x, log2(e), log2(C))
18694// fmul (fpow x, Y), C -> exp (fma (log x), Y, log2(C))
18695//
18696// contract is required on the multiply that the fma replaces: the inner fmul
18697// of an fexp2, the fpow, or this fmul when folding an fexp. reassoc and afn
18698// are required on this fmul. GlobalISel does not fold this.
18699SDValue SITargetLowering::performFMulExpCombine(SDNode *N,
18700 DAGCombinerInfo &DCI) const {
18701 SelectionDAG &DAG = DCI.DAG;
18702 // fexp and fexp2 are custom lowered, so they can't be created after
18703 // LegalizeDAG. fexp in particular is gone by then, expanded to a multiply
18704 // by log2(e).
18705 if (DCI.isAfterLegalizeDAG() || N->getValueType(0) != MVT::f32)
18706 return SDValue();
18707
18708 // log2(C) is rarely an inline constant, so the fma needs a literal.
18709 if (!getSubtarget()->hasVOP3Literal() ||
18711 return SDValue();
18712
18713 SDNodeFlags Flags = N->getFlags();
18714 if (!Flags.hasAllowReassociation() || !Flags.hasApproximateFuncs())
18715 return SDValue();
18716
18717 // With other users the exp would have to be duplicated.
18718 SDValue Exp = N->getOperand(0);
18719 auto *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1));
18720 if (!C || !Exp.hasOneUse() || !Exp->getFlags().hasApproximateFuncs())
18721 return SDValue();
18722
18723 // C must be a positive normal. isNormal() also rejects 0, Inf, and NaN,
18724 // whose log2 is not a finite fma addend. A denormal is rejected in every
18725 // denormal mode: under flush-to-zero the fmul flushes it to zero, and
18726 // log2(C) would not. A negative C has no real log2.
18727 const APFloat &CVal = C->getValueAPF();
18728 if (!CVal.isNormal() || CVal.isNegative())
18729 return SDValue();
18730
18731 Flags &= Exp->getFlags();
18732 SDLoc SL(N);
18733 SDValue A, B;
18734 unsigned ExpOpc;
18735 bool UseFmaLegacy = false;
18736 if (Exp.getOpcode() == ISD::FEXP2) {
18737 SDValue Arg = Exp.getOperand(0);
18738 if (Arg.getOpcode() != ISD::FMUL || !Arg.hasOneUse() ||
18739 !Arg->getFlags().hasAllowContract())
18740 return SDValue();
18741 Flags &= Arg->getFlags();
18742 A = Arg.getOperand(0);
18743 B = Arg.getOperand(1);
18744 // Keep fexp2 so its lowering still adds denormal handling if required.
18745 ExpOpc = ISD::FEXP2;
18746 } else if (Exp.getOpcode() == ISD::FEXP) {
18747 // Contract the scale into the multiply by log2(e) that fexp lowering
18748 // would insert.
18749 if (!N->getFlags().hasAllowContract())
18750 return SDValue();
18751 A = Exp.getOperand(0);
18752 B = DAG.getConstantFP(numbers::log2e, SL, MVT::f32);
18753 // Keep fexp2 so its lowering still adds denormal handling if required.
18754 ExpOpc = ISD::FEXP2;
18755 } else if (Exp.getOpcode() == ISD::FPOW) {
18756 if (!Exp->getFlags().hasAllowContract())
18757 return SDValue();
18758 // fpow is custom-lowered by lowerFPOW, which multiplies with fmul_legacy
18759 // (0 * inf = 0). An IEEE fma matches that only for a normal constant
18760 // exponent; otherwise fma_legacy is needed.
18761 auto *Y = dyn_cast<ConstantFPSDNode>(Exp.getOperand(1));
18762 UseFmaLegacy = !Y || !Y->getValueAPF().isNormal();
18763 if (UseFmaLegacy && !getSubtarget()->hasFmaLegacy32Insts())
18764 return SDValue();
18765 // log2(0) is -inf, which exp2 turns back into 0. Drop ninf on the core,
18766 // matching lowerFPOW, so a later fold cannot treat that -inf as poison.
18767 Flags.setNoInfs(false);
18768 A = DAG.getNode(AMDGPUISD::LOG, SL, MVT::f32, Exp.getOperand(0), Flags);
18769 B = Exp.getOperand(1);
18770 ExpOpc = AMDGPUISD::EXP;
18771 } else {
18772 return SDValue();
18773 }
18774
18775 // Computed in double and rounded once to f32.
18776 SDValue K =
18777 DAG.getConstantFP(std::log2(CVal.convertToDouble()), SL, MVT::f32);
18778 SDValue Fma =
18779 UseFmaLegacy
18780 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::f32,
18781 DAG.getTargetConstant(Intrinsic::amdgcn_fma_legacy, SL,
18782 MVT::i32),
18783 A, B, K, Flags)
18784 : DAG.getNode(ISD::FMA, SL, MVT::f32, A, B, K, Flags);
18785 return DAG.getNode(ExpOpc, SL, MVT::f32, Fma, Flags);
18786}
18787
18788SDValue SITargetLowering::performFMACombine(SDNode *N,
18789 DAGCombinerInfo &DCI) const {
18790 SelectionDAG &DAG = DCI.DAG;
18791 EVT VT = N->getValueType(0);
18792 SDLoc SL(N);
18793
18794 if (!Subtarget->hasDot10Insts() || VT != MVT::f32)
18795 return SDValue();
18796
18797 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
18798 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
18799 SDValue Op1 = N->getOperand(0);
18800 SDValue Op2 = N->getOperand(1);
18801 SDValue FMA = N->getOperand(2);
18802
18803 if (FMA.getOpcode() != ISD::FMA || Op1.getOpcode() != ISD::FP_EXTEND ||
18804 Op2.getOpcode() != ISD::FP_EXTEND)
18805 return SDValue();
18806
18807 // The fdot2 fold (fma_mix -> dot2) is only safe when both instructions agree
18808 // on how f16 subnormal inputs are handled. However, if both FMAs carry afn
18809 // the caller accepts approximate results, so any subnormal flushing
18810 // introduced by dot2 is acceptable regardless of mode.
18811 //
18812 // gfx90a (CDNA2) is the sole exception (dot2UnconditionalFlush): v_dot2c
18813 // unconditionally flushes f16 subnormal inputs to zero regardless of MODE,
18814 // while v_fma_mix_f32 preserves them when ieee=1 (the default compute kernel
18815 // mode). The fold is safe only when f32 denorm = PreserveSign, which implies
18816 // ieee=0 so both flush.
18817 //
18818 // All other GPUs: v_dot2 does NOT flush f16 subnormal inputs. v_fma_mix_f32
18819 // flushes them only when f32 denorm = PreserveSign. The fold is safe only
18820 // when f32 denorm is IEEE (both preserve the subnormal). Dynamic mode is
18821 // also rejected since the runtime value is unknown.
18822 bool AllowInaccuracy = N->getFlags().hasApproximateFuncs() &&
18823 FMA->getFlags().hasApproximateFuncs();
18824 if (!AllowInaccuracy) {
18825 const MachineFunction &MF = DAG.getMachineFunction();
18826 DenormalMode Mode = MF.getDenormalMode(APFloat::IEEEsingle());
18827 if (Subtarget->dot2UnconditionalFlush()) {
18828 // gfx90a: fold safe only when f32 denorm flushes.
18830 return SDValue();
18831 } else {
18832 // All other GPUs: fold safe only when f32 denorm is IEEE.
18833 if (Mode != DenormalMode::getIEEE())
18834 return SDValue();
18835 }
18836 }
18837
18838 // fp-contract allows reassociating the fma tree into a dot product.
18839 if (N->getFlags().hasAllowContract() && FMA->getFlags().hasAllowContract()) {
18840 Op1 = Op1.getOperand(0);
18841 Op2 = Op2.getOperand(0);
18842 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18844 return SDValue();
18845
18846 SDValue Vec1 = Op1.getOperand(0);
18847 SDValue Idx1 = Op1.getOperand(1);
18848 SDValue Vec2 = Op2.getOperand(0);
18849
18850 SDValue FMAOp1 = FMA.getOperand(0);
18851 SDValue FMAOp2 = FMA.getOperand(1);
18852 SDValue FMAAcc = FMA.getOperand(2);
18853
18854 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
18855 FMAOp2.getOpcode() != ISD::FP_EXTEND)
18856 return SDValue();
18857
18858 FMAOp1 = FMAOp1.getOperand(0);
18859 FMAOp2 = FMAOp2.getOperand(0);
18860 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18862 return SDValue();
18863
18864 SDValue Vec3 = FMAOp1.getOperand(0);
18865 SDValue Vec4 = FMAOp2.getOperand(0);
18866 SDValue Idx2 = FMAOp1.getOperand(1);
18867
18868 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1))
18869 return SDValue();
18870
18871 if (!isa<ConstantSDNode>(Idx1) || !isa<ConstantSDNode>(Idx2) ||
18872 Idx1 == Idx2)
18873 return SDValue();
18874
18875 if (Vec1 == Vec2 || Vec3 == Vec4)
18876 return SDValue();
18877
18878 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
18879 return SDValue();
18880
18881 if ((Vec1 == Vec3 && Vec2 == Vec4) || (Vec1 == Vec4 && Vec2 == Vec3)) {
18882 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
18883 DAG.getTargetConstant(0, SL, MVT::i1));
18884 }
18885 }
18886 return SDValue();
18887}
18888
18889// Given a double-precision ordered or unordered comparison, return the
18890// condition code for an equivalent integral comparison of the operands' upper
18891// 32 bits, or `SETCC_INVALID` if not possible.
18892// For simplicity, no simplification occurs if the operands are not both known
18893// to have sign bit zero.
18894//
18895// EQ/NE:
18896// If LHS.lo32 == RHS.lo32:
18897// setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, eq/ne
18898// If LHS.lo32 != RHS.lo32:
18899// setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, false/true
18900// The reduction is not possible if operands may be +0 and -0.
18901// For ordered eq / unordered ne, at most one operand may be NaN.
18902// For unordered eq / ordered ne, neither operand can be NaN.
18903//
18904// LT/GE:
18905// If LHS.lo32 >= RHS.lo32 (unsigned):
18906// setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]lt/ge
18907// If LHS.lo32 < RHS.lo32 (unsigned):
18908// setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]le/gt
18909// The reduction is only supported if both operands are nonnegative.
18910// For ordered lt / unordered ge, the RHS cannot be NaN.
18911// For unordered lt / ordered ge, neither operand can be NaN.
18912//
18913// LE/GT:
18914// If LHS.lo32 > RHS.lo32 (unsigned):
18915// setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]lt/ge
18916// If LHS.lo32 <= RHS.lo32 (unsigned):
18917// setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]le/gt
18918// The reduction is only supported if both operands are nonnegative.
18919// For unordered le / ordered gt, the LHS cannot be NaN.
18920// For ordered le / unordered gt, neither operand can be NaN.
18922 const SDValue LHS,
18923 const SDValue RHS,
18924 const SelectionDAG &DAG) {
18925 EVT VT = LHS.getValueType();
18926 assert(VT == MVT::f64 && "Incorrect operand type!");
18927
18928 const KnownBits RHSBits = DAG.computeKnownBits(RHS);
18929 // Bail if RHS sign bit is not known to be zero.
18930 if (!RHSBits.Zero.isSignBitSet())
18931 return ISD::SETCC_INVALID;
18932
18933 const KnownBits RHSKnownLo32 = RHSBits.trunc(32);
18934 const KnownFPClass RHSFPClass =
18936 const bool RHSMaybeNaN = !RHSFPClass.isKnownNeverNaN();
18937
18938 const KnownBits LHSBits = DAG.computeKnownBits(LHS);
18939 const KnownBits LHSKnownLo32 = LHSBits.trunc(32);
18940 const KnownFPClass LHSFPClass =
18942 const bool LHSMaybeNaN = !LHSFPClass.isKnownNeverNaN();
18943
18944 // Bail if LHS sign bit is not known to be zero.
18945 if (!LHSBits.Zero.isSignBitSet())
18946 return ISD::SETCC_INVALID;
18947
18948 switch (CC) {
18949 default:
18950 break;
18951 case ISD::SETEQ:
18952 case ISD::SETOEQ:
18953 case ISD::SETUEQ:
18954 case ISD::SETONE:
18955 case ISD::SETUNE: {
18956 // OEQ should be false if either operand is NaN, so it suffices that at
18957 // least one operand is not NaN.
18958 if (CC == ISD::SETOEQ && LHSMaybeNaN && RHSMaybeNaN)
18959 break;
18960 // UEQ should be true if either operand is NaN, but this cannot be checked
18961 // on underlying bits.
18962 if (CC == ISD::SETUEQ && (LHSMaybeNaN || RHSMaybeNaN))
18963 break;
18964 // ONE should be false if either operand is NaN, but this cannot be
18965 // checked on underlying bits.
18966 if (CC == ISD::SETONE && (LHSMaybeNaN || RHSMaybeNaN))
18967 break;
18968 // UNE should be true if either operand is NaN, so it suffices that they
18969 // are not both NaN.
18970 if (CC == ISD::SETUNE && LHSMaybeNaN && RHSMaybeNaN)
18971 break;
18972
18973 const std::optional<bool> KnownEq =
18974 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
18975
18976 if (!KnownEq)
18977 break;
18978
18979 if (*KnownEq)
18980 return (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ)
18981 ? ISD::SETEQ
18982 : ISD::SETNE;
18983
18984 return (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ)
18986 : ISD::SETTRUE;
18987 }
18988 case ISD::SETLT:
18989 case ISD::SETOLT:
18990 case ISD::SETULT:
18991 case ISD::SETGE:
18992 case ISD::SETOGE:
18993 case ISD::SETUGE: {
18994 // OLT should be false if either operand is NaN.
18995 // Since NaNs have maximum exponent and nonzero mantissa, false positives
18996 // are only possible if the RHS is NaN. (No issue with RHS == +inf since
18997 // the inequality is strict)
18998 if (CC == ISD::SETOLT && RHSMaybeNaN)
18999 break;
19000 // ULT should be true if either operand is NaN, but this cannot be ensured
19001 // with a truncated comparison.
19002 if (CC == ISD::SETULT && (LHSMaybeNaN || RHSMaybeNaN))
19003 break;
19004 // OGE should be false if either operand is NaN, but this cannot be
19005 // ensured with a truncated comparison.
19006 if (CC == ISD::SETOGE && (LHSMaybeNaN || RHSMaybeNaN))
19007 break;
19008 // UGE should be true if either operand is NaN.
19009 // False negatives are only possible if the RHS is NaN.
19010 // (No issue with RHS == +inf since the inequality is inclusive)
19011 if (CC == ISD::SETUGE && RHSMaybeNaN)
19012 break;
19013
19014 const std::optional<bool> KnownUge =
19015 KnownBits::uge(LHSKnownLo32, RHSKnownLo32);
19016
19017 if (!KnownUge)
19018 break;
19019
19020 if (*KnownUge) {
19021 // LHS.lo32 uge RHS.lo32, so LHS >= RHS iff LHS.hi32 >= RHS.hi32
19022 return (CC == ISD::SETLT || CC == ISD::SETOLT || CC == ISD::SETULT)
19023 ? ISD::SETLT
19024 : ISD::SETGE;
19025 }
19026 // LHS.lo32 ult RHS.lo32, so LHS >= RHS iff LHS.hi32 > RHS.hi32
19027 return (CC == ISD::SETLT || CC == ISD::SETOLT || CC == ISD::SETULT)
19028 ? ISD::SETLE
19029 : ISD::SETGT;
19030 }
19031 case ISD::SETLE:
19032 case ISD::SETOLE:
19033 case ISD::SETULE:
19034 case ISD::SETGT:
19035 case ISD::SETOGT:
19036 case ISD::SETUGT: {
19037 // OLE should be false if either operand is NaN, but this cannot be
19038 // ensured with a truncated comparison.
19039 if (CC == ISD::SETOLE && (LHSMaybeNaN || RHSMaybeNaN))
19040 break;
19041 // ULE should be true if either operand is NaN.
19042 // False negatives are only possible if the LHS is NaN.
19043 // (No issue with LHS == +inf since the inequality is inclusive)
19044 if (CC == ISD::SETULE && LHSMaybeNaN)
19045 break;
19046 // OGT should be false if either operand is NaN.
19047 // False positives are only possible if the LHS is NaN.
19048 // (No issue with LHS == +inf since the inequality is strict)
19049 if (CC == ISD::SETOGT && LHSMaybeNaN)
19050 break;
19051 // UGT should be true if either operand is NaN, but this cannot be ensured
19052 // with a truncated comparison.
19053 if (CC == ISD::SETUGT && (LHSMaybeNaN || RHSMaybeNaN))
19054 break;
19055
19056 const std::optional<bool> KnownUle =
19057 KnownBits::ule(LHSKnownLo32, RHSKnownLo32);
19058
19059 if (!KnownUle)
19060 break;
19061
19062 if (*KnownUle) {
19063 // LHS.lo32 ule RHS.lo32, so LHS <= RHS iff LHS.hi32 <= RHS.hi32
19064 return (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE)
19065 ? ISD::SETLE
19066 : ISD::SETGT;
19067 }
19068 // LHS.lo32 ugt RHS.lo32, so LHS <= RHS iff LHS.hi32 < RHS.hi32
19069 return (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE)
19070 ? ISD::SETLT
19071 : ISD::SETGE;
19072 }
19073 }
19074
19075 return ISD::SETCC_INVALID;
19076}
19077
19078SDValue SITargetLowering::performSetCCCombine(SDNode *N,
19079 DAGCombinerInfo &DCI) const {
19080 SelectionDAG &DAG = DCI.DAG;
19081 SDLoc SL(N);
19082
19083 SDValue LHS = N->getOperand(0);
19084 SDValue RHS = N->getOperand(1);
19085 EVT VT = LHS.getValueType();
19086 ISD::CondCode CC = N->getOperandCondCode(2);
19087
19088 auto *CRHS = dyn_cast<ConstantSDNode>(RHS);
19089 if (!CRHS) {
19091 if (CRHS) {
19092 std::swap(LHS, RHS);
19094 }
19095 }
19096
19097 if (CRHS) {
19098 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
19099 isBoolSGPR(LHS.getOperand(0))) {
19100 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
19101 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
19102 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
19103 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
19104 if ((CRHS->isAllOnes() &&
19105 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
19106 (CRHS->isZero() &&
19107 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
19108 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
19109 DAG.getAllOnesConstant(SL, MVT::i1));
19110 if ((CRHS->isAllOnes() &&
19111 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
19112 (CRHS->isZero() &&
19113 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
19114 return LHS.getOperand(0);
19115 }
19116
19117 const APInt &CRHSVal = CRHS->getAPIntValue();
19118 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
19119 LHS.getOpcode() == ISD::SELECT &&
19120 isa<ConstantSDNode>(LHS.getOperand(1)) &&
19121 isa<ConstantSDNode>(LHS.getOperand(2)) &&
19122 isBoolSGPR(LHS.getOperand(0))) {
19123 // Given CT != FT:
19124 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
19125 // setcc (select cc, CT, CF), CF, ne => cc
19126 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
19127 // setcc (select cc, CT, CF), CT, eq => cc
19128 const APInt &CT = LHS.getConstantOperandAPInt(1);
19129 const APInt &CF = LHS.getConstantOperandAPInt(2);
19130
19131 if (CT != CF) {
19132 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
19133 (CT == CRHSVal && CC == ISD::SETNE))
19134 return DAG.getNOT(SL, LHS.getOperand(0), MVT::i1);
19135 if ((CF == CRHSVal && CC == ISD::SETNE) ||
19136 (CT == CRHSVal && CC == ISD::SETEQ))
19137 return LHS.getOperand(0);
19138 }
19139 }
19140 }
19141
19142 // Truncate 64-bit setcc to only test upper or lower 32-bits.
19143 if (VT == MVT::i64) {
19144 const KnownBits LHSKnown = DAG.computeKnownBits(LHS);
19145 const KnownBits RHSKnown = DAG.computeKnownBits(RHS);
19146 const KnownBits LHSKnownLo32 = LHSKnown.trunc(32);
19147 const KnownBits RHSKnownLo32 = RHSKnown.trunc(32);
19148 // Truncate 64-bit setcc to test only upper 32-bits of its operands in the
19149 // following cases where information about the lower 32-bits of its operands
19150 // is known:
19151 //
19152 // If LHS.lo32 == RHS.lo32:
19153 // setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, eq/ne
19154 // If LHS.lo32 != RHS.lo32:
19155 // setcc LHS, RHS, eq/ne => setcc LHS.hi32, RHS.hi32, false/true
19156 // If LHS.lo32 >= RHS.lo32 (unsigned):
19157 // setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]lt/ge
19158 // If LHS.lo32 > RHS.lo32 (unsigned):
19159 // setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]lt/ge
19160 // If LHS.lo32 <= RHS.lo32 (unsigned):
19161 // setcc LHS, RHS, [u]le/gt => LHS.hi32, RHS.hi32, [u]le/gt
19162 // If LHS.lo32 < RHS.lo32 (unsigned):
19163 // setcc LHS, RHS, [u]lt/ge => LHS.hi32, RHS.hi32, [u]le/gt
19164
19165 // NewCC is valid iff we can truncate the setcc to only test the upper 32
19166 // bits
19168
19169 switch (CC) {
19170 default:
19171 llvm_unreachable("Unexpected condition code for integer setcc");
19172 break;
19173 case ISD::SETEQ: {
19174 const std::optional<bool> KnownEq =
19175 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
19176 if (KnownEq)
19177 NewCC = *KnownEq ? ISD::SETEQ : ISD::SETFALSE;
19178
19179 break;
19180 }
19181 case ISD::SETNE: {
19182 const std::optional<bool> KnownEq =
19183 KnownBits::eq(LHSKnownLo32, RHSKnownLo32);
19184 if (KnownEq)
19185 NewCC = *KnownEq ? ISD::SETNE : ISD::SETTRUE;
19186
19187 break;
19188 }
19189 case ISD::SETULT:
19190 case ISD::SETUGE:
19191 case ISD::SETLT:
19192 case ISD::SETGE: {
19193 const std::optional<bool> KnownUge =
19194 KnownBits::uge(LHSKnownLo32, RHSKnownLo32);
19195 if (KnownUge) {
19196 if (*KnownUge) {
19197 // LHS.lo32 uge RHS.lo32, so LHS >= RHS iff LHS.hi32 >= RHS.hi32
19198 NewCC = CC;
19199 } else {
19200 // LHS.lo32 ult RHS.lo32, so LHS >= RHS iff LHS.hi32 > RHS.hi32
19201 NewCC = CC == ISD::SETULT ? ISD::SETULE
19203 : CC == ISD::SETLT ? ISD::SETLE
19204 : ISD::SETGT;
19205 }
19206 }
19207 break;
19208 }
19209 case ISD::SETULE:
19210 case ISD::SETUGT:
19211 case ISD::SETLE:
19212 case ISD::SETGT: {
19213 const std::optional<bool> KnownUle =
19214 KnownBits::ule(LHSKnownLo32, RHSKnownLo32);
19215 if (KnownUle) {
19216 if (*KnownUle) {
19217 // LHS.lo32 ule RHS.lo32, so LHS <= RHS iff LHS.hi32 <= RHS.hi32
19218 NewCC = CC;
19219 } else {
19220 // LHS.lo32 ugt RHS.lo32, so LHS <= RHS iff LHS.hi32 < RHS.hi32
19221 NewCC = CC == ISD::SETULE ? ISD::SETULT
19223 : CC == ISD::SETLE ? ISD::SETLT
19224 : ISD::SETGE;
19225 }
19226 }
19227 break;
19228 }
19229 }
19230
19231 if (NewCC != ISD::SETCC_INVALID)
19232 return DAG.getSetCC(SL, N->getValueType(0), getHiHalf64(LHS, DAG),
19233 getHiHalf64(RHS, DAG), NewCC);
19234
19235 // Truncate 64-bit setcc to test only lower 32-bits when upper 32-bits are
19236 // known equal.
19237 const KnownBits LHSKnownHi32 = LHSKnown.extractBits(32, 32);
19238 const KnownBits RHSKnownHi32 = RHSKnown.extractBits(32, 32);
19239 const std::optional<bool> KnownEq =
19240 KnownBits::eq(LHSKnownHi32, RHSKnownHi32);
19241
19242 if (KnownEq == true) {
19243 // For signed comparisons, convert to unsigned since upper halves match
19245
19246 SDValue LHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
19247 SDValue RHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, RHS);
19248 return DAG.getSetCC(SL, N->getValueType(0), LHSLo, RHSLo, NewCC);
19249 }
19250 }
19251
19252 // Eliminate setcc by using carryout from add/sub instruction
19253
19254 // LHS = ADD i64 RHS, Z LHSlo = UADDO i32 RHSlo, Zlo
19255 // setcc LHS ult RHS -> LHSHi = UADDO_CARRY i32 RHShi, Zhi
19256 // similarly for subtraction
19257
19258 // LHS = ADD i64 Y, 1 LHSlo = UADDO i32 Ylo, 1
19259 // setcc LHS eq 0 -> LHSHi = UADDO_CARRY i32 Yhi, 0
19260
19261 if (VT == MVT::i64 && ((CC == ISD::SETULT &&
19263 (CC == ISD::SETUGT &&
19265 (CC == ISD::SETEQ && CRHS && CRHS->isZero() &&
19266 sd_match(LHS, m_Add(m_Value(), m_One()))))) {
19267 bool IsAdd = LHS.getOpcode() == ISD::ADD;
19268
19269 SDValue Op0 = LHS.getOperand(0);
19270 SDValue Op1 = LHS.getOperand(1);
19271
19272 SDValue Op0Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Op0);
19273 SDValue Op1Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Op1);
19274
19275 SDValue Op0Hi = getHiHalf64(Op0, DAG);
19276 SDValue Op1Hi = getHiHalf64(Op1, DAG);
19277
19278 SDValue NodeLo =
19279 DAG.getNode(IsAdd ? ISD::UADDO : ISD::USUBO, SL,
19280 DAG.getVTList(MVT::i32, MVT::i1), {Op0Lo, Op1Lo});
19281
19282 SDValue CarryInHi = NodeLo.getValue(1);
19283 SDValue NodeHi = DAG.getNode(IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY,
19284 SL, DAG.getVTList(MVT::i32, MVT::i1),
19285 {Op0Hi, Op1Hi, CarryInHi});
19286
19287 SDValue ResultLo = NodeLo.getValue(0);
19288 SDValue ResultHi = NodeHi.getValue(0);
19289
19290 SDValue JoinedResult =
19291 DAG.getBuildVector(MVT::v2i32, SL, {ResultLo, ResultHi});
19292
19293 SDValue Result = DAG.getNode(ISD::BITCAST, SL, VT, JoinedResult);
19294 SDValue Overflow = NodeHi.getValue(1);
19295 DCI.CombineTo(LHS.getNode(), Result);
19296 return Overflow;
19297 }
19298
19299 if (VT != MVT::f32 && VT != MVT::f64 &&
19300 (!Subtarget->has16BitInsts() || VT != MVT::f16))
19301 return SDValue();
19302
19303 // Match isinf/isfinite pattern
19304 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
19305 // (fcmp one (fabs x), inf) -> (fp_class x,
19306 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
19307 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) &&
19308 LHS.getOpcode() == ISD::FABS) {
19309 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
19310 if (!CRHS)
19311 return SDValue();
19312
19313 const APFloat &APF = CRHS->getValueAPF();
19314 if (APF.isInfinity() && !APF.isNegative()) {
19315 const unsigned IsInfMask =
19317 const unsigned IsFiniteMask =
19321 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
19322 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
19323 DAG.getConstant(Mask, SL, MVT::i32));
19324 }
19325 }
19326
19327 if (VT == MVT::f64) {
19329 if (HiHalfCC != ISD::SETCC_INVALID)
19330 return DAG.getSetCC(SL, N->getValueType(0), getHiHalf64(LHS, DAG),
19331 getHiHalf64(RHS, DAG), HiHalfCC);
19332 }
19333
19334 return SDValue();
19335}
19336
19337SDValue
19338SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
19339 DAGCombinerInfo &DCI) const {
19340 SelectionDAG &DAG = DCI.DAG;
19341 SDLoc SL(N);
19342 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
19343
19344 SDValue Src = N->getOperand(0);
19345 SDValue Shift = N->getOperand(0);
19346
19347 // TODO: Extend type shouldn't matter (assuming legal types).
19348 if (Shift.getOpcode() == ISD::ZERO_EXTEND)
19349 Shift = Shift.getOperand(0);
19350
19351 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
19352 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x
19353 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
19354 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
19355 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
19356 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
19357 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
19358 SDValue Shifted = DAG.getZExtOrTrunc(
19359 Shift.getOperand(0), SDLoc(Shift.getOperand(0)), MVT::i32);
19360
19361 unsigned ShiftOffset = 8 * Offset;
19362 if (Shift.getOpcode() == ISD::SHL)
19363 ShiftOffset -= C->getZExtValue();
19364 else
19365 ShiftOffset += C->getZExtValue();
19366
19367 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
19368 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
19369 MVT::f32, Shifted);
19370 }
19371 }
19372 }
19373
19375 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
19376 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
19377 // We simplified Src. If this node is not dead, visit it again so it is
19378 // folded properly.
19379 if (N->getOpcode() != ISD::DELETED_NODE)
19380 DCI.AddToWorklist(N);
19381 return SDValue(N, 0);
19382 }
19383
19384 // Handle (or x, (srl y, 8)) pattern when known bits are zero.
19385 if (SDValue DemandedSrc =
19386 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
19387 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
19388
19389 return SDValue();
19390}
19391
19392SDValue SITargetLowering::performClampCombine(SDNode *N,
19393 DAGCombinerInfo &DCI) const {
19394 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
19395 if (!CSrc)
19396 return SDValue();
19397
19398 const MachineFunction &MF = DCI.DAG.getMachineFunction();
19399 const APFloat &F = CSrc->getValueAPF();
19400 APFloat Zero = APFloat::getZero(F.getSemantics());
19401 if (F < Zero ||
19402 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
19403 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
19404 }
19405
19406 APFloat One = APFloat::getOne(F.getSemantics());
19407 if (F > One)
19408 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
19409
19410 return getCanonicalConstantFP(DCI.DAG, SDLoc(N), N->getValueType(0), F);
19411}
19412
19413// Check if V is the exponent result of a frexp operation. Returns the frexp
19414// input via FrexpInput if matched. We only match the exponent (not mantissa)
19415// because V_FREXP_MANT returns its input for Inf/NaN, not zero.
19416static bool isFrexpExp(SDValue V, SDValue &FrexpInput) {
19417 // ISD::FFREXP returns {mant, exp} - only match if using the exp result
19418 // (result number 1).
19419 if (V.getOpcode() == ISD::FFREXP && V.getResNo() == 1) {
19420 FrexpInput = V.getOperand(0);
19421 return true;
19422 }
19424 m_Value(FrexpInput))))
19425 return true;
19426 return false;
19427}
19428
19429SDValue
19430SITargetLowering::performFrexpSelectCombine(SDNode *N,
19431 DAGCombinerInfo &DCI) const {
19432 // This optimization only applies when the hardware handles inf/nan correctly.
19433 if (Subtarget->hasFractBug())
19434 return SDValue();
19435
19436 SDValue Cond = N->getOperand(0);
19437 SDValue TrueVal = N->getOperand(1);
19438 SDValue FalseVal = N->getOperand(2);
19439
19440 // Identify which operand is the frexp result and which is the zero constant.
19441 // Pattern 1: select cond, 0, frexp_result (cond true -> return 0)
19442 // Pattern 2: select cond, frexp_result, 0 (cond false -> return 0)
19443 SDValue FrexpVal;
19444 SDValue ZeroVal;
19445 bool CondSelectsZero; // If true, condition=true selects zero
19446
19447 // Check if FrexpVal comes from ISD::FFREXP (exponent result only) or
19448 // amdgcn_frexp_exp intrinsic.
19449 SDValue FrexpInput;
19450 if (isFrexpExp(FalseVal, FrexpInput)) {
19451 FrexpVal = FalseVal;
19452 ZeroVal = TrueVal;
19453 CondSelectsZero = true;
19454 } else if (isFrexpExp(TrueVal, FrexpInput)) {
19455 FrexpVal = TrueVal;
19456 ZeroVal = FalseVal;
19457 CondSelectsZero = false;
19458 } else {
19459 return SDValue();
19460 }
19461
19462 // frexp_exp returns integer, so check for integer zero.
19463 if (!isNullConstant(ZeroVal))
19464 return SDValue();
19465
19466 // The frexp intrinsics ignore sign, so we can strip sign ops when comparing.
19467 SDValue FrexpInputStripped = peekFPSignOps(FrexpInput);
19468
19469 bool IsNonFiniteTest = false;
19470
19471 // Handle SETCC conditions for inf/nan tests.
19472 // The canonical form of these checks is fcmp + fabs.
19473 if (Cond.getOpcode() == ISD::SETCC) {
19474 ISD::CondCode CC = Cond.getOperandCondCode(2);
19475 SDValue CondLHS = Cond.getOperand(0);
19476 SDValue CondRHS = Cond.getOperand(1);
19477
19478 // Check if LHS is fabs(FrexpInput) - required for infinity comparisons.
19479 SDValue FAbsInput;
19480 bool LHSIsFabs = sd_match(CondLHS, m_FAbs(m_Value(FAbsInput)));
19481 bool LHSMatchesFrexp =
19482 (CondLHS == FrexpInput) ||
19483 (LHSIsFabs && peekFPSignOps(FAbsInput) == FrexpInputStripped) ||
19484 (peekFPSignOps(CondLHS) == FrexpInputStripped);
19485 bool RHSMatchesFrexp = (CondRHS == FrexpInput) ||
19486 (peekFPSignOps(CondRHS) == FrexpInputStripped);
19487
19488 if (CC == ISD::SETUO) {
19489 // fcmp uno x, y - true if either x or y is NaN
19490 // We can only fold if the non-frexp operand is known to never be NaN,
19491 // otherwise the comparison could be true due to the other operand.
19492 // Special case: fcmp uno x, x (same operand) is a valid NaN test.
19493 SelectionDAG &DAG = DCI.DAG;
19494 if (LHSMatchesFrexp &&
19495 (CondLHS == CondRHS || DAG.isKnownNeverNaN(CondRHS)))
19496 IsNonFiniteTest = CondSelectsZero;
19497 else if (RHSMatchesFrexp && DAG.isKnownNeverNaN(CondLHS))
19498 IsNonFiniteTest = CondSelectsZero;
19499 } else if ((CC == ISD::SETOEQ || CC == ISD::SETUEQ) && LHSMatchesFrexp &&
19500 LHSIsFabs &&
19501 sd_match(CondRHS,
19503 CondRHS.getValueType().getFltSemantics())))) {
19504 // fcmp oeq/ueq fabs(x), +inf - true if x is inf (or inf/nan for ueq)
19505 IsNonFiniteTest = CondSelectsZero;
19506 } else if ((CC == ISD::SETONE || CC == ISD::SETUNE) && LHSMatchesFrexp &&
19507 LHSIsFabs &&
19508 sd_match(CondRHS,
19510 CondRHS.getValueType().getFltSemantics())))) {
19511 // fcmp one/une fabs(x), +inf - true if x is NOT inf
19512 IsNonFiniteTest = !CondSelectsZero;
19513 } else if (CC == ISD::SETO) {
19514 // fcmp ord x, y - true if both are NOT NaN
19515 // We can only fold if the non-frexp operand is known to never be NaN,
19516 // otherwise the comparison could be false due to the other operand.
19517 // Special case: fcmp ord x, x (same operand) is a valid not-NaN test.
19518 SelectionDAG &DAG = DCI.DAG;
19519 if (LHSMatchesFrexp &&
19520 (CondLHS == CondRHS || DAG.isKnownNeverNaN(CondRHS)))
19521 IsNonFiniteTest = !CondSelectsZero;
19522 else if (RHSMatchesFrexp && DAG.isKnownNeverNaN(CondLHS))
19523 IsNonFiniteTest = !CondSelectsZero;
19524 }
19525 } else if (Cond.getOpcode() == AMDGPUISD::FP_CLASS &&
19526 peekFPSignOps(Cond.getOperand(0)) == FrexpInputStripped) {
19527 // The inf/nan tests above may already have been combined into an fp_class
19528 // test. The select only matters for the classes that select zero, so it can
19529 // be eliminated if none of them are finite.
19530 if (const auto *CMask = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) {
19531 const unsigned FiniteMask =
19535 unsigned Mask = CMask->getZExtValue();
19536 unsigned ZeroMask = CondSelectsZero ? Mask : ~Mask;
19537 IsNonFiniteTest = (ZeroMask & FiniteMask) == 0;
19538 }
19539 }
19540
19541 if (!IsNonFiniteTest)
19542 return SDValue();
19543
19544 // The select can be eliminated - just return the frexp result directly.
19545 return FrexpVal;
19546}
19547
19548SDValue SITargetLowering::performSelectCombine(SDNode *N,
19549 DAGCombinerInfo &DCI) const {
19550
19551 // Try to fold CMP + SELECT patterns with shared constants (both FP and
19552 // integer).
19553 // Detect when CMP and SELECT use the same constant and fold them to avoid
19554 // loading the constant twice. Specifically handles patterns like:
19555 // %cmp = icmp eq i32 %val, 4242
19556 // %sel = select i1 %cmp, i32 4242, i32 %other
19557 // It can be optimized to reuse %val instead of 4242 in select.
19558 SDValue Cond = N->getOperand(0);
19559 SDValue TrueVal = N->getOperand(1);
19560 SDValue FalseVal = N->getOperand(2);
19561
19562 // Check if condition is a comparison.
19563 if (Cond.getOpcode() != ISD::SETCC)
19564 return SDValue();
19565
19566 SDValue LHS = Cond.getOperand(0);
19567 SDValue RHS = Cond.getOperand(1);
19568 ISD::CondCode CC = Cond.getOperandCondCode(2);
19569
19570 bool isFloatingPoint = LHS.getValueType().isFloatingPoint();
19571 bool isInteger = LHS.getValueType().isInteger();
19572
19573 // Handle simple floating-point and integer types only.
19574 if (!isFloatingPoint && !isInteger)
19575 return SDValue();
19576
19577 // Bare SETEQ/SETNE is the builder's NaN-impossible downgrade.
19578 bool isEquality = CC == ISD::SETEQ || (isFloatingPoint && CC == ISD::SETOEQ);
19579 bool isNonEquality =
19580 CC == ISD::SETNE || (isFloatingPoint && CC == ISD::SETONE);
19581 if (!isEquality && !isNonEquality)
19582 return SDValue();
19583
19584 SDValue ArgVal, ConstVal;
19585 if ((isFloatingPoint && isa<ConstantFPSDNode>(RHS)) ||
19586 (isInteger && isa<ConstantSDNode>(RHS))) {
19587 ConstVal = RHS;
19588 ArgVal = LHS;
19589 } else if ((isFloatingPoint && isa<ConstantFPSDNode>(LHS)) ||
19590 (isInteger && isa<ConstantSDNode>(LHS))) {
19591 ConstVal = LHS;
19592 ArgVal = RHS;
19593 } else {
19594 return SDValue();
19595 }
19596
19597 // Skip optimization for inlinable immediates.
19598 if (isFloatingPoint) {
19599 const APFloat &Val = cast<ConstantFPSDNode>(ConstVal)->getValueAPF();
19600 if (!Val.isNormal() || Subtarget->getInstrInfo()->isInlineConstant(Val))
19601 return SDValue();
19602 } else {
19603 const std::optional<int64_t> Val =
19604 cast<ConstantSDNode>(ConstVal)->getAPIntValue().trySExtValue();
19605 if (Val && AMDGPU::isInlinableIntLiteral(*Val))
19606 return SDValue();
19607 }
19608
19609 // For equality and non-equality comparisons, patterns:
19610 // select (setcc x, const), const, y -> select (setcc x, const), x, y
19611 // select (setccinv x, const), y, const -> select (setccinv x, const), y, x
19612 if (!(isEquality && TrueVal == ConstVal) &&
19613 !(isNonEquality && FalseVal == ConstVal))
19614 return SDValue();
19615
19616 // SETONE's false arm is also taken for NaN ArgVal, so require NaN excluded.
19617 if (isFloatingPoint && isNonEquality && FalseVal == ConstVal &&
19618 !Cond->getFlags().hasNoNaNs() && !DCI.DAG.isKnownNeverNaN(ArgVal))
19619 return SDValue();
19620
19621 SDValue SelectLHS = (isEquality && TrueVal == ConstVal) ? ArgVal : TrueVal;
19622 SDValue SelectRHS =
19623 (isNonEquality && FalseVal == ConstVal) ? ArgVal : FalseVal;
19624 return DCI.DAG.getNode(ISD::SELECT, SDLoc(N), N->getValueType(0), Cond,
19625 SelectLHS, SelectRHS);
19626}
19627
19629 DAGCombinerInfo &DCI) const {
19630 switch (N->getOpcode()) {
19631 case ISD::ABS:
19632 if (SDValue Res = promoteUniformUnaryOpToI32(SDValue(N, 0), DCI))
19633 return Res;
19634 break;
19635 case ISD::ADD:
19636 case ISD::SUB:
19637 case ISD::SHL:
19638 case ISD::SRL:
19639 case ISD::SRA:
19640 case ISD::AND:
19641 case ISD::OR:
19642 case ISD::XOR:
19643 case ISD::MUL:
19644 case ISD::SETCC:
19645 case ISD::SELECT:
19646 case ISD::SMIN:
19647 case ISD::SMAX:
19648 case ISD::UMIN:
19649 case ISD::UMAX:
19650 case ISD::USUBSAT:
19651 case ISD::UADDSAT:
19652 if (auto Res = promoteUniformOpToI32(SDValue(N, 0), DCI))
19653 return Res;
19654 break;
19655 case ISD::LOAD:
19656 case ISD::STORE:
19657 // TODO: Move this to LowerLOAD and LowerSTORE once the action of a
19658 // non-extending load or non-truncating store can depend on the address
19659 // space. Until then one whose action is Legal, such as i32, never reaches
19660 // them.
19662 if (SDValue V = lowerLoadStoreVGPR(SDValue(N, 0), DCI.DAG))
19663 return V;
19664 }
19665 break;
19666 default:
19667 break;
19668 }
19669
19670 if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
19671 return SDValue();
19672
19673 switch (N->getOpcode()) {
19674 case ISD::ADD:
19675 return performAddCombine(N, DCI);
19676 case ISD::PTRADD:
19677 return performPtrAddCombine(N, DCI);
19678 case ISD::SUB:
19679 return performSubCombine(N, DCI);
19680 case ISD::FADD:
19681 if (SDValue Res = splitPackedMathWithFAbsSource(N, DCI))
19682 return Res;
19683 return performFAddCombine(N, DCI);
19684 case ISD::FSUB:
19685 return performFSubCombine(N, DCI);
19686 case ISD::FDIV:
19687 return performFDivCombine(N, DCI);
19688 case ISD::FMUL:
19689 if (SDValue Res = splitPackedMathWithFAbsSource(N, DCI))
19690 return Res;
19691 return performFMulCombine(N, DCI);
19692 case ISD::SETCC:
19693 return performSetCCCombine(N, DCI);
19694 case ISD::SELECT:
19695 if (auto Res = performFrexpSelectCombine(N, DCI))
19696 return Res;
19697 if (auto Res = performSelectCombine(N, DCI))
19698 return Res;
19699 break;
19700 case ISD::FMAXNUM:
19701 case ISD::FMINNUM:
19702 case ISD::FMAXNUM_IEEE:
19703 case ISD::FMINNUM_IEEE:
19704 case ISD::FMAXIMUM:
19705 case ISD::FMINIMUM:
19706 case ISD::FMAXIMUMNUM:
19707 case ISD::FMINIMUMNUM:
19708 case ISD::SMAX:
19709 case ISD::SMIN:
19710 case ISD::UMAX:
19711 case ISD::UMIN:
19712 case AMDGPUISD::FMIN_LEGACY:
19713 case AMDGPUISD::FMAX_LEGACY:
19714 if (SDValue Res = splitPackedMathWithFAbsSource(N, DCI))
19715 return Res;
19716 return performMinMaxCombine(N, DCI);
19717 case ISD::FMA:
19718 if (SDValue Res = splitPackedMathWithFAbsSource(N, DCI))
19719 return Res;
19720 return performFMACombine(N, DCI);
19721 case ISD::AND:
19722 return performAndCombine(N, DCI);
19723 case ISD::OR:
19724 return performOrCombine(N, DCI);
19725 case ISD::FSHR: {
19727 if (N->getValueType(0) == MVT::i32 && N->isDivergent() &&
19728 TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
19729 return matchPERM(N, DCI);
19730 }
19731 break;
19732 }
19733 case ISD::XOR:
19734 return performXorCombine(N, DCI);
19735 case ISD::ANY_EXTEND:
19736 case ISD::ZERO_EXTEND:
19737 return performZeroOrAnyExtendCombine(N, DCI);
19738 case ISD::SIGN_EXTEND:
19739 return performExtendTruncShiftCombine(N, DCI);
19741 return performSignExtendInRegCombine(N, DCI);
19742 case AMDGPUISD::FP_CLASS:
19743 return performClassCombine(N, DCI);
19744 case ISD::FCANONICALIZE:
19745 return performFCanonicalizeCombine(N, DCI);
19746 case AMDGPUISD::RCP:
19747 return performRcpCombine(N, DCI);
19748 case ISD::FLDEXP:
19749 case AMDGPUISD::FRACT:
19750 case AMDGPUISD::RSQ:
19751 case AMDGPUISD::RCP_LEGACY:
19752 case AMDGPUISD::RCP_IFLAG:
19753 case AMDGPUISD::RSQ_CLAMP: {
19754 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
19755 SDValue Src = N->getOperand(0);
19756 if (Src.isUndef())
19757 return Src;
19758 break;
19759 }
19760 case ISD::SINT_TO_FP:
19761 case ISD::UINT_TO_FP:
19762 return performUCharToFloatCombine(N, DCI);
19763 case ISD::FCOPYSIGN:
19764 return performFCopySignCombine(N, DCI);
19765 case AMDGPUISD::CVT_F32_UBYTE0:
19766 case AMDGPUISD::CVT_F32_UBYTE1:
19767 case AMDGPUISD::CVT_F32_UBYTE2:
19768 case AMDGPUISD::CVT_F32_UBYTE3:
19769 return performCvtF32UByteNCombine(N, DCI);
19770 case AMDGPUISD::FMED3:
19771 return performFMed3Combine(N, DCI);
19772 case AMDGPUISD::CVT_PKRTZ_F16_F32:
19773 return performCvtPkRTZCombine(N, DCI);
19775 if (SDValue Res = performExponentOnlyScaleCombine(N, DCI))
19776 return Res;
19777 break;
19778 case AMDGPUISD::CLAMP:
19779 return performClampCombine(N, DCI);
19780 case ISD::SCALAR_TO_VECTOR: {
19781 SelectionDAG &DAG = DCI.DAG;
19782 EVT VT = N->getValueType(0);
19783
19784 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
19785 if (VT == MVT::v2i16 || VT == MVT::v2f16 || VT == MVT::v2bf16) {
19786 SDLoc SL(N);
19787 SDValue Src = N->getOperand(0);
19788 EVT EltVT = Src.getValueType();
19789 if (EltVT != MVT::i16)
19790 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
19791
19792 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
19793 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
19794 }
19795
19796 break;
19797 }
19799 return performExtractVectorEltCombine(N, DCI);
19801 return performInsertVectorEltCombine(N, DCI);
19802 case ISD::FP_ROUND:
19803 return performFPRoundCombine(N, DCI);
19804 case ISD::LOAD: {
19805 if (SDValue Widened = widenLoad(cast<LoadSDNode>(N), DCI))
19806 return Widened;
19807 [[fallthrough]];
19808 }
19809 default: {
19810 if (!DCI.isBeforeLegalize()) {
19811 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
19812 return performMemSDNodeCombine(MemNode, DCI);
19813 }
19814
19815 break;
19816 }
19817 }
19818
19820}
19821
19822/// Helper function for adjustWritemask
19823static unsigned SubIdx2Lane(unsigned Idx) {
19824 switch (Idx) {
19825 default:
19826 return ~0u;
19827 case AMDGPU::sub0:
19828 return 0;
19829 case AMDGPU::sub1:
19830 return 1;
19831 case AMDGPU::sub2:
19832 return 2;
19833 case AMDGPU::sub3:
19834 return 3;
19835 case AMDGPU::sub4:
19836 return 4; // Possible with TFE/LWE
19837 }
19838}
19839
19840/// Adjust the writemask of MIMG, VIMAGE or VSAMPLE instructions
19841SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
19842 SelectionDAG &DAG) const {
19843 unsigned Opcode = Node->getMachineOpcode();
19844
19845 // Subtract 1 because the vdata output is not a MachineSDNode operand.
19846 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
19847 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
19848 return Node; // not implemented for D16
19849
19850 SDNode *Users[5] = {nullptr};
19851 unsigned Lane = 0;
19852 unsigned DmaskIdx =
19853 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
19854 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
19855 unsigned NewDmask = 0;
19856 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
19857 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
19858 bool UsesTFC = (int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
19859 (int(LWEIdx) >= 0 && Node->getConstantOperandVal(LWEIdx));
19860 unsigned TFCLane = 0;
19861 bool HasChain = Node->getNumValues() > 1;
19862
19863 if (OldDmask == 0) {
19864 // These are folded out, but on the chance it happens don't assert.
19865 return Node;
19866 }
19867
19868 unsigned OldBitsSet = llvm::popcount(OldDmask);
19869 // Work out which is the TFE/LWE lane if that is enabled.
19870 if (UsesTFC) {
19871 TFCLane = OldBitsSet;
19872 }
19873
19874 // Try to figure out the used register components
19875 for (SDUse &Use : Node->uses()) {
19876
19877 // Don't look at users of the chain.
19878 if (Use.getResNo() != 0)
19879 continue;
19880
19881 SDNode *User = Use.getUser();
19882
19883 // Abort if we can't understand the usage
19884 if (!User->isMachineOpcode() ||
19885 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
19886 return Node;
19887
19888 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
19889 // Note that subregs are packed, i.e. Lane==0 is the first bit set
19890 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
19891 // set, etc.
19892 Lane = SubIdx2Lane(User->getConstantOperandVal(1));
19893 if (Lane == ~0u)
19894 return Node;
19895
19896 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
19897 if (UsesTFC && Lane == TFCLane) {
19898 Users[Lane] = User;
19899 } else {
19900 // Set which texture component corresponds to the lane.
19901 unsigned Comp;
19902 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
19903 Comp = llvm::countr_zero(Dmask);
19904 Dmask &= ~(1 << Comp);
19905 }
19906
19907 // Abort if we have more than one user per component.
19908 if (Users[Lane])
19909 return Node;
19910
19911 Users[Lane] = User;
19912 NewDmask |= 1 << Comp;
19913 }
19914 }
19915
19916 // Don't allow 0 dmask, as hardware assumes one channel enabled.
19917 bool NoChannels = !NewDmask;
19918 if (NoChannels) {
19919 if (!UsesTFC) {
19920 // No uses of the result and not using TFC. Then do nothing.
19921 return Node;
19922 }
19923 // If the original dmask has one channel - then nothing to do
19924 if (OldBitsSet == 1)
19925 return Node;
19926 // Use an arbitrary dmask - required for the instruction to work
19927 NewDmask = 1;
19928 }
19929 // Abort if there's no change
19930 if (NewDmask == OldDmask)
19931 return Node;
19932
19933 unsigned BitsSet = llvm::popcount(NewDmask);
19934
19935 // Check for TFE or LWE - increase the number of channels by one to account
19936 // for the extra return value
19937 // This will need adjustment for D16 if this is also included in
19938 // adjustWriteMask (this function) but at present D16 are excluded.
19939 unsigned NewChannels = BitsSet + UsesTFC;
19940
19941 int NewOpcode =
19942 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
19943 assert(NewOpcode != -1 &&
19944 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
19945 "failed to find equivalent MIMG op");
19946
19947 // Adjust the writemask in the node
19949 llvm::append_range(Ops, Node->ops().take_front(DmaskIdx));
19950 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
19951 llvm::append_range(Ops, Node->ops().drop_front(DmaskIdx + 1));
19952
19953 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
19954
19955 MVT ResultVT = NewChannels == 1
19956 ? SVT
19957 : MVT::getVectorVT(SVT, NewChannels == 3 ? 4
19958 : NewChannels == 5 ? 8
19959 : NewChannels);
19960 SDVTList NewVTList =
19961 HasChain ? DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
19962
19963 MachineSDNode *NewNode =
19964 DAG.getMachineNode(NewOpcode, SDLoc(Node), NewVTList, Ops);
19965
19966 if (HasChain) {
19967 // Update chain.
19968 DAG.setNodeMemRefs(NewNode, Node->memoperands());
19969 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
19970 }
19971
19972 if (NewChannels == 1) {
19973 assert(Node->hasNUsesOfValue(1, 0));
19974 SDNode *Copy =
19975 DAG.getMachineNode(TargetOpcode::COPY, SDLoc(Node),
19976 Users[Lane]->getValueType(0), SDValue(NewNode, 0));
19977 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
19978 return nullptr;
19979 }
19980
19981 // Update the users of the node with the new indices
19982 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
19983 SDNode *User = Users[i];
19984 if (!User) {
19985 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
19986 // Users[0] is still nullptr because channel 0 doesn't really have a use.
19987 if (i || !NoChannels)
19988 continue;
19989 } else {
19990 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
19991 SDNode *NewUser = DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
19992 if (NewUser != User) {
19993 DAG.ReplaceAllUsesWith(SDValue(User, 0), SDValue(NewUser, 0));
19994 DAG.RemoveDeadNode(User);
19995 }
19996 }
19997
19998 switch (Idx) {
19999 default:
20000 break;
20001 case AMDGPU::sub0:
20002 Idx = AMDGPU::sub1;
20003 break;
20004 case AMDGPU::sub1:
20005 Idx = AMDGPU::sub2;
20006 break;
20007 case AMDGPU::sub2:
20008 Idx = AMDGPU::sub3;
20009 break;
20010 case AMDGPU::sub3:
20011 Idx = AMDGPU::sub4;
20012 break;
20013 }
20014 }
20015
20016 DAG.RemoveDeadNode(Node);
20017 return nullptr;
20018}
20019
20021 if (Op.getOpcode() == ISD::AssertZext)
20022 Op = Op.getOperand(0);
20023
20024 return isa<FrameIndexSDNode>(Op);
20025}
20026
20027/// Legalize target independent instructions (e.g. INSERT_SUBREG)
20028/// with frame index operands.
20029/// LLVM assumes that inputs are to these instructions are registers.
20030SDNode *
20032 SelectionDAG &DAG) const {
20033 if (Node->getOpcode() == ISD::CopyToReg) {
20034 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
20035 SDValue SrcVal = Node->getOperand(2);
20036
20037 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
20038 // to try understanding copies to physical registers.
20039 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
20040 SDLoc SL(Node);
20042 SDValue VReg = DAG.getRegister(
20043 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
20044
20045 SDNode *Glued = Node->getGluedNode();
20046 SDValue ToVReg = DAG.getCopyToReg(
20047 Node->getOperand(0), SL, VReg, SrcVal,
20048 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
20049 SDValue ToResultReg = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
20050 VReg, ToVReg.getValue(1));
20051 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
20052 DAG.RemoveDeadNode(Node);
20053 return ToResultReg.getNode();
20054 }
20055 }
20056
20058 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
20059 if (!isFrameIndexOp(Node->getOperand(i))) {
20060 Ops.push_back(Node->getOperand(i));
20061 continue;
20062 }
20063
20064 SDLoc DL(Node);
20065 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
20066 Node->getOperand(i).getValueType(),
20067 Node->getOperand(i)),
20068 0));
20069 }
20070
20071 return DAG.UpdateNodeOperands(Node, Ops);
20072}
20073
20074/// Fold the instructions after selecting them.
20075/// Returns null if users were already updated.
20077 SelectionDAG &DAG) const {
20079 unsigned Opcode = Node->getMachineOpcode();
20080
20081 if (TII->isImage(Opcode) && !TII->get(Opcode).mayStore() &&
20082 !TII->isGather4(Opcode) &&
20083 AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::dmask)) {
20084 return adjustWritemask(Node, DAG);
20085 }
20086
20087 if (Opcode == AMDGPU::INSERT_SUBREG || Opcode == AMDGPU::REG_SEQUENCE) {
20089 return Node;
20090 }
20091
20092 switch (Opcode) {
20093 case AMDGPU::V_DIV_SCALE_F32_e64:
20094 case AMDGPU::V_DIV_SCALE_F64_e64: {
20095 // Satisfy the operand register constraint when one of the inputs is
20096 // undefined. Ordinarily each undef value will have its own implicit_def of
20097 // a vreg, so force these to use a single register.
20098 SDValue Src0 = Node->getOperand(1);
20099 SDValue Src1 = Node->getOperand(3);
20100 SDValue Src2 = Node->getOperand(5);
20101
20102 if ((Src0.isMachineOpcode() &&
20103 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
20104 (Src0 == Src1 || Src0 == Src2))
20105 break;
20106
20107 MVT VT = Src0.getValueType().getSimpleVT();
20108 const TargetRegisterClass *RC =
20109 getRegClassFor(VT, Src0.getNode()->isDivergent());
20110
20112 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
20113
20114 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), UndefReg,
20115 Src0, SDValue());
20116
20117 // src0 must be the same register as src1 or src2, even if the value is
20118 // undefined, so make sure we don't violate this constraint.
20119 if (Src0.isMachineOpcode() &&
20120 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
20121 if (Src1.isMachineOpcode() &&
20122 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
20123 Src0 = Src1;
20124 else if (Src2.isMachineOpcode() &&
20125 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
20126 Src0 = Src2;
20127 else {
20128 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
20129 Src0 = UndefReg;
20130 Src1 = UndefReg;
20131 }
20132 } else
20133 break;
20134
20136 Ops[1] = Src0;
20137 Ops[3] = Src1;
20138 Ops[5] = Src2;
20139 Ops.push_back(ImpDef.getValue(1));
20140 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
20141 }
20142 default:
20143 break;
20144 }
20145
20146 return Node;
20147}
20148
20149// Any MIMG instructions that use tfe or lwe require an initialization of the
20150// result register that will be written in the case of a memory access failure.
20151// The required code is also added to tie this init code to the result of the
20152// img instruction.
20155 const SIRegisterInfo &TRI = TII->getRegisterInfo();
20156 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
20157 MachineBasicBlock &MBB = *MI.getParent();
20158
20159 int DstIdx =
20160 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
20161 unsigned InitIdx = 0;
20162
20163 if (TII->isImage(MI)) {
20164 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
20165 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
20166 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
20167
20168 if (!TFE && !LWE) // intersect_ray
20169 return;
20170
20171 unsigned TFEVal = TFE ? TFE->getImm() : 0;
20172 unsigned LWEVal = LWE ? LWE->getImm() : 0;
20173 unsigned D16Val = D16 ? D16->getImm() : 0;
20174
20175 if (!TFEVal && !LWEVal)
20176 return;
20177
20178 // At least one of TFE or LWE are non-zero
20179 // We have to insert a suitable initialization of the result value and
20180 // tie this to the dest of the image instruction.
20181
20182 // Calculate which dword we have to initialize to 0.
20183 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
20184
20185 // check that dmask operand is found.
20186 assert(MO_Dmask && "Expected dmask operand in instruction");
20187
20188 unsigned dmask = MO_Dmask->getImm();
20189 // Determine the number of active lanes taking into account the
20190 // Gather4 special case
20191 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : llvm::popcount(dmask);
20192
20193 bool Packed = !Subtarget->hasUnpackedD16VMem();
20194
20195 InitIdx = D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
20196
20197 // Abandon attempt if the dst size isn't large enough
20198 // - this is in fact an error but this is picked up elsewhere and
20199 // reported correctly.
20200 const TargetRegisterClass *DstRC = TII->getRegClass(MI.getDesc(), DstIdx);
20201
20202 uint32_t DstSize = TRI.getRegSizeInBits(*DstRC) / 32;
20203 if (DstSize < InitIdx)
20204 return;
20205 } else if (TII->isMUBUF(MI) && AMDGPU::getMUBUFTfe(MI.getOpcode())) {
20206 const TargetRegisterClass *DstRC = TII->getRegClass(MI.getDesc(), DstIdx);
20207 InitIdx = TRI.getRegSizeInBits(*DstRC) / 32;
20208 } else {
20209 return;
20210 }
20211
20212 const DebugLoc &DL = MI.getDebugLoc();
20213
20214 // Create a register for the initialization value.
20215 Register PrevDst = MRI.cloneVirtualRegister(MI.getOperand(DstIdx).getReg());
20216 unsigned NewDst = 0; // Final initialized value will be in here
20217
20218 // If PRTStrictNull feature is enabled (the default) then initialize
20219 // all the result registers to 0, otherwise just the error indication
20220 // register (VGPRn+1)
20221 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
20222 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
20223
20224 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
20225 for (; SizeLeft; SizeLeft--, CurrIdx++) {
20226 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
20227 // Initialize dword
20228 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
20229 // clang-format off
20230 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
20231 .addImm(0);
20232 // clang-format on
20233 // Insert into the super-reg
20234 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
20235 .addReg(PrevDst)
20236 .addReg(SubReg)
20238
20239 PrevDst = NewDst;
20240 }
20241
20242 // Add as an implicit operand
20243 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
20244
20245 // Tie the just added implicit operand to the dst
20246 MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
20247}
20248
20249/// Assign the register class depending on the number of
20250/// bits set in the writemask
20252 SDNode *Node) const {
20254
20255 MachineFunction *MF = MI.getMF();
20257
20258 if (TII->isVOP3(MI.getOpcode())) {
20259 // Make sure constant bus requirements are respected.
20260 TII->legalizeOperandsVOP3(MRI, MI);
20261
20262 if (TII->isMAI(MI)) {
20263 // The ordinary src0, src1, src2 were legalized above.
20264 //
20265 // We have to also legalize the appended v_mfma_ld_scale_b32 operands,
20266 // as a separate instruction.
20267 int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
20268 AMDGPU::OpName::scale_src0);
20269 if (Src0Idx != -1) {
20270 int Src1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
20271 AMDGPU::OpName::scale_src1);
20272 if (TII->usesConstantBus(MRI, MI, Src0Idx) &&
20273 TII->usesConstantBus(MRI, MI, Src1Idx))
20274 TII->legalizeOpWithMove(MI, Src1Idx);
20275 }
20276 }
20277
20278 return;
20279 }
20280
20281 if (TII->isImage(MI))
20282 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
20283}
20284
20286 uint64_t Val) {
20287 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
20288 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
20289}
20290
20292 const SDLoc &DL,
20293 SDValue Ptr) const {
20295
20296 // Build the half of the subregister with the constants before building the
20297 // full 128-bit register. If we are building multiple resource descriptors,
20298 // this will allow CSEing of the 2-component register.
20299 const SDValue Ops0[] = {
20300 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
20301 buildSMovImm32(DAG, DL, 0),
20302 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
20303 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
20304 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
20305
20306 SDValue SubRegHi = SDValue(
20307 DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v2i32, Ops0), 0);
20308
20309 // Combine the constants and the pointer.
20310 const SDValue Ops1[] = {
20311 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), Ptr,
20312 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), SubRegHi,
20313 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)};
20314
20315 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
20316}
20317
20318/// Return a resource descriptor with the 'Add TID' bit enabled
20319/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
20320/// of the resource descriptor) to create an offset, which is added to
20321/// the resource pointer.
20323 SDValue Ptr, uint32_t RsrcDword1,
20324 uint64_t RsrcDword2And3) const {
20325 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
20326 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
20327 if (RsrcDword1) {
20328 PtrHi = DAG.getNode(ISD::OR, DL, MVT::i32, PtrHi,
20329 DAG.getConstant(RsrcDword1, DL, MVT::i32));
20330 }
20331
20332 SDValue DataLo =
20333 buildSMovImm32(DAG, DL, RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
20334 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
20335
20336 const SDValue Ops[] = {
20337 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
20338 PtrLo,
20339 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
20340 PtrHi,
20341 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
20342 DataLo,
20343 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
20344 DataHi,
20345 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)};
20346
20347 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
20348}
20349
20350//===----------------------------------------------------------------------===//
20351// SI Inline Assembly Support
20352//===----------------------------------------------------------------------===//
20353
20354std::pair<unsigned, const TargetRegisterClass *>
20356 StringRef Constraint,
20357 MVT VT) const {
20358 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
20359
20360 const TargetRegisterClass *RC = nullptr;
20361 if (Constraint.size() == 1) {
20362 // Check if we cannot determine the bit size of the given value type. This
20363 // can happen, for example, in this situation where we have an empty struct
20364 // (size 0): `call void asm "", "v"({} poison)`-
20365 if (VT == MVT::Other)
20366 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20367 const unsigned BitWidth = VT.getSizeInBits();
20368 switch (Constraint[0]) {
20369 default:
20370 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20371 case 's':
20372 case 'r':
20373 switch (BitWidth) {
20374 case 16:
20375 RC = &AMDGPU::SReg_32RegClass;
20376 break;
20377 case 64:
20378 RC = &AMDGPU::SGPR_64RegClass;
20379 break;
20380 default:
20382 if (!RC)
20383 return std::pair(0U, nullptr);
20384 break;
20385 }
20386 break;
20387 case 'v':
20388 switch (BitWidth) {
20389 case 1:
20390 return std::pair(0U, nullptr);
20391 case 16:
20392 RC = Subtarget->useRealTrue16Insts() ? &AMDGPU::VGPR_16RegClass
20393 : &AMDGPU::VGPR_32_Lo256RegClass;
20394 break;
20395 default:
20396 RC = Subtarget->hasVGPRMSBs()
20397 ? TRI->getAlignedLo256VGPRClassForBitWidth(BitWidth)
20398 : TRI->getVGPRClassForBitWidth(BitWidth);
20399 if (!RC)
20400 return std::pair(0U, nullptr);
20401 break;
20402 }
20403 break;
20404 case 'a':
20405 if (!Subtarget->hasMAIInsts())
20406 break;
20407 switch (BitWidth) {
20408 case 1:
20409 return std::pair(0U, nullptr);
20410 case 16:
20411 RC = &AMDGPU::AGPR_32RegClass;
20412 break;
20413 default:
20414 RC = TRI->getAGPRClassForBitWidth(BitWidth);
20415 if (!RC)
20416 return std::pair(0U, nullptr);
20417 break;
20418 }
20419 break;
20420 }
20421 } else if (Constraint == "VA" && Subtarget->hasGFX90AInsts()) {
20422 const unsigned BitWidth = VT.getSizeInBits();
20423 switch (BitWidth) {
20424 case 16:
20425 RC = &AMDGPU::AV_32RegClass;
20426 break;
20427 default:
20428 RC = TRI->getVectorSuperClassForBitWidth(BitWidth);
20429 if (!RC)
20430 return std::pair(0U, nullptr);
20431 break;
20432 }
20433 }
20434
20435 // We actually support i128, i16 and f16 as inline parameters
20436 // even if they are not reported as legal
20437 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
20438 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
20439 return std::pair(0U, RC);
20440
20441 auto [Kind, Idx, NumRegs] = AMDGPU::parseAsmConstraintPhysReg(Constraint);
20442 if (Kind != '\0') {
20443 if (Kind == 'v') {
20444 RC = &AMDGPU::VGPR_32_Lo256RegClass;
20445 } else if (Kind == 's') {
20446 RC = &AMDGPU::SGPR_32RegClass;
20447 } else if (Kind == 'a') {
20448 RC = &AMDGPU::AGPR_32RegClass;
20449 }
20450
20451 if (RC) {
20452 if (NumRegs > 1) {
20453 if (Idx >= RC->getNumRegs() || Idx + NumRegs - 1 >= RC->getNumRegs())
20454 return std::pair(0U, nullptr);
20455
20456 uint32_t Width = NumRegs * 32;
20457 // Prohibit constraints for register ranges with a width that does not
20458 // match the required type.
20459 if (VT.SimpleTy != MVT::Other && Width != VT.getSizeInBits())
20460 return std::pair(0U, nullptr);
20461
20462 MCRegister Reg = RC->getRegister(Idx);
20464 RC = TRI->getVGPRClassForBitWidth(Width);
20465 else if (SIRegisterInfo::isSGPRClass(RC))
20466 RC = TRI->getSGPRClassForBitWidth(Width);
20467 else if (SIRegisterInfo::isAGPRClass(RC))
20468 RC = TRI->getAGPRClassForBitWidth(Width);
20469 if (RC) {
20470 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
20471 if (!Reg) {
20472 // The register class does not contain the requested register,
20473 // e.g., because it is an SGPR pair that would violate alignment
20474 // requirements.
20475 return std::pair(0U, nullptr);
20476 }
20477 return std::pair(Reg, RC);
20478 }
20479 }
20480
20481 // Reject types that do not fit a single 32-bit register: any scalar wider
20482 // than 32 bits, or a vector that is not exactly 32 bits.
20483 if (VT.SimpleTy != MVT::Other &&
20484 (VT.getSizeInBits() > 32 ||
20485 (VT.isVector() && VT.getSizeInBits() != 32)))
20486 return std::pair(0U, nullptr);
20487 if (RC && Idx < RC->getNumRegs())
20488 return std::pair(RC->getRegister(Idx), RC);
20489 return std::pair(0U, nullptr);
20490 }
20491 }
20492
20493 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20494 if (Ret.first) {
20495 Ret.second = TRI->getPhysRegBaseClass(Ret.first);
20496 if (!Subtarget->useRealTrue16Insts() &&
20497 TRI->getRegSizeInBits(*Ret.second) == 16)
20498 return std::pair(0U, nullptr);
20499 }
20500
20501 return Ret;
20502}
20503
20504static bool isImmConstraint(StringRef Constraint) {
20505 if (Constraint.size() == 1) {
20506 switch (Constraint[0]) {
20507 default:
20508 break;
20509 case 'I':
20510 case 'J':
20511 case 'A':
20512 case 'B':
20513 case 'C':
20514 return true;
20515 }
20516 } else if (Constraint == "DA" || Constraint == "DB") {
20517 return true;
20518 }
20519 return false;
20520}
20521
20524 if (Constraint.size() == 1) {
20525 switch (Constraint[0]) {
20526 default:
20527 break;
20528 case 's':
20529 case 'v':
20530 case 'a':
20531 return C_RegisterClass;
20532 case 'm':
20533 return C_Memory;
20534 }
20535 } else if (Constraint.size() == 2) {
20536 if (Constraint == "VA")
20537 return C_RegisterClass;
20538 if (Constraint == "RF")
20539 return C_Memory;
20540 }
20541 if (isImmConstraint(Constraint)) {
20542 return C_Other;
20543 }
20544 return TargetLowering::getConstraintType(Constraint);
20545}
20546
20549 if (ConstraintCode == "RF")
20551
20552 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
20553}
20554
20555static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
20557 Val = Val & maskTrailingOnes<uint64_t>(Size);
20558 }
20559 return Val;
20560}
20561
20563 StringRef Constraint,
20564 std::vector<SDValue> &Ops,
20565 SelectionDAG &DAG) const {
20566 if (isImmConstraint(Constraint)) {
20567 uint64_t Val;
20568 if (getAsmOperandConstVal(Op, Val) &&
20569 checkAsmConstraintVal(Op, Constraint, Val)) {
20570 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
20571 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
20572 }
20573 } else {
20575 }
20576}
20577
20579 unsigned Size = Op.getScalarValueSizeInBits();
20580 if (Size > 64)
20581 return false;
20582
20583 if (Size == 16 && !Subtarget->has16BitInsts())
20584 return false;
20585
20587 Val = C->getSExtValue();
20588 return true;
20589 }
20591 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
20592 return true;
20593 }
20595 if (Size != 16 || Op.getNumOperands() != 2)
20596 return false;
20597 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
20598 return false;
20599 if (ConstantSDNode *C = V->getConstantSplatNode()) {
20600 Val = C->getSExtValue();
20601 return true;
20602 }
20603 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
20604 Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
20605 return true;
20606 }
20607 }
20608
20609 return false;
20610}
20611
20613 uint64_t Val) const {
20614 if (Constraint.size() == 1) {
20615 switch (Constraint[0]) {
20616 case 'I':
20618 case 'J':
20619 return isInt<16>(Val);
20620 case 'A':
20621 return checkAsmConstraintValA(Op, Val);
20622 case 'B':
20623 return isInt<32>(Val);
20624 case 'C':
20625 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
20627 default:
20628 break;
20629 }
20630 } else if (Constraint.size() == 2) {
20631 if (Constraint == "DA") {
20632 int64_t HiBits = static_cast<int32_t>(Val >> 32);
20633 int64_t LoBits = static_cast<int32_t>(Val);
20634 return checkAsmConstraintValA(Op, HiBits, 32) &&
20635 checkAsmConstraintValA(Op, LoBits, 32);
20636 }
20637 if (Constraint == "DB") {
20638 return true;
20639 }
20640 }
20641 llvm_unreachable("Invalid asm constraint");
20642}
20643
20645 unsigned MaxSize) const {
20646 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
20647 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
20648 if (Size == 16) {
20649 MVT VT = Op.getSimpleValueType();
20650 switch (VT.SimpleTy) {
20651 default:
20652 return false;
20653 case MVT::i16:
20654 return AMDGPU::isInlinableLiteralI16(Val, HasInv2Pi);
20655 case MVT::f16:
20656 return AMDGPU::isInlinableLiteralFP16(Val, HasInv2Pi);
20657 case MVT::bf16:
20658 return AMDGPU::isInlinableLiteralBF16(Val, HasInv2Pi);
20659 case MVT::v2i16:
20660 return AMDGPU::getInlineEncodingV2I16(Val).has_value();
20661 case MVT::v2f16:
20662 return AMDGPU::getInlineEncodingV2F16(Val).has_value();
20663 case MVT::v2bf16:
20664 return AMDGPU::getInlineEncodingV2BF16(Val).has_value();
20665 }
20666 }
20667 if ((Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
20668 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi)))
20669 return true;
20670 return false;
20671}
20672
20673static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
20674 switch (UnalignedClassID) {
20675 case AMDGPU::VReg_64RegClassID:
20676 return AMDGPU::VReg_64_Align2RegClassID;
20677 case AMDGPU::VReg_96RegClassID:
20678 return AMDGPU::VReg_96_Align2RegClassID;
20679 case AMDGPU::VReg_128RegClassID:
20680 return AMDGPU::VReg_128_Align2RegClassID;
20681 case AMDGPU::VReg_160RegClassID:
20682 return AMDGPU::VReg_160_Align2RegClassID;
20683 case AMDGPU::VReg_192RegClassID:
20684 return AMDGPU::VReg_192_Align2RegClassID;
20685 case AMDGPU::VReg_224RegClassID:
20686 return AMDGPU::VReg_224_Align2RegClassID;
20687 case AMDGPU::VReg_256RegClassID:
20688 return AMDGPU::VReg_256_Align2RegClassID;
20689 case AMDGPU::VReg_288RegClassID:
20690 return AMDGPU::VReg_288_Align2RegClassID;
20691 case AMDGPU::VReg_320RegClassID:
20692 return AMDGPU::VReg_320_Align2RegClassID;
20693 case AMDGPU::VReg_352RegClassID:
20694 return AMDGPU::VReg_352_Align2RegClassID;
20695 case AMDGPU::VReg_384RegClassID:
20696 return AMDGPU::VReg_384_Align2RegClassID;
20697 case AMDGPU::VReg_512RegClassID:
20698 return AMDGPU::VReg_512_Align2RegClassID;
20699 case AMDGPU::VReg_1024RegClassID:
20700 return AMDGPU::VReg_1024_Align2RegClassID;
20701 case AMDGPU::AReg_64RegClassID:
20702 return AMDGPU::AReg_64_Align2RegClassID;
20703 case AMDGPU::AReg_96RegClassID:
20704 return AMDGPU::AReg_96_Align2RegClassID;
20705 case AMDGPU::AReg_128RegClassID:
20706 return AMDGPU::AReg_128_Align2RegClassID;
20707 case AMDGPU::AReg_160RegClassID:
20708 return AMDGPU::AReg_160_Align2RegClassID;
20709 case AMDGPU::AReg_192RegClassID:
20710 return AMDGPU::AReg_192_Align2RegClassID;
20711 case AMDGPU::AReg_256RegClassID:
20712 return AMDGPU::AReg_256_Align2RegClassID;
20713 case AMDGPU::AReg_512RegClassID:
20714 return AMDGPU::AReg_512_Align2RegClassID;
20715 case AMDGPU::AReg_1024RegClassID:
20716 return AMDGPU::AReg_1024_Align2RegClassID;
20717 default:
20718 return -1;
20719 }
20720}
20721
20722// Figure out which registers should be reserved for stack access. Only after
20723// the function is legalized do we know all of the non-spill stack objects or if
20724// calls are present.
20728 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
20729 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
20730 const SIInstrInfo *TII = ST.getInstrInfo();
20731
20732 if (Info->isEntryFunction()) {
20733 // Callable functions have fixed registers used for stack access.
20735 }
20736
20737 // TODO: Move this logic to getReservedRegs()
20738 // Reserve the SGPR(s) to save/restore EXEC for WWM spill/copy handling.
20739 unsigned MaxNumSGPRs = ST.getMaxNumSGPRs(MF);
20740 Register SReg = ST.isWave32()
20741 ? AMDGPU::SGPR_32RegClass.getRegister(MaxNumSGPRs - 1)
20742 : TRI->getAlignedHighSGPRForRC(MF, /*Align=*/2,
20743 &AMDGPU::SGPR_64RegClass);
20744 Info->setSGPRForEXECCopy(SReg);
20745
20746 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
20747 Info->getStackPtrOffsetReg()));
20748 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
20749 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
20750
20751 // We need to worry about replacing the default register with itself in case
20752 // of MIR testcases missing the MFI.
20753 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
20754 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
20755
20756 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
20757 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
20758
20759 Info->limitOccupancy(MF);
20760
20761 if (ST.isWave32() && !MF.empty()) {
20762 for (auto &MBB : MF) {
20763 for (auto &MI : MBB) {
20764 TII->fixImplicitOperands(MI);
20765 }
20766 }
20767 }
20768
20769 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
20770 // classes if required. Ideally the register class constraints would differ
20771 // per-subtarget, but there's no easy way to achieve that right now. This is
20772 // not a problem for VGPRs because the correctly aligned VGPR class is implied
20773 // from using them as the register class for legal types.
20774 if (ST.needsAlignedVGPRs()) {
20775 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
20776 const Register Reg = Register::index2VirtReg(I);
20777 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
20778 if (!RC)
20779 continue;
20780 int NewClassID = getAlignedAGPRClassID(RC->getID());
20781 if (NewClassID != -1)
20782 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
20783 }
20784 }
20785
20787}
20788
20791 const APInt &DemandedElts,
20792 const SelectionDAG &DAG,
20793 unsigned Depth) const {
20794 Known.resetAll();
20795 unsigned Opc = Op.getOpcode();
20796 switch (Opc) {
20798 unsigned IID = Op.getConstantOperandVal(0);
20799 switch (IID) {
20800 case Intrinsic::amdgcn_mbcnt_lo:
20801 case Intrinsic::amdgcn_mbcnt_hi: {
20802 const GCNSubtarget &ST =
20804 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
20805 // most 31 + src1.
20806 Known.Zero.setBitsFrom(
20807 IID == Intrinsic::amdgcn_mbcnt_lo ? ST.getWavefrontSizeLog2() : 5);
20808 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(2), Depth + 1);
20809 Known = KnownBits::add(Known, Known2);
20810 return;
20811 }
20812 }
20813 break;
20814 }
20815 }
20817 Op, Known, DemandedElts, DAG, Depth);
20818}
20819
20821 KnownBits &Known, const MachineFunction &MF, Align Alignment) const {
20823
20824 // Set the high bits to zero based on the maximum allowed scratch size per
20825 // wave. We can't use vaddr in MUBUF instructions if we don't know the address
20826 // calculation won't overflow, so assume the sign bit is never set.
20827 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
20828}
20829
20832 unsigned Dim) {
20833 unsigned MaxValue =
20834 ST.getMaxWorkitemID(VT.getMachineFunction().getFunction(), Dim);
20835 Known.Zero.setHighBits(llvm::countl_zero(MaxValue));
20836}
20837
20839 KnownBits &Known, const APInt &DemandedElts,
20840 unsigned BFEWidth, bool SExt, unsigned Depth) {
20842 const MachineOperand &Src1 = MI.getOperand(2);
20843
20844 unsigned Src1Cst = 0;
20845 if (Src1.isImm()) {
20846 Src1Cst = Src1.getImm();
20847 } else if (Src1.isReg()) {
20848 auto Cst = getIConstantVRegValWithLookThrough(Src1.getReg(), MRI);
20849 if (!Cst)
20850 return;
20851 Src1Cst = Cst->Value.getZExtValue();
20852 } else {
20853 return;
20854 }
20855
20856 // Offset is at bits [4:0] for 32 bit, [5:0] for 64 bit.
20857 // Width is always [22:16].
20858 const unsigned Offset =
20859 Src1Cst & maskTrailingOnes<unsigned>((BFEWidth == 32) ? 5 : 6);
20860 const unsigned Width = (Src1Cst >> 16) & maskTrailingOnes<unsigned>(6);
20861
20862 if (Width >= BFEWidth) // Ill-formed.
20863 return;
20864
20865 VT.computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
20866 Depth + 1);
20867
20868 Known = Known.extractBits(Width, Offset);
20869
20870 if (SExt)
20871 Known = Known.sext(BFEWidth);
20872 else
20873 Known = Known.zext(BFEWidth);
20874}
20875
20878 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
20879 unsigned Depth) const {
20880 Known.resetAll();
20881 const MachineInstr *MI = MRI.getVRegDef(R);
20882 switch (MI->getOpcode()) {
20883 case AMDGPU::S_BFE_I32:
20884 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/32,
20885 /*SExt=*/true, Depth);
20886 case AMDGPU::S_BFE_U32:
20887 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/32,
20888 /*SExt=*/false, Depth);
20889 case AMDGPU::S_BFE_I64:
20890 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/64,
20891 /*SExt=*/true, Depth);
20892 case AMDGPU::S_BFE_U64:
20893 return knownBitsForSBFE(*MI, VT, Known, DemandedElts, /*Width=*/64,
20894 /*SExt=*/false, Depth);
20895 case AMDGPU::G_INTRINSIC:
20896 case AMDGPU::G_INTRINSIC_CONVERGENT: {
20897 Intrinsic::ID IID = cast<GIntrinsic>(MI)->getIntrinsicID();
20898 switch (IID) {
20899 case Intrinsic::amdgcn_workitem_id_x:
20901 break;
20902 case Intrinsic::amdgcn_workitem_id_y:
20904 break;
20905 case Intrinsic::amdgcn_workitem_id_z:
20907 break;
20908 case Intrinsic::amdgcn_mbcnt_lo:
20909 case Intrinsic::amdgcn_mbcnt_hi: {
20910 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
20911 // most 31 + src1.
20912 Known.Zero.setBitsFrom(IID == Intrinsic::amdgcn_mbcnt_lo
20913 ? getSubtarget()->getWavefrontSizeLog2()
20914 : 5);
20915 KnownBits Known2;
20916 VT.computeKnownBitsImpl(MI->getOperand(3).getReg(), Known2, DemandedElts,
20917 Depth + 1);
20918 Known = KnownBits::add(Known, Known2);
20919 break;
20920 }
20921 case Intrinsic::amdgcn_groupstaticsize: {
20922 // We can report everything over the maximum size as 0. We can't report
20923 // based on the actual size because we don't know if it's accurate or not
20924 // at any given point.
20925 Known.Zero.setHighBits(
20926 llvm::countl_zero(getSubtarget()->getAddressableLocalMemorySize()));
20927 break;
20928 }
20929 case Intrinsic::amdgcn_readfirstlane:
20930 case Intrinsic::amdgcn_readlane: {
20931 // Result is the data operand's value from some lane.
20932 VT.computeKnownBitsImpl(MI->getOperand(2).getReg(), Known, DemandedElts,
20933 Depth + 1);
20934 break;
20935 }
20936 case Intrinsic::amdgcn_mul_u24:
20937 case Intrinsic::amdgcn_mul_i24: {
20938 Register LHS = MI->getOperand(2).getReg();
20939 Register RHS = MI->getOperand(3).getReg();
20940
20941 KnownBits RHSKnown;
20942 VT.computeKnownBitsImpl(RHS, RHSKnown, DemandedElts, Depth + 1);
20943
20944 bool SelfMultiply = LHS == RHS;
20945
20946 // For a self-multiply both operands are the same value, so RHSKnown also
20947 // describes the LHS; avoid the duplicated query.
20948 KnownBits LHSKnown;
20949 if (SelfMultiply)
20950 LHSKnown = RHSKnown;
20951 else
20952 VT.computeKnownBitsImpl(LHS, LHSKnown, DemandedElts, Depth + 1);
20953
20954 if (SelfMultiply)
20955 SelfMultiply &= isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1);
20956
20957 Known = computeKnownBitsForMul24(LHSKnown, RHSKnown, Known.getBitWidth(),
20958 IID == Intrinsic::amdgcn_mul_i24,
20959 SelfMultiply);
20960 break;
20961 }
20962 }
20963 break;
20964 }
20965 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
20966 Known.Zero.setHighBits(24);
20967 break;
20968 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
20969 Known.Zero.setHighBits(16);
20970 break;
20971 case AMDGPU::G_AMDGPU_COPY_SCC_VCC:
20972 // G_AMDGPU_COPY_SCC_VCC converts a uniform boolean in VCC to SGPR s32,
20973 // producing exactly 0 or 1.
20974 Known.Zero.setHighBits(Known.getBitWidth() - 1);
20975 break;
20976 case AMDGPU::G_AMDGPU_SMED3:
20977 case AMDGPU::G_AMDGPU_UMED3: {
20978 auto [Dst, Src0, Src1, Src2] = MI->getFirst4Regs();
20979
20980 KnownBits Known2;
20981 VT.computeKnownBitsImpl(Src2, Known2, DemandedElts, Depth + 1);
20982 if (Known2.isUnknown())
20983 break;
20984
20985 KnownBits Known1;
20986 VT.computeKnownBitsImpl(Src1, Known1, DemandedElts, Depth + 1);
20987 if (Known1.isUnknown())
20988 break;
20989
20990 KnownBits Known0;
20991 VT.computeKnownBitsImpl(Src0, Known0, DemandedElts, Depth + 1);
20992 if (Known0.isUnknown())
20993 break;
20994
20995 // TODO: Handle LeadZero/LeadOne from UMIN/UMAX handling.
20996 Known.Zero = Known0.Zero & Known1.Zero & Known2.Zero;
20997 Known.One = Known0.One & Known1.One & Known2.One;
20998 break;
20999 }
21000 }
21001}
21002
21005 unsigned Depth) const {
21006 const MachineInstr *MI = MRI.getVRegDef(R);
21007 if (auto *GI = dyn_cast<GIntrinsic>(MI)) {
21008 // FIXME: Can this move to generic code? What about the case where the call
21009 // site specifies a lower alignment?
21010 Intrinsic::ID IID = GI->getIntrinsicID();
21012 AttributeList Attrs =
21013 Intrinsic::getAttributes(Ctx, IID, Intrinsic::getType(Ctx, IID));
21014 if (MaybeAlign RetAlign = Attrs.getRetAlignment())
21015 return *RetAlign;
21016 }
21017 return Align(1);
21018}
21019
21021 MachineLoop *ML, const MachineBasicBlock *BlockToAlign) const {
21023 const Align CacheLineAlign = Align(64);
21024
21025 // GFX950: Prevent an 8-byte instruction at the block being aligned from being
21026 // split by the 32-byte instruction fetch window boundary. This avoids a
21027 // significant fetch delay after a backward branch. We use 32-byte alignment
21028 // with max padding of 4 bytes (one s_nop), see
21029 // getMaxPermittedBytesForAlignment().
21030 if (ML && getSubtarget()->getCLOpts().loop_alignment &&
21031 getSubtarget()->hasLoopHeadInstSplitSensitivity()) {
21032 // Loop rotation can make the backedge destination a block other than the
21033 // LoopInfo header, so prefer the block the caller is actually aligning.
21034 if (!BlockToAlign)
21035 BlockToAlign = ML->getHeader();
21036 // Respect user-specified or previously set alignment.
21037 if (BlockToAlign->getAlignment() != PrefAlign)
21038 return BlockToAlign->getAlignment();
21039 if (needsFetchWindowAlignment(*BlockToAlign))
21040 return Align(32);
21041 }
21042
21043 // Pre-GFX10 target did not benefit from loop alignment
21044 if (!ML || !getSubtarget()->getCLOpts().loop_alignment ||
21045 !getSubtarget()->hasInstPrefetch() ||
21046 getSubtarget()->hasInstFwdPrefetchBug())
21047 return PrefAlign;
21048
21049 // On GFX10 I$ is 4 x 64 bytes cache lines.
21050 // By default prefetcher keeps one cache line behind and reads two ahead.
21051 // We can modify it with S_INST_PREFETCH for larger loops to have two lines
21052 // behind and one ahead.
21053 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
21054 // If loop fits 64 bytes it always spans no more than two cache lines and
21055 // does not need an alignment.
21056 // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
21057 // Else if loop is less or equal 192 bytes we need two lines behind.
21058
21060 const MachineBasicBlock *Header = ML->getHeader();
21061 if (Header->getAlignment() != PrefAlign)
21062 return Header->getAlignment(); // Already processed.
21063
21064 unsigned LoopSize = 0;
21065 for (const MachineBasicBlock *MBB : ML->blocks()) {
21066 // If inner loop block is aligned assume in average half of the alignment
21067 // size to be added as nops.
21068 if (MBB != Header)
21069 LoopSize += MBB->getAlignment().value() / 2;
21070
21071 for (const MachineInstr &MI : *MBB) {
21072 LoopSize += TII->getInstSizeInBytes(MI);
21073 if (LoopSize > 192)
21074 return PrefAlign;
21075 }
21076 }
21077
21078 if (LoopSize <= 64)
21079 return PrefAlign;
21080
21081 if (LoopSize <= 128)
21082 return CacheLineAlign;
21083
21084 // If any of parent loops is surrounded by prefetch instructions do not
21085 // insert new for inner loop, which would reset parent's settings.
21086 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
21087 if (MachineBasicBlock *Exit = P->getExitBlock()) {
21088 auto I = Exit->getFirstNonDebugInstr();
21089 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
21090 return CacheLineAlign;
21091 }
21092 }
21093
21094 MachineBasicBlock *Pre = ML->getLoopPreheader();
21095 MachineBasicBlock *Exit = ML->getExitBlock();
21096
21097 if (Pre && Exit) {
21098 auto PreTerm = Pre->getFirstTerminator();
21099 if (PreTerm == Pre->begin() ||
21100 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
21101 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
21102 .addImm(1); // prefetch 2 lines behind PC
21103
21104 auto ExitHead = Exit->getFirstNonDebugInstr();
21105 if (ExitHead == Exit->end() ||
21106 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
21107 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
21108 .addImm(2); // prefetch 1 line behind PC
21109 }
21110
21111 return CacheLineAlign;
21112}
21113
21115 MachineBasicBlock *MBB) const {
21116 // GFX950: Limit padding to 4 bytes (one s_nop) for blocks where an 8-byte
21117 // instruction could be split by the 32-byte fetch window boundary.
21118 // See getPrefLoopAlignment() for context.
21119 if (needsFetchWindowAlignment(*MBB))
21120 return 4;
21122}
21123
21124bool SITargetLowering::needsFetchWindowAlignment(
21125 const MachineBasicBlock &MBB) const {
21126 if (!getSubtarget()->hasLoopHeadInstSplitSensitivity())
21127 return false;
21129 for (const MachineInstr &MI : MBB) {
21130 if (MI.isMetaInstruction())
21131 continue;
21132 // Instructions larger than 4 bytes can be split by a 32-byte boundary.
21133 return TII->getInstSizeInBytes(MI) > 4;
21134 }
21135 return false;
21136}
21137
21138[[maybe_unused]]
21139static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
21140 assert(N->getOpcode() == ISD::CopyFromReg);
21141 do {
21142 // Follow the chain until we find an INLINEASM node.
21143 N = N->getOperand(0).getNode();
21144 if (N->getOpcode() == ISD::INLINEASM || N->getOpcode() == ISD::INLINEASM_BR)
21145 return true;
21146 } while (N->getOpcode() == ISD::CopyFromReg);
21147 return false;
21148}
21149
21152 UniformityInfo *UA) const {
21153 switch (N->getOpcode()) {
21154 case ISD::CopyFromReg: {
21155 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
21156 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
21157 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
21158 Register Reg = R->getReg();
21159
21160 // FIXME: Why does this need to consider isLiveIn?
21161 if (Reg.isPhysical() || MRI.isLiveIn(Reg))
21162 return !TRI->isSGPRReg(MRI, Reg);
21163
21164 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
21165 return UA->isDivergentAtDef(V);
21166
21168 return !TRI->isSGPRReg(MRI, Reg);
21169 }
21170 case ISD::LOAD: {
21171 const LoadSDNode *L = cast<LoadSDNode>(N);
21172 unsigned AS = L->getAddressSpace();
21173 // A flat load may access private memory, and a VGPR load reads each lane's
21174 // own registers.
21175 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS ||
21176 AS == AMDGPUAS::VGPR;
21177 }
21178 // As above, after the pre-ISel combine.
21179 case AMDGPUISD::REG_LOAD:
21180 return true;
21181 case ISD::CALLSEQ_END:
21182 return true;
21184 return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(0));
21186 return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(1));
21187 case AMDGPUISD::ATOMIC_CMP_SWAP:
21188 case AMDGPUISD::BUFFER_ATOMIC_SWAP:
21189 case AMDGPUISD::BUFFER_ATOMIC_ADD:
21190 case AMDGPUISD::BUFFER_ATOMIC_SUB:
21191 case AMDGPUISD::BUFFER_ATOMIC_SMIN:
21192 case AMDGPUISD::BUFFER_ATOMIC_UMIN:
21193 case AMDGPUISD::BUFFER_ATOMIC_SMAX:
21194 case AMDGPUISD::BUFFER_ATOMIC_UMAX:
21195 case AMDGPUISD::BUFFER_ATOMIC_AND:
21196 case AMDGPUISD::BUFFER_ATOMIC_OR:
21197 case AMDGPUISD::BUFFER_ATOMIC_XOR:
21198 case AMDGPUISD::BUFFER_ATOMIC_INC:
21199 case AMDGPUISD::BUFFER_ATOMIC_DEC:
21200 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
21201 case AMDGPUISD::BUFFER_ATOMIC_FADD:
21202 case AMDGPUISD::BUFFER_ATOMIC_FMIN:
21203 case AMDGPUISD::BUFFER_ATOMIC_FMAX:
21204 // Target-specific read-modify-write atomics are sources of divergence.
21205 return true;
21206 default:
21207 if (auto *A = dyn_cast<AtomicSDNode>(N)) {
21208 // Generic read-modify-write atomics are sources of divergence.
21209 return A->readMem() && A->writeMem();
21210 }
21211 return false;
21212 }
21213}
21214
21216 EVT VT) const {
21217 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
21218 case MVT::f32:
21220 case MVT::f64:
21221 case MVT::f16:
21223 default:
21224 return false;
21225 }
21226}
21227
21229 LLT Ty, const MachineFunction &MF) const {
21230 switch (Ty.getScalarSizeInBits()) {
21231 case 32:
21232 return !denormalModeIsFlushAllF32(MF);
21233 case 64:
21234 case 16:
21235 return !denormalModeIsFlushAllF64F16(MF);
21236 default:
21237 return false;
21238 }
21239}
21240
21242 const APInt &DemandedElts,
21243 const SelectionDAG &DAG,
21244 bool SNaN,
21245 unsigned Depth) const {
21246 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
21247 const MachineFunction &MF = DAG.getMachineFunction();
21249
21250 if (Info->getMode().DX10Clamp)
21251 return true; // Clamped to 0.
21252 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
21253 }
21254
21256 DAG, SNaN, Depth);
21257}
21258
21259namespace {
21260
21261/// Why a floating-point atomic instruction which may flush denormals is
21262/// acceptable.
21263enum class AtomicFlushDenormalReason {
21264 Native,
21265 IEEE,
21266 IgnoreDenormalMode,
21267 FunctionFlushesDenormals
21268};
21269
21270/// Why a native floating-point atomic instruction is acceptable for a global
21271/// memory address.
21272enum class GlobalFPAtomicLegality {
21273 Illegal,
21274 AgentScopeFineGrainedRemoteMemory,
21275 EmulatedSystemScope,
21276 NoRemoteMemory,
21277 NoFineGrainedMemory
21278};
21279
21280} // end anonymous namespace
21281
21282// On older subtargets, global FP atomic instructions have a hardcoded FP mode
21283// and do not support FP32 denormals, and only support v2f16/f64 denormals.
21284static AtomicFlushDenormalReason
21286 if (RMW->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
21287 return AtomicFlushDenormalReason::IgnoreDenormalMode;
21288
21289 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
21290 auto DenormMode = RMW->getFunction()->getDenormalMode(Flt);
21291 return DenormMode == DenormalMode::getPreserveSign()
21292 ? AtomicFlushDenormalReason::FunctionFlushesDenormals
21293 : AtomicFlushDenormalReason::IEEE;
21294}
21295
21296static OptimizationRemark
21298 GlobalFPAtomicLegality MemLegality,
21299 AtomicFlushDenormalReason DenormReason) {
21300 LLVMContext &Ctx = RMW->getContext();
21301 StringRef MemScope = Ctx.getSyncScopeName(RMW->getSyncScopeID()).value_or("");
21302 if (MemScope.empty())
21303 MemScope = "system";
21304
21305 OptimizationRemark R(DEBUG_TYPE, "Passed", RMW);
21306 R << "hardware instruction generated for atomic "
21307 << ore::NV("Operation", RMW->getOperationName(RMW->getOperation()))
21308 << " at " << ore::NV("SyncScope", MemScope) << " scope since ";
21309
21310 switch (MemLegality) {
21311 case GlobalFPAtomicLegality::AgentScopeFineGrainedRemoteMemory:
21312 R << "fine-grained remote memory atomics work below system scope";
21313 break;
21314 case GlobalFPAtomicLegality::EmulatedSystemScope:
21315 R << "system scope atomics are emulated in hardware";
21316 break;
21317 case GlobalFPAtomicLegality::NoRemoteMemory:
21318 R << "memory is not remote (!amdgpu.no.remote.memory)";
21319 break;
21320 case GlobalFPAtomicLegality::NoFineGrainedMemory:
21321 R << "memory is not fine-grained (!amdgpu.no.fine.grained.memory)";
21322 break;
21323 case GlobalFPAtomicLegality::Illegal:
21324 llvm_unreachable("remark for illegal atomic");
21325 }
21326
21327 switch (DenormReason) {
21328 case AtomicFlushDenormalReason::Native:
21329 break;
21330 case AtomicFlushDenormalReason::IgnoreDenormalMode:
21331 R << ", and denormals may be flushed (!atomic.ignore.denormal.mode)";
21332 break;
21333 case AtomicFlushDenormalReason::FunctionFlushesDenormals:
21334 R << ", and the floating-point environment flushes denormals";
21335 break;
21336 case AtomicFlushDenormalReason::IEEE:
21337 llvm_unreachable("remark for illegal atomic");
21338 }
21339
21340 return R;
21341}
21342
21343static bool isV2F16OrV2BF16(Type *Ty) {
21344 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
21345 Type *EltTy = VT->getElementType();
21346 return VT->getNumElements() == 2 &&
21347 (EltTy->isHalfTy() || EltTy->isBFloatTy());
21348 }
21349
21350 return false;
21351}
21352
21353static bool isV2F16(Type *Ty) {
21355 return VT && VT->getNumElements() == 2 && VT->getElementType()->isHalfTy();
21356}
21357
21358static bool isV2BF16(Type *Ty) {
21360 return VT && VT->getNumElements() == 2 && VT->getElementType()->isBFloatTy();
21361}
21362
21363/// \return true if atomicrmw integer ops work for the type.
21364static bool isAtomicRMWLegalIntTy(Type *Ty) {
21365 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
21366 unsigned BW = IT->getBitWidth();
21367 return BW == 32 || BW == 64;
21368 }
21369
21370 return false;
21371}
21372
21373/// \return true if this atomicrmw xchg type can be selected.
21374static bool isAtomicRMWLegalXChgTy(const AtomicRMWInst *RMW) {
21375 Type *Ty = RMW->getType();
21376 if (isAtomicRMWLegalIntTy(Ty))
21377 return true;
21378
21379 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
21380 const DataLayout &DL = RMW->getFunction()->getDataLayout();
21381 unsigned BW = DL.getPointerSizeInBits(PT->getAddressSpace());
21382 return BW == 32 || BW == 64;
21383 }
21384
21385 if (Ty->isFloatTy() || Ty->isDoubleTy())
21386 return true;
21387
21389 return VT->getNumElements() == 2 &&
21390 VT->getElementType()->getPrimitiveSizeInBits() == 16;
21391 }
21392
21393 return false;
21394}
21395
21396/// \returns whether it's valid to emit a native instruction for \p RMW, and
21397/// why, based on the properties of the target memory.
21398static GlobalFPAtomicLegality
21400 const AtomicRMWInst *RMW, bool HasSystemScope) {
21401 // The remote/fine-grained access logic is different from the integer
21402 // atomics. Without AgentScopeFineGrainedRemoteMemoryAtomics support,
21403 // fine-grained access does not work, even for a device local allocation.
21404 //
21405 // With AgentScopeFineGrainedRemoteMemoryAtomics, system scoped device local
21406 // allocations work.
21407 if (HasSystemScope) {
21408 if (Subtarget.hasAgentScopeFineGrainedRemoteMemoryAtomics() &&
21409 RMW->hasMetadata("amdgpu.no.remote.memory"))
21410 return GlobalFPAtomicLegality::NoRemoteMemory;
21411 if (Subtarget.hasEmulatedSystemScopeAtomics())
21412 return GlobalFPAtomicLegality::EmulatedSystemScope;
21413 } else if (Subtarget.hasAgentScopeFineGrainedRemoteMemoryAtomics())
21414 return GlobalFPAtomicLegality::AgentScopeFineGrainedRemoteMemory;
21415
21416 return RMW->hasMetadata("amdgpu.no.fine.grained.memory")
21417 ? GlobalFPAtomicLegality::NoFineGrainedMemory
21418 : GlobalFPAtomicLegality::Illegal;
21419}
21420
21421/// \return Action to perform on AtomicRMWInsts for integer operations.
21428
21429/// Return if a flat address space atomicrmw can access private memory.
21431 const MDNode *MD = I->getMetadata(LLVMContext::MD_noalias_addrspace);
21432 return !MD ||
21434}
21435
21438 // For GAS, lower to flat atomic.
21439 return STI.hasGloballyAddressableScratch()
21442}
21443
21446 unsigned AS = RMW->getPointerAddressSpace();
21447 if (AS == AMDGPUAS::PRIVATE_ADDRESS)
21449
21450 // Only the executing lane can access its view of the VGPRs, so as with
21451 // private memory there is nothing to be atomic with respect to.
21452 if (AS == AMDGPUAS::VGPR)
21454
21455 // 64-bit flat atomics that dynamically reside in private memory will silently
21456 // be dropped.
21457 //
21458 // Note that we will emit a new copy of the original atomic in the expansion,
21459 // which will be incrementally relegalized.
21460 const DataLayout &DL = RMW->getFunction()->getDataLayout();
21461 if (AS == AMDGPUAS::FLAT_ADDRESS &&
21462 DL.getTypeSizeInBits(RMW->getType()) == 64 &&
21465
21466 GlobalFPAtomicLegality MemLegality = GlobalFPAtomicLegality::Illegal;
21467 AtomicFlushDenormalReason DenormReason = AtomicFlushDenormalReason::Native;
21468 auto ReportHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
21470 ORE.emit([&]() {
21471 return emitAtomicRMWLegalRemark(RMW, MemLegality, DenormReason);
21472 });
21473 return Kind;
21474 };
21475
21476 auto SSID = RMW->getSyncScopeID();
21477 bool HasSystemScope =
21478 SSID == SyncScope::System ||
21480 getTargetMachine().getTargetTriple(), AtomicScope::System,
21481 /*OneAddressSpace=*/true));
21482
21483 auto Op = RMW->getOperation();
21484 switch (Op) {
21486 // PCIe supports add and xchg for system atomics.
21487 return isAtomicRMWLegalXChgTy(RMW)
21490 case AtomicRMWInst::Add:
21491 // PCIe supports add and xchg for system atomics.
21493 case AtomicRMWInst::Sub:
21494 case AtomicRMWInst::And:
21495 case AtomicRMWInst::Or:
21496 case AtomicRMWInst::Xor:
21497 case AtomicRMWInst::Max:
21498 case AtomicRMWInst::Min:
21505 if (Op == AtomicRMWInst::USubCond && !Subtarget->hasCondSubInsts())
21507 if (Op == AtomicRMWInst::USubSat) {
21508 // The global and buffer forms predate the LDS and flat ones.
21509 if (!Subtarget->hasSubClampInsts() ||
21510 (AS == AMDGPUAS::LOCAL_ADDRESS &&
21511 !Subtarget->hasAtomicDsCondSubClampInsts()) ||
21512 (AS == AMDGPUAS::FLAT_ADDRESS &&
21513 !Subtarget->hasAtomicCondSubClampFlatInsts()))
21515 }
21517 auto *IT = dyn_cast<IntegerType>(RMW->getType());
21518 if (!IT || IT->getBitWidth() != 32)
21520 }
21521
21524 if (Subtarget->hasEmulatedSystemScopeAtomics())
21526
21527 // On most subtargets, for atomicrmw operations other than add/xchg,
21528 // whether or not the instructions will behave correctly depends on where
21529 // the address physically resides and what interconnect is used in the
21530 // system configuration. On some some targets the instruction will nop,
21531 // and in others synchronization will only occur at degraded device scope.
21532 //
21533 // If the allocation is known local to the device, the instructions should
21534 // work correctly.
21535 if (RMW->hasMetadata("amdgpu.no.remote.memory"))
21537
21538 // If fine-grained remote memory works at device scope, we don't need to
21539 // do anything.
21540 if (!HasSystemScope &&
21541 Subtarget->hasAgentScopeFineGrainedRemoteMemoryAtomics())
21543
21544 // If we are targeting a remote allocated address, it depends what kind of
21545 // allocation the address belongs to.
21546 //
21547 // If the allocation is fine-grained (in host memory, or in PCIe peer
21548 // device memory), the operation will fail depending on the target.
21549 //
21550 // Note fine-grained host memory access does work on APUs or if XGMI is
21551 // used, but we do not know if we are targeting an APU or the system
21552 // configuration from the ISA version/target-cpu.
21553 if (RMW->hasMetadata("amdgpu.no.fine.grained.memory"))
21555
21558 // Atomic sub/or/xor do not work over PCI express, but atomic add
21559 // does. InstCombine transforms these with 0 to or, so undo that.
21560 // Sub-word types are not selectable and take the cmpxchg expansion.
21561 if (const Constant *ConstVal = dyn_cast<Constant>(RMW->getValOperand());
21562 ConstVal && ConstVal->isNullValue() &&
21565 }
21566
21567 // If the allocation could be in remote, fine-grained memory, the rmw
21568 // instructions may fail. cmpxchg should work, so emit that. On some
21569 // system configurations, PCIe atomics aren't supported so cmpxchg won't
21570 // even work, so you're out of luck anyway.
21571
21572 // In summary:
21573 //
21574 // Cases that may fail:
21575 // - fine-grained pinned host memory
21576 // - fine-grained migratable host memory
21577 // - fine-grained PCIe peer device
21578 //
21579 // Cases that should work, but may be treated overly conservatively.
21580 // - fine-grained host memory on an APU
21581 // - fine-grained XGMI peer device
21583 }
21584
21586 }
21587 case AtomicRMWInst::FAdd: {
21588 Type *Ty = RMW->getType();
21589
21590 // TODO: Handle REGION_ADDRESS
21591 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
21592 // DS F32 FP atomics do respect the denormal mode, but the rounding mode
21593 // is fixed to round-to-nearest-even.
21594 //
21595 // F64 / PK_F16 / PK_BF16 never flush and are also fixed to
21596 // round-to-nearest-even.
21597 //
21598 // We ignore the rounding mode problem, even in strictfp. The C++ standard
21599 // suggests it is OK if the floating-point mode may not match the calling
21600 // thread.
21601 if (Ty->isFloatTy()) {
21602 return Subtarget->hasLDSFPAtomicAddF32() ? AtomicExpansionKind::None
21604 }
21605
21606 if (Ty->isDoubleTy()) {
21607 // Ignores denormal mode, but we don't consider flushing mandatory.
21608 return Subtarget->hasLdsAtomicAddF64() ? AtomicExpansionKind::None
21610 }
21611
21612 if (Subtarget->hasAtomicDsPkAdd16Insts() && isV2F16OrV2BF16(Ty))
21614
21616 }
21617
21618 // LDS atomics respect the denormal mode from the mode register.
21619 //
21620 // Traditionally f32 global/buffer memory atomics would unconditionally
21621 // flush denormals, but newer targets do not flush. f64/f16/bf16 cases never
21622 // flush.
21623 //
21624 // On targets with flat atomic fadd, denormals would flush depending on
21625 // whether the target address resides in LDS or global memory. We consider
21626 // this flat-maybe-flush as will-flush.
21627 if (Ty->isFloatTy() &&
21628 !Subtarget->hasMemoryAtomicFaddF32DenormalSupport()) {
21629 DenormReason = getAtomicFlushDenormalReason(RMW);
21630 if (DenormReason == AtomicFlushDenormalReason::IEEE)
21632 }
21633
21634 MemLegality =
21635 getGlobalMemoryFPAtomicLegality(*Subtarget, RMW, HasSystemScope);
21636 if (MemLegality != GlobalFPAtomicLegality::Illegal) {
21637 if (AS == AMDGPUAS::FLAT_ADDRESS) {
21638 // gfx942, gfx12
21639 if (Subtarget->hasAtomicFlatPkAdd16Insts() && isV2F16OrV2BF16(Ty))
21640 return ReportHWInst(AtomicExpansionKind::None);
21641 } else if (AMDGPU::isExtendedGlobalAddrSpace(AS)) {
21642 // gfx90a, gfx942, gfx12
21643 if (Subtarget->hasAtomicBufferGlobalPkAddF16Insts() && isV2F16(Ty))
21644 return ReportHWInst(AtomicExpansionKind::None);
21645
21646 // gfx942, gfx12
21647 if (Subtarget->hasAtomicGlobalPkAddBF16Inst() && isV2BF16(Ty))
21648 return ReportHWInst(AtomicExpansionKind::None);
21649 } else if (AS == AMDGPUAS::BUFFER_FAT_POINTER) {
21650 // gfx90a, gfx942, gfx12
21651 if (Subtarget->hasAtomicBufferGlobalPkAddF16Insts() && isV2F16(Ty))
21652 return ReportHWInst(AtomicExpansionKind::None);
21653
21654 // While gfx90a/gfx942 supports v2bf16 for global/flat, it does not for
21655 // buffer. gfx12 does have the buffer version.
21656 if (Subtarget->hasAtomicBufferPkAddBF16Inst() && isV2BF16(Ty))
21657 return ReportHWInst(AtomicExpansionKind::None);
21658 }
21659
21660 // global and flat atomic fadd f64: gfx90a, gfx942.
21661 if (Subtarget->hasFlatBufferGlobalAtomicFaddF64Inst() && Ty->isDoubleTy())
21662 return ReportHWInst(AtomicExpansionKind::None);
21663
21664 if (AS != AMDGPUAS::FLAT_ADDRESS) {
21665 if (Ty->isFloatTy()) {
21666 // global/buffer atomic fadd f32 no-rtn: gfx908, gfx90a, gfx942,
21667 // gfx11+.
21668 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
21669 return ReportHWInst(AtomicExpansionKind::None);
21670 // global/buffer atomic fadd f32 rtn: gfx90a, gfx942, gfx11+.
21671 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
21672 return ReportHWInst(AtomicExpansionKind::None);
21673 } else {
21674 // gfx908
21675 if (RMW->use_empty() &&
21676 Subtarget->hasAtomicBufferGlobalPkAddF16NoRtnInsts() &&
21677 isV2F16(Ty))
21678 return ReportHWInst(AtomicExpansionKind::None);
21679 }
21680 }
21681
21682 // flat atomic fadd f32: gfx942, gfx11+.
21683 if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy()) {
21684 if (Subtarget->hasFlatAtomicFaddF32Inst())
21685 return ReportHWInst(AtomicExpansionKind::None);
21686
21687 // If it is in flat address space, and the type is float, we will try to
21688 // expand it, if the target supports global and lds atomic fadd. The
21689 // reason we need that is, in the expansion, we emit the check of
21690 // address space. If it is in global address space, we emit the global
21691 // atomic fadd; if it is in shared address space, we emit the LDS atomic
21692 // fadd.
21693 if (Subtarget->hasLDSFPAtomicAddF32()) {
21694 if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
21696 if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
21698 }
21699 }
21700 }
21701
21703 }
21705 case AtomicRMWInst::FMax: {
21706 Type *Ty = RMW->getType();
21707
21708 // LDS float and double fmin/fmax were always supported.
21709 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
21710 return Ty->isFloatTy() || Ty->isDoubleTy() ? AtomicExpansionKind::None
21712 }
21713
21714 MemLegality =
21715 getGlobalMemoryFPAtomicLegality(*Subtarget, RMW, HasSystemScope);
21716 if (MemLegality != GlobalFPAtomicLegality::Illegal) {
21717 // For flat and global cases:
21718 // float, double in gfx7. Manual claims denormal support.
21719 // Removed in gfx8.
21720 // float, double restored in gfx10.
21721 // double removed again in gfx11, so only f32 for gfx11/gfx12.
21722 //
21723 // For gfx9, gfx90a and gfx942 support f64 for global (same as fadd), but
21724 // no f32.
21725 if (AS == AMDGPUAS::FLAT_ADDRESS) {
21726 if (Subtarget->hasAtomicFMinFMaxF32FlatInsts() && Ty->isFloatTy())
21727 return ReportHWInst(AtomicExpansionKind::None);
21728 if (Subtarget->hasAtomicFMinFMaxF64FlatInsts() && Ty->isDoubleTy())
21729 return ReportHWInst(AtomicExpansionKind::None);
21730 } else if (AMDGPU::isExtendedGlobalAddrSpace(AS) ||
21732 if (Subtarget->hasAtomicFMinFMaxF32GlobalInsts() && Ty->isFloatTy())
21733 return ReportHWInst(AtomicExpansionKind::None);
21734 if (Subtarget->hasAtomicFMinFMaxF64GlobalInsts() && Ty->isDoubleTy())
21735 return ReportHWInst(AtomicExpansionKind::None);
21736 }
21737 }
21738
21740 }
21743 default:
21745 }
21746
21747 llvm_unreachable("covered atomicrmw op switch");
21748}
21749
21758
21761 if (SI->getPointerAddressSpace() == AMDGPUAS::VGPR)
21763 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
21766}
21767
21770 const AtomicCmpXchgInst *CmpX) const {
21771 unsigned AddrSpace = CmpX->getPointerAddressSpace();
21772 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
21774
21775 if (AddrSpace == AMDGPUAS::VGPR)
21777
21778 if (AddrSpace != AMDGPUAS::FLAT_ADDRESS || !flatInstrMayAccessPrivate(CmpX))
21780
21781 const DataLayout &DL = CmpX->getDataLayout();
21782
21783 Type *ValTy = CmpX->getNewValOperand()->getType();
21784
21785 // If a 64-bit flat atomic may alias private, we need to avoid using the
21786 // atomic in the private case.
21787 return DL.getTypeSizeInBits(ValTy) == 64 ? AtomicExpansionKind::CustomExpand
21789}
21790
21791const TargetRegisterClass *
21792SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
21794 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
21795 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
21796 return Subtarget->isWave64() ? &AMDGPU::SReg_64RegClass
21797 : &AMDGPU::SReg_32RegClass;
21798 if (!TRI->isSGPRClass(RC) && !isDivergent)
21799 return TRI->getEquivalentSGPRClass(RC);
21800 if (TRI->isSGPRClass(RC) && isDivergent) {
21801 if (Subtarget->hasGFX90AInsts())
21802 return TRI->getEquivalentAVClass(RC);
21803 return TRI->getEquivalentVGPRClass(RC);
21804 }
21805
21806 return RC;
21807}
21808
21809// FIXME: This is a workaround for DivergenceAnalysis not understanding always
21810// uniform values (as produced by the mask results of control flow intrinsics)
21811// used outside of divergent blocks. The phi users need to also be treated as
21812// always uniform.
21813//
21814// FIXME: DA is no longer in-use. Does this still apply to UniformityAnalysis?
21816 unsigned WaveSize) {
21817 // FIXME: We assume we never cast the mask results of a control flow
21818 // intrinsic.
21819 // Early exit if the type won't be consistent as a compile time hack.
21820 IntegerType *IT = dyn_cast<IntegerType>(V->getType());
21821 if (!IT || IT->getBitWidth() != WaveSize)
21822 return false;
21823
21824 if (!isa<Instruction>(V))
21825 return false;
21826 if (!Visited.insert(V).second)
21827 return false;
21828 bool Result = false;
21829 for (const auto *U : V->users()) {
21831 if (V == U->getOperand(1)) {
21832 switch (Intrinsic->getIntrinsicID()) {
21833 default:
21834 Result = false;
21835 break;
21836 case Intrinsic::amdgcn_if_break:
21837 case Intrinsic::amdgcn_if:
21838 case Intrinsic::amdgcn_else:
21839 Result = true;
21840 break;
21841 }
21842 }
21843 if (V == U->getOperand(0)) {
21844 switch (Intrinsic->getIntrinsicID()) {
21845 default:
21846 Result = false;
21847 break;
21848 case Intrinsic::amdgcn_end_cf:
21849 case Intrinsic::amdgcn_loop:
21850 Result = true;
21851 break;
21852 }
21853 }
21854 } else {
21855 Result = hasCFUser(U, Visited, WaveSize);
21856 }
21857 if (Result)
21858 break;
21859 }
21860 return Result;
21861}
21862
21864 const Value *V) const {
21865 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
21866 if (CI->isInlineAsm()) {
21867 // FIXME: This cannot give a correct answer. This should only trigger in
21868 // the case where inline asm returns mixed SGPR and VGPR results, used
21869 // outside the defining block. We don't have a specific result to
21870 // consider, so this assumes if any value is SGPR, the overall register
21871 // also needs to be SGPR.
21872 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
21874 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
21875 for (auto &TC : TargetConstraints) {
21876 if (TC.Type == InlineAsm::isOutput) {
21878 const TargetRegisterClass *RC =
21879 getRegForInlineAsmConstraint(SIRI, TC.ConstraintCode,
21880 TC.ConstraintVT)
21881 .second;
21882 if (RC && SIRI->isSGPRClass(RC))
21883 return true;
21884 }
21885 }
21886 }
21887 }
21889 return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
21890}
21891
21893 for (SDUse &Use : N->uses()) {
21895 if (getBasePtrIndex(M) == Use.getOperandNo())
21896 return true;
21897 }
21898 }
21899 return false;
21900}
21901
21903 SDValue N1) const {
21904 if (!N0.hasOneUse())
21905 return false;
21906 // Take care of the opportunity to keep N0 uniform
21907 if (N0->isDivergent() || !N1->isDivergent())
21908 return true;
21909 // Check if we have a good chance to form the memory access pattern with the
21910 // base and offset
21911 return (DAG.isBaseWithConstantOffset(N0) &&
21913}
21914
21916 Register N0, Register N1) const {
21917 return MRI.hasOneNonDBGUse(N0); // FIXME: handle regbanks
21918}
21919
21922 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
21924 if (I.getMetadata("amdgpu.noclobber"))
21925 Flags |= MONoClobber;
21926 if (I.getMetadata("amdgpu.last.use"))
21927 Flags |= MOLastUse;
21928 if (MDNode *N = I.getMetadata("amdgpu.cfs")) {
21929 const ConstantAsMetadata *CAM = cast<ConstantAsMetadata>(N->getOperand(0));
21931 unsigned CFS = CI->getZExtValue() & AMDGPU::CPol::CFS_MASK;
21932 static_assert((MOCFSB0 << 1) == MOCFSB1,
21933 "MOCFSB0 and MOCFSB1 are not adjacent bits");
21934 Flags |= static_cast<MachineMemOperand::Flags>(CFS * MOCFSB0);
21935 }
21936 return Flags;
21937}
21938
21940 Instruction *AI) const {
21941 // Given: atomicrmw fadd ptr %addr, float %val ordering
21942 //
21943 // With this expansion we produce the following code:
21944 // [...]
21945 // %is.shared = call i1 @llvm.amdgcn.is.shared(ptr %addr)
21946 // br i1 %is.shared, label %atomicrmw.shared, label %atomicrmw.check.private
21947 //
21948 // atomicrmw.shared:
21949 // %cast.shared = addrspacecast ptr %addr to ptr addrspace(3)
21950 // %loaded.shared = atomicrmw fadd ptr addrspace(3) %cast.shared,
21951 // float %val ordering
21952 // br label %atomicrmw.phi
21953 //
21954 // atomicrmw.check.private:
21955 // %is.private = call i1 @llvm.amdgcn.is.private(ptr %int8ptr)
21956 // br i1 %is.private, label %atomicrmw.private, label %atomicrmw.global
21957 //
21958 // atomicrmw.private:
21959 // %cast.private = addrspacecast ptr %addr to ptr addrspace(5)
21960 // %loaded.private = load float, ptr addrspace(5) %cast.private
21961 // %val.new = fadd float %loaded.private, %val
21962 // store float %val.new, ptr addrspace(5) %cast.private
21963 // br label %atomicrmw.phi
21964 //
21965 // atomicrmw.global:
21966 // %cast.global = addrspacecast ptr %addr to ptr addrspace(1)
21967 // %loaded.global = atomicrmw fadd ptr addrspace(1) %cast.global,
21968 // float %val ordering
21969 // br label %atomicrmw.phi
21970 //
21971 // atomicrmw.phi:
21972 // %loaded.phi = phi float [ %loaded.shared, %atomicrmw.shared ],
21973 // [ %loaded.private, %atomicrmw.private ],
21974 // [ %loaded.global, %atomicrmw.global ]
21975 // br label %atomicrmw.end
21976 //
21977 // atomicrmw.end:
21978 // [...]
21979 //
21980 //
21981 // For 64-bit atomics which may reside in private memory, we perform a simpler
21982 // version that only inserts the private check, and uses the flat operation.
21983
21984 IRBuilder<> Builder(AI);
21985 LLVMContext &Ctx = Builder.getContext();
21986
21987 auto *RMW = dyn_cast<AtomicRMWInst>(AI);
21988 const unsigned PtrOpIdx = RMW ? AtomicRMWInst::getPointerOperandIndex()
21990 Value *Addr = AI->getOperand(PtrOpIdx);
21991
21992 /// TODO: Only need to check private, then emit flat-known-not private (no
21993 /// need for shared block, or cast to global).
21995
21996 Align Alignment;
21997 if (RMW)
21998 Alignment = RMW->getAlign();
21999 else if (CX)
22000 Alignment = CX->getAlign();
22001 else
22002 llvm_unreachable("unhandled atomic operation");
22003
22004 // FullFlatEmulation is true if we need to issue the private, shared, and
22005 // global cases.
22006 //
22007 // If this is false, we are only dealing with the flat-targeting-private case,
22008 // where we only insert a check for private and still use the flat instruction
22009 // for global and shared.
22010
22011 bool FullFlatEmulation =
22012 RMW && RMW->getOperation() == AtomicRMWInst::FAdd &&
22013 ((Subtarget->hasAtomicFaddInsts() && RMW->getType()->isFloatTy()) ||
22014 (Subtarget->hasFlatBufferGlobalAtomicFaddF64Inst() &&
22015 RMW->getType()->isDoubleTy()));
22016
22017 // If the return value isn't used, do not introduce a false use in the phi.
22018 bool ReturnValueIsUsed = !AI->use_empty();
22019
22020 BasicBlock *BB = Builder.GetInsertBlock();
22021 Function *F = BB->getParent();
22022 BasicBlock *ExitBB =
22023 BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
22024 BasicBlock *SharedBB = nullptr;
22025
22026 BasicBlock *CheckPrivateBB = BB;
22027 if (FullFlatEmulation) {
22028 SharedBB = BasicBlock::Create(Ctx, "atomicrmw.shared", F, ExitBB);
22029 CheckPrivateBB =
22030 BasicBlock::Create(Ctx, "atomicrmw.check.private", F, ExitBB);
22031 }
22032
22033 BasicBlock *PrivateBB =
22034 BasicBlock::Create(Ctx, "atomicrmw.private", F, ExitBB);
22035 BasicBlock *GlobalBB = BasicBlock::Create(Ctx, "atomicrmw.global", F, ExitBB);
22036 BasicBlock *PhiBB = BasicBlock::Create(Ctx, "atomicrmw.phi", F, ExitBB);
22037
22038 std::prev(BB->end())->eraseFromParent();
22039 Builder.SetInsertPoint(BB);
22040
22041 Value *LoadedShared = nullptr;
22042 if (FullFlatEmulation) {
22043 Value *IsShared = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_shared,
22044 {Addr}, nullptr, "is.shared");
22045 Builder.CreateCondBr(IsShared, SharedBB, CheckPrivateBB);
22046 Builder.SetInsertPoint(SharedBB);
22047 Value *CastToLocal = Builder.CreateAddrSpaceCast(
22049
22050 Instruction *Clone = AI->clone();
22051 Clone->insertInto(SharedBB, SharedBB->end());
22052 Clone->getOperandUse(PtrOpIdx).set(CastToLocal);
22053 LoadedShared = Clone;
22054
22055 Builder.CreateBr(PhiBB);
22056 Builder.SetInsertPoint(CheckPrivateBB);
22057 }
22058
22059 Value *IsPrivate = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_private,
22060 {Addr}, nullptr, "is.private");
22061 Builder.CreateCondBr(IsPrivate, PrivateBB, GlobalBB);
22062
22063 Builder.SetInsertPoint(PrivateBB);
22064
22065 Value *CastToPrivate = Builder.CreateAddrSpaceCast(
22067
22068 Value *LoadedPrivate;
22069 if (RMW) {
22070 LoadedPrivate = Builder.CreateAlignedLoad(
22071 RMW->getType(), CastToPrivate, RMW->getAlign(), RMW->isVolatile(),
22072 "loaded.private");
22073
22074 Value *NewVal = buildAtomicRMWValue(RMW->getOperation(), Builder,
22075 LoadedPrivate, RMW->getValOperand());
22076
22077 Builder.CreateAlignedStore(NewVal, CastToPrivate, RMW->getAlign(),
22078 RMW->isVolatile());
22079 } else {
22080 auto [ResultLoad, Equal] = buildCmpXchgValue(
22081 Builder, CastToPrivate, CX->getCompareOperand(), CX->getNewValOperand(),
22082 CX->getAlign(), CX->isVolatile());
22083
22084 Value *Insert = Builder.CreateInsertValue(PoisonValue::get(CX->getType()),
22085 ResultLoad, 0);
22086 LoadedPrivate = Builder.CreateInsertValue(Insert, Equal, 1);
22087 }
22088
22089 Builder.CreateBr(PhiBB);
22090
22091 Builder.SetInsertPoint(GlobalBB);
22092
22093 // Continue using a flat instruction if we only emitted the check for private.
22094 Instruction *LoadedGlobal = AI;
22095 if (FullFlatEmulation) {
22096 Value *CastToGlobal = Builder.CreateAddrSpaceCast(
22098 AI->getOperandUse(PtrOpIdx).set(CastToGlobal);
22099 }
22100
22101 AI->removeFromParent();
22102 AI->insertInto(GlobalBB, GlobalBB->end());
22103
22104 // The new atomicrmw may go through another round of legalization later.
22105 if (!FullFlatEmulation) {
22106 // We inserted the runtime check already, make sure we do not try to
22107 // re-expand this.
22108 // TODO: Should union with any existing metadata.
22109 MDBuilder MDB(F->getContext());
22110 MDNode *RangeNotPrivate =
22113 LoadedGlobal->setMetadata(LLVMContext::MD_noalias_addrspace,
22114 RangeNotPrivate);
22115 }
22116
22117 Builder.CreateBr(PhiBB);
22118
22119 Builder.SetInsertPoint(PhiBB);
22120
22121 if (ReturnValueIsUsed) {
22122 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 3);
22123 AI->replaceAllUsesWith(Loaded);
22124 if (FullFlatEmulation)
22125 Loaded->addIncoming(LoadedShared, SharedBB);
22126 Loaded->addIncoming(LoadedPrivate, PrivateBB);
22127 Loaded->addIncoming(LoadedGlobal, GlobalBB);
22128 Loaded->takeName(AI);
22129 }
22130
22131 Builder.CreateBr(ExitBB);
22132}
22133
22135 unsigned PtrOpIdx) {
22136 Value *PtrOp = I->getOperand(PtrOpIdx);
22139
22140 Type *FlatPtr = PointerType::get(I->getContext(), AMDGPUAS::FLAT_ADDRESS);
22141 Value *ASCast = CastInst::CreatePointerCast(PtrOp, FlatPtr, "scratch.ascast",
22142 I->getIterator());
22143 I->setOperand(PtrOpIdx, ASCast);
22144}
22145
22148
22151
22154 if (const auto *ConstVal = dyn_cast<Constant>(AI->getValOperand());
22155 ConstVal && ConstVal->isNullValue() &&
22157 // atomicrmw or %ptr, 0 -> atomicrmw add %ptr, 0
22159
22160 // We may still need the private-alias-flat handling below.
22161
22162 // TODO: Skip this for cases where we cannot access remote memory.
22163 }
22164 }
22165
22166 // The non-flat expansions should only perform the de-canonicalization of
22167 // identity values.
22169 return;
22170
22172}
22173
22180
22184
22186 "Expand Atomic Load only handles SCRATCH -> FLAT conversion");
22187}
22188
22190 if (SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
22191 return convertScratchAtomicToFlatAtomic(SI, SI->getPointerOperandIndex());
22192
22194 "Expand Atomic Store only handles SCRATCH -> FLAT conversion");
22195}
static bool isMul(MachineInstr *MI)
unsigned NumParts
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
AMDGPU address space definition.
static constexpr std::pair< ImplicitArgumentMask, StringLiteral > ImplicitAttrs[]
static bool allUsesHaveSourceMods(MachineInstr &MI, MachineRegisterInfo &MRI, unsigned CostThreshold=4)
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
static bool isCtlzOpc(unsigned Opc)
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
static bool isNoUnsignedWrap(MachineInstr *Addr)
static bool parseTexFail(uint64_t TexFailCtrl, bool &TFE, bool &LWE, bool &IsTexFail)
static bool isAsyncLDSDMA(Intrinsic::ID Intr)
static std::optional< uint32_t > getConstantNamedBarrierNumber(const MachineOperand &BarOp, const MachineRegisterInfo &MRI)
Return the barrier ID for BarOp if it's statically known, mapping poison to 0 and masking off the hig...
static void packImage16bitOpsToDwords(MachineIRBuilder &B, MachineInstr &MI, SmallVectorImpl< Register > &PackedAddrs, unsigned ArgOffset, const AMDGPU::ImageDimIntrinsicInfo *Intr, bool IsA16, bool IsG16)
Turn a set of f16 typed registers in AddrRegs into a dword sized vector with f16 typed elements.
static Register readClusterIdField(MachineIRBuilder &B)
static bool isKnownNonNull(Register Val, MachineRegisterInfo &MRI, const AMDGPUTargetMachine &TM, unsigned AddrSpace)
Return true if the value is a known valid address, such that a null check is not necessary.
Provides AMDGPU specific target descriptions.
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
static DenormalFPEnv getDenormalFPEnv(AttributeSet FnAttrs)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
@ DEFAULT
Default weight is used in cases when there is no dedicated execution weight set.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< SDByteProvider > calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, std::optional< uint64_t > VectorIndex, unsigned StartingIndex=0, MutableArrayRef< uint8_t > ByteMask={})
dxil translate DXIL Translate Metadata
static bool isSigned(unsigned Opcode)
Utilities for dealing with flags related to floating point properties and mode controls.
AMD GCN specific subclass of TargetSubtarget.
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
uint64_t IntrinsicInst * II
#define P(N)
static constexpr MCPhysReg SPReg
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Contains matchers for matching SelectionDAG nodes and values.
static void r0(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition SHA1.cpp:39
static void r3(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition SHA1.cpp:57
static void r2(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition SHA1.cpp:51
static void r1(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition SHA1.cpp:45
#define FP_DENORM_FLUSH_NONE
Definition SIDefines.h:1523
#define FP_DENORM_FLUSH_IN_FLUSH_OUT
Definition SIDefines.h:1520
SI Fold Operands
static void reservePrivateMemoryRegs(const TargetMachine &TM, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info)
static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, const SDLoc &DL, SelectionDAG &DAG, bool Unpacked)
static MachineBasicBlock * emitIndirectSrc(MachineInstr &MI, MachineBasicBlock &MBB, const GCNSubtarget &ST)
static bool denormalModeIsFlushAllF64F16(const MachineFunction &MF)
static bool isBuiltFromFAbs(SDValue Op)
static bool isAtomicRMWLegalIntTy(Type *Ty)
static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelValueTracking &VT, KnownBits &Known, unsigned Dim)
static bool flatInstrMayAccessPrivate(const Instruction *I)
Return if a flat address space atomicrmw can access private memory.
static std::pair< unsigned, int > computeIndirectRegAndOffset(const SIRegisterInfo &TRI, const TargetRegisterClass *SuperRC, unsigned VecReg, int Offset)
static bool denormalModeIsFlushAllF32(const MachineFunction &MF)
static bool addresses16Bits(int Mask)
static MachineBasicBlock * expand64BitScalarArithmetic(MachineInstr &MI, MachineBasicBlock *BB)
static bool isClampZeroToOne(SDValue A, SDValue B)
static bool isBoolSGPRExt(SDValue V)
static bool supportsMin3Max3(const GCNSubtarget &Subtarget, unsigned Opc, EVT VT)
static AtomicFlushDenormalReason getAtomicFlushDenormalReason(const AtomicRMWInst *RMW)
static unsigned findFirstFreeSGPR(CCState &CCInfo)
static uint32_t getPermuteMask(SDValue V)
static SDValue lowerLaneOp(const SITargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
static int getAlignedAGPRClassID(unsigned UnalignedClassID)
static void processPSInputArgs(SmallVectorImpl< ISD::InputArg > &Splits, CallingConv::ID CallConv, ArrayRef< ISD::InputArg > Ins, BitVector &Skipped, FunctionType *FType, SIMachineFunctionInfo *Info)
static SDValue selectSOffset(SDValue SOffset, SelectionDAG &DAG, const GCNSubtarget *Subtarget)
static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, ISD::LoadExtType ExtType, SDValue Op, const SDLoc &SL, EVT VT)
static std::tuple< unsigned, unsigned > getDPPOpcForWaveReduction(unsigned Opc, const GCNSubtarget &ST)
static void fixMasks(SmallVectorImpl< DotSrc > &Srcs, unsigned ChainLength)
static bool is32bitWaveReduceOperation(unsigned Opc)
static TargetLowering::AtomicExpansionKind atomicSupportedIfLegalIntType(const AtomicRMWInst *RMW)
static SDValue strictFPExtFromF16(SelectionDAG &DAG, SDValue Src)
Return the source of an fp_extend from f16 to f32, or a converted FP constant.
static bool isAtomicRMWLegalXChgTy(const AtomicRMWInst *RMW)
static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val)
static void convertScratchAtomicToFlatAtomic(Instruction *I, unsigned PtrOpIdx)
static bool isCopyFromRegOfInlineAsm(const SDNode *N)
static bool elementPairIsOddToEven(ArrayRef< int > Mask, int Elt)
static SDValue lowerBFEIntrinsic(SDValue Op, SelectionDAG &DAG, Intrinsic::ID IntrinsicID)
static SDValue getDWordFromOffset(SelectionDAG &DAG, SDLoc SL, SDValue Src, unsigned DWordOffset)
static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, unsigned InitResultReg, unsigned PhiReg, int Offset, bool UseGPRIdxMode, Register &SGPRIdxReg)
static bool isFloatingPointWaveReduceOperation(unsigned Opc)
static bool isImmConstraint(StringRef Constraint)
static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, SDValue Src, int ExtraElts)
static bool hasCFUser(const Value *V, SmallPtrSet< const Value *, 16 > &Visited, unsigned WaveSize)
static std::pair< Register, Register > ExtractSubRegs(MachineInstr &MI, MachineOperand &Op, const TargetRegisterClass *SrcRC, const GCNSubtarget &ST, MachineRegisterInfo &MRI)
static unsigned SubIdx2Lane(unsigned Idx)
Helper function for adjustWritemask.
static TargetLowering::AtomicExpansionKind getPrivateAtomicExpansionKind(const GCNSubtarget &STI)
static bool addressMayBeAccessedAsPrivate(const MachineMemOperand *MMO, const SIMachineFunctionInfo &Info)
static MachineBasicBlock * lowerWaveReduce(MachineInstr &MI, MachineBasicBlock &BB, const GCNSubtarget &ST, unsigned Opc)
static bool elementPairIsContiguous(ArrayRef< int > Mask, int Elt)
static bool hasOneLiveUse(SDValue Op)
static bool isV2BF16(Type *Ty)
static bool isFrexpExp(SDValue V, SDValue &FrexpInput)
static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, const TargetRegisterClass *RC, unsigned NumArgRegs)
static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, EVT VT, SDValue N0, SDValue N1, SDValue N2, bool Signed)
static SDValue resolveSources(SelectionDAG &DAG, SDLoc SL, SmallVectorImpl< DotSrc > &Srcs, bool IsSigned, bool IsAny)
static bool hasNon16BitAccesses(uint64_t PermMask, SDValue &Op, SDValue &OtherOp)
static SDValue lowerWaveShuffle(const SITargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
static SDValue diagnoseUnsupportedImage(SelectionDAG &DAG, SDValue Op, ArrayRef< EVT > ResultTypes, const SDLoc &DL, const Twine &Msg)
Emit a DiagnosticInfoUnsupported for an unsupported image intrinsic and return poison values of Resul...
static void placeSources(ByteProvider< SDValue > &Src0, ByteProvider< SDValue > &Src1, SmallVectorImpl< DotSrc > &Src0s, SmallVectorImpl< DotSrc > &Src1s, int Step)
static unsigned parseSyncscopeMDArg(const CallBase &CI, unsigned ArgIdx)
static EVT memVTFromLoadIntrReturn(const SITargetLowering &TLI, const DataLayout &DL, Type *Ty, unsigned MaxNumLanes)
static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, const DebugLoc &DL, const MachineOperand &Idx, unsigned InitReg, unsigned ResultReg, unsigned PhiReg, unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, Register &SGPRIdxReg)
static SDValue matchPERM(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static bool isFrameIndexOp(SDValue Op)
static ConstantFPSDNode * getSplatConstantFP(SDValue Op)
static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg)
static void knownBitsForSBFE(const MachineInstr &MI, GISelValueTracking &VT, KnownBits &Known, const APInt &DemandedElts, unsigned BFEWidth, bool SExt, unsigned Depth)
static bool isExtendedFrom16Bits(SDValue &Operand)
static std::optional< bool > checkDot4MulSignedness(const SDValue &N, ByteProvider< SDValue > &Src0, ByteProvider< SDValue > &Src1, const SDValue &S0Op, const SDValue &S1Op, const SelectionDAG &DAG)
static SDValue matchHalfZeroPack(SDValue V, bool &IsHigh)
If V is a 32-bit value whose low or high 16 bits are known zero because it was built as a half-zero p...
static bool vectorEltWillFoldAway(SDValue Op)
static SDValue getSPDenormModeValue(uint32_t SPDenormMode, SelectionDAG &DAG, const SIMachineFunctionInfo *Info, const GCNSubtarget *ST)
static uint32_t getConstantPermuteMask(uint32_t C)
static AtomicOrdering parseAtomicOrderingCABIArg(const CallBase &CI, unsigned ArgIdx)
static MachineBasicBlock * emitIndirectDst(MachineInstr &MI, MachineBasicBlock &MBB, const GCNSubtarget &ST)
static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, MachineRegisterInfo &MRI, MachineInstr &MI, int Offset)
static DenormalFPEnv getDenormalFPEnv(const MachineFunction &MF)
static std::pair< MachineBasicBlock *, MachineBasicBlock * > splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop)
static unsigned getBasePtrIndex(const MemSDNode *N)
MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset by the chain and intrinsi...
static void allocateFixedSGPRInputImpl(CCState &CCInfo, const TargetRegisterClass *RC, MCRegister Reg)
static SDValue constructRetValue(SelectionDAG &DAG, MachineSDNode *Result, ArrayRef< EVT > ResultTypes, bool IsTexFail, bool Unpacked, bool IsD16, int DMaskPop, int NumVDataDwords, bool IsAtomicPacked16Bit, const SDLoc &DL)
static std::pair< SDValue, SDValue > splitTFEValueAndStatus(SDValue Op, EVT VT, const SDLoc &DL, SelectionDAG &DAG)
static std::optional< ByteProvider< SDValue > > handleMulOperand(const SDValue &MulOperand)
static ISD::CondCode tryReduceF64CompareToHiHalf(const ISD::CondCode CC, const SDValue LHS, const SDValue RHS, const SelectionDAG &DAG)
static Register getIndirectSGPRIdx(const SIInstrInfo *TII, MachineRegisterInfo &MRI, MachineInstr &MI, int Offset)
static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, EVT VT)
static bool isSingleUseFAbs(SDValue Op)
static EVT memVTFromLoadIntrData(const SITargetLowering &TLI, const DataLayout &DL, Type *Ty, unsigned MaxNumLanes)
static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc)
static unsigned getExtOpcodeForPromotedOp(SDValue Op)
static void expand64BitV_CNDMASK(MachineInstr &MI, MachineBasicBlock *BB)
static GlobalFPAtomicLegality getGlobalMemoryFPAtomicLegality(const GCNSubtarget &Subtarget, const AtomicRMWInst *RMW, bool HasSystemScope)
static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, uint64_t Val)
static SDValue tryFoldMADwithSRL(SelectionDAG &DAG, const SDLoc &SL, SDValue MulLHS, SDValue MulRHS, SDValue AddRHS)
static unsigned getIntrMemWidth(unsigned IntrID)
static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, ArrayRef< SDValue > Elts)
static SDNode * findUser(SDValue Value, unsigned Opcode)
Helper function for LowerBRCOND.
static unsigned addPermMasks(unsigned First, unsigned Second)
static uint64_t clearUnusedBits(uint64_t Val, unsigned Size)
static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue C, SDValue GlueChain, SDNodeFlags Flags)
static bool isV2F16OrV2BF16(Type *Ty)
static OptimizationRemark emitAtomicRMWLegalRemark(const AtomicRMWInst *RMW, GlobalFPAtomicLegality MemLegality, AtomicFlushDenormalReason DenormReason)
static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, EVT VT)
static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue GlueChain, SDNodeFlags Flags)
static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, const SDLoc &DL, int64_t Offset, EVT PtrVT, unsigned GAFlags=SIInstrInfo::MO_NONE)
static const std::optional< ByteProvider< SDValue > > calculateSrcByte(const SDValue Op, uint64_t DestByte, uint64_t SrcIndex=0, unsigned Depth=0)
static bool isV2F16(Type *Ty)
static void initializeM0ToZeroForClusterLoad(SDValue Op, SelectionDAG &DAG, SDLoc DL)
static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg)
static uint64_t getIdentityValueForWaveReduction(unsigned Opc)
static void foldAsyncLDSOffset(SDValue Op, SelectionDAG &DAG, SDLoc DL)
SI DAG Lowering interface definition.
Interface definition for SIRegisterInfo.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
const char * Msg
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
LLVM IR instance of the generic uniformity analysis.
static constexpr int Concat[]
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static bool isSupportedBitWidth(unsigned Bits)
unsigned allocateBarrierGlobal(const DataLayout &DL, const GlobalVariable &GV)
static std::optional< uint32_t > getLDSKernelIdMetadata(const Function &F)
void setDynLDSAlign(const Function &F, const GlobalVariable &GV)
static std::optional< uint32_t > get32BitAbsoluteAddress(const GlobalValue &GV, unsigned AS)
static unsigned numBitsSigned(SDValue Op, SelectionDAG &DAG)
SDValue SplitVectorLoad(SDValue Op, SelectionDAG &DAG) const
Split a vector load into 2 loads of half the vector.
void analyzeFormalArgumentsCompute(CCState &State, const SmallVectorImpl< ISD::InputArg > &Ins) const
The SelectionDAGBuilder will automatically promote function arguments with illegal types.
SDValue LowerF64ToF16Safe(SDValue Src, const SDLoc &DL, SelectionDAG &DAG) const
SDValue storeStackInputValue(SelectionDAG &DAG, const SDLoc &SL, SDValue Chain, SDValue ArgVal, int64_t Offset) const
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
SDValue splitBinaryBitConstantOpImpl(DAGCombinerInfo &DCI, const SDLoc &SL, unsigned Opc, SDValue LHS, uint32_t ValLo, uint32_t ValHi) const
Split the 64-bit value LHS into two 32-bit components, and perform the binary operation Opc to it wit...
SDValue lowerUnhandledCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals, StringRef Reason) const
virtual SDValue LowerGlobalAddress(AMDGPUMachineFunctionInfo *MFI, SDValue Op, SelectionDAG &DAG) const
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
SDValue addTokenForArgument(SDValue Chain, SelectionDAG &DAG, MachineFrameInfo &MFI, int ClobberedFI) const
bool isKnownNeverNaNForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, bool SNaN=false, unsigned Depth=0) const override
If SNaN is false,.
static bool needsDenormHandlingF32(const SelectionDAG &DAG, SDValue Src, SDNodeFlags Flags)
uint32_t getImplicitParameterOffset(const MachineFunction &MF, const ImplicitParameter Param) const
Helper function that returns the byte offset of the given type of implicit parameter.
SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const
static KnownBits computeKnownBitsForMul24(const KnownBits &LHSKnown, const KnownBits &RHSKnown, unsigned BitWidth, bool IsSigned, bool SelfMultiply)
SDValue loadInputValue(SelectionDAG &DAG, const TargetRegisterClass *RC, EVT VT, const SDLoc &SL, const ArgDescriptor &Arg) const
AMDGPUTargetLowering(const TargetMachine &TM, const TargetSubtargetInfo &STI, const AMDGPUSubtarget &AMDGPUSTI)
static EVT getEquivalentMemType(LLVMContext &Context, EVT VT)
SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
SDValue CreateLiveInRegister(SelectionDAG &DAG, const TargetRegisterClass *RC, Register Reg, EVT VT, const SDLoc &SL, bool RawReg=false) const
Helper function that adds Reg to the LiveIn list of the DAG's MachineFunction.
SDValue SplitVectorStore(SDValue Op, SelectionDAG &DAG) const
Split a vector store into 2 stores of half the vector.
std::pair< SDValue, SDValue > split64BitValue(SDValue Op, SelectionDAG &DAG) const
Return 64-bit value Op as two 32-bit integers.
static CCAssignFn * CCAssignFnForReturn(CallingConv::ID CC, bool IsVarArg)
static CCAssignFn * CCAssignFnForCall(CallingConv::ID CC, bool IsVarArg)
Selects the correct CCAssignFn for a given CallingConvention value.
static unsigned numBitsUnsigned(SDValue Op, SelectionDAG &DAG)
static bool allowApproxFunc(const SelectionDAG &DAG, SDNodeFlags Flags)
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
SDValue performRcpCombine(SDNode *N, DAGCombinerInfo &DCI) const
SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const
static bool shouldFoldFNegIntoSrc(SDNode *FNeg, SDValue FNegSrc)
bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const override
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue WidenOrSplitVectorLoad(SDValue Op, SelectionDAG &DAG) const
Widen a suitably aligned v3 load.
SDValue getHiHalf64(SDValue Op, SelectionDAG &DAG) const
bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
const std::array< unsigned, 3 > & getDims() const
static const LaneMaskConstants & get(const GCNSubtarget &ST)
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1257
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1687
bool isNegative() const
Definition APFloat.h:1616
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6336
bool isNormal() const
Definition APFloat.h:1620
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1225
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1275
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1235
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1216
bool isInfinity() const
Definition APFloat.h:1613
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
bool isOneBitSet(unsigned BitNo) const
Determine if this APInt Value only has the specified bit set.
Definition APInt.h:362
bool isMask(unsigned numBits) const
Definition APInt.h:484
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
unsigned getAddressSpace() const
Return the address space for the allocation.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:332
const Function * getParent() const
Definition Argument.h:44
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
An instruction that atomically checks whether a specified value is in a memory location,...
bool isVolatile() const
Return true if this is a cmpxchg from a volatile memory location.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
static unsigned getPointerOperandIndex()
an instruction that atomically reads a memory location, combines it with another value,...
static unsigned getPointerOperandIndex()
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
void setOperation(BinOp Operation)
BinOp getOperation() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
static LLVM_ABI StringRef getOperationName(BinOp Op)
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
bool isCompareAndSwap() const
Returns true if this SDNode represents cmpxchg atomic operation, false otherwise.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
LLVM_ABI MemoryEffects getMemoryEffects() const
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
A "pseudo-class" with methods for operating on BUILD_VECTORs.
Represents known origin of an individual byte in combine pattern.
static ByteProvider getConstantZero()
static ByteProvider getSrc(std::optional< ISelOp > Val, int64_t ByteOffset, int64_t VectorOffset)
CCState - This class holds information needed while lowering arguments and return values.
MachineFunction & getMachineFunction() const
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
static LLVM_ABI bool resultsCompatible(CallingConv::ID CalleeCC, CallingConv::ID CallerCC, MachineFunction &MF, LLVMContext &C, const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn CalleeFn, CCAssignFn CallerFn)
Returns true if the results of the two calling conventions are compatible.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
MCRegister AllocateReg(MCPhysReg Reg)
AllocateReg - Attempt to allocate one register.
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
int64_t AllocateStack(unsigned Size, Align Alignment)
AllocateStack - Allocate a chunk of stack space with the specified size and alignment.
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
bool isAllocated(MCRegister Reg) const
isAllocated - Return true if the specified register (or an alias) is allocated.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
int64_t getLocMemOffset() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
static LLVM_ABI CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
Constant * getValue() const
Definition Metadata.h:557
const APFloat & getValueAPF() const
bool isPosZero() const
Return true if the value is positive zero.
bool isOne() const
Returns true if this value is exactly +1.0.
bool isMinusOne() const
Returns true if this value is exactly -1.0.
bool isNegative() const
Return true if the value is negative.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool isBigEndian() const
Definition DataLayout.h:220
A debug info location.
Definition DebugLoc.h:126
Diagnostic information for unsupported feature in backend.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Register DemoteRegister
DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg allocated to hold a pointer to ...
LLVM_ABI const Value * getValueFromVirtualReg(Register Vreg)
This method is called from TargetLowerinInfo::isSDNodeSourceOfDivergence to get the Value correspondi...
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:356
iterator_range< arg_iterator > args()
Definition Function.h:886
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition Function.cpp:807
size_t arg_size() const
Definition Function.h:895
Argument * getArg(unsigned i) const
Definition Function.h:880
const SIInstrInfo * getInstrInfo() const override
bool hasMadF16() const
unsigned getInstCacheLineSize() const
Instruction cache line size in bytes (64 for pre-GFX11, 128 for GFX11+).
const SIRegisterInfo * getRegisterInfo() const override
unsigned getMaxPrivateElementSize(bool ForBufferRSrc=false) const
bool hasPrivateSegmentBuffer() const
const MachineFunction & getMachineFunction() const
void computeKnownBitsImpl(Register R, KnownBits &Known, const APInt &DemandedElts, unsigned Depth=0)
Evaluate a known-bits query with an explicit worklist instead of recursive descent.
bool isDivergentAtDef(ConstValueRefT V) const
Whether V is divergent at its definition.
LLVM_ABI unsigned getAddressSpace() const
const GlobalValue * getGlobal() const
bool hasExternalLinkage() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
Class to represent integer types.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
constexpr unsigned getScalarSizeInBits() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
static LLT integer(unsigned SizeInBits)
LLT changeElementSize(unsigned NewEltSize) const
If this type is a vector, return a vector with the same number of elements but the new element size.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
LLVM_ABI SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static unsigned getPointerOperandIndex()
This class is used to represent ISD::LOAD nodes.
bool hasValue() const
TypeSize getValue() const
Describe properties that are true of each instruction in the target description file.
unsigned getID() const
getID() - Return the register class ID number.
MCRegister getRegister(unsigned i) const
getRegister - Return the specified register in the class.
unsigned getNumRegs() const
getNumRegs - Return the number of registers in this class.
iterator begin() const
begin/end - Return all of the registers in this class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
LLVM_ABI MDNode * createRange(const APInt &Lo, const APInt &Hi)
Return metadata describing the range [Lo, Hi).
Definition MDBuilder.cpp:92
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
Helper class for constructing bundles of MachineInstrs.
MachineBasicBlock::instr_iterator begin() const
Return an iterator to the first bundled instruction.
Machine Value Type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool bitsLE(MVT VT) const
Return true if this has no more bits than VT.
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isScalableVector() const
Return true if this is a vector value type where the runtime length is machine dependent.
MVT changeTypeToInteger()
Return the type converted to an equivalently sized integer or vector with integer element type.
static LLVM_ABI MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
static auto all_valuetypes()
SimpleValueType Iteration.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
static MVT getIntegerVT(unsigned BitWidth)
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
bool hasCalls() const
Return true if the current function has any function calls.
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
bool hasStackObjects() const
Return true if there are any stack objects in this function.
PseudoSourceValueManager & getPSVManager() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
void push_back(MachineBasicBlock *MBB)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static MachineOperand CreateImm(int64_t Val)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
An SDNode that represents everything that will be needed to construct a MachineInstr.
This is an abstract virtual class for memory operations.
unsigned getAddressSpace() const
Return the address space for the associated pointer.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
EVT getMemoryVT() const
Return the type of the in-memory value.
bool onlyWritesMemory() const
Whether this function only (at most) writes memory.
Definition ModRef.h:252
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI const PseudoSourceValue * getConstantPool()
Return a pseudo source value referencing the constant pool.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
bool hasOneUse() const
Return true if there is exactly one use of this node.
value_iterator value_end() const
ISD::CondCode getOperandCondCode(unsigned Num) const
Helper method returns the CondCode of a CondCodeSDNode.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
user_iterator user_begin() const
Provide iteration support to walk over all users of an SDNode.
op_iterator op_end() const
bool isAnyAdd() const
Returns true if the node type is ADD or PTRADD.
value_iterator value_begin() const
op_iterator op_begin() const
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
unsigned getNumOperands() const
static unsigned getMaxMUBUFImmOffset(const GCNSubtarget &ST)
static unsigned getDSShaderTypeValue(const MachineFunction &MF)
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
AMDGPU::ClusterDimsAttr getClusterDims() const
SIModeRegisterDefaults getMode() const
std::tuple< const ArgDescriptor *, const TargetRegisterClass *, LLT > getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const
const AMDGPUGWSResourcePseudoSourceValue * getGWSPSV(const AMDGPUTargetMachine &TM)
static LLVM_READONLY const TargetRegisterClass * getSGPRClassForBitWidth(unsigned BitWidth)
static unsigned getSubRegFromChannel(uint64_t Channel, uint64_t NumRegs=1)
static bool isVGPRClass(const TargetRegisterClass *RC)
static bool isSGPRClass(const TargetRegisterClass *RC)
static bool isAGPRClass(const TargetRegisterClass *RC)
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
bool isTypeDesirableForOp(unsigned Op, EVT VT) const override
Return true if the target has native support for the specified value type and it is 'desirable' to us...
SDNode * PostISelFolding(MachineSDNode *N, SelectionDAG &DAG) const override
Fold the instructions after selecting them.
SDValue splitTernaryVectorOp(SDValue Op, SelectionDAG &DAG) const
MachineSDNode * wrapAddr64Rsrc(SelectionDAG &DAG, const SDLoc &DL, SDValue Ptr) const
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
SDValue lowerGET_ROUNDING(SDValue Op, SelectionDAG &DAG) const
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
bool requiresUniformRegister(MachineFunction &MF, const Value *V) const override
Allows target to decide about the register class of the specific value that is live outside the defin...
bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const override
Returns true if be combined with to form an ISD::FMAD.
void bundleInstWithWaitcnt(MachineInstr &MI) const
Insert MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
SDValue lowerROTR(SDValue Op, SelectionDAG &DAG) const
MVT getScalarShiftAmountTy(const DataLayout &, EVT) const override
Return the type to use for a scalar shift opcode, given the shifted amount type.
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
MVT getPointerTy(const DataLayout &DL, unsigned AS) const override
Map address space 7 to MVT::amdgpuBufferFatPointer because that's its in-memory representation.
bool denormalsEnabledForType(const SelectionDAG &DAG, EVT VT) const
void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock * > &Exits) const override
Insert explicit copies in entry and exit blocks.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
SDNode * legalizeTargetIndependentNode(SDNode *Node, SelectionDAG &DAG) const
Legalize target independent instructions (e.g.
bool allowsMisalignedMemoryAccessesImpl(unsigned Size, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *IsFast=nullptr) const
TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
SDValue lowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const
const GCNSubtarget * getSubtarget() const
bool enableAggressiveFMAFusion(EVT VT) const override
Return true if target always benefits from combining into FMA for a given value type.
bool shouldEmitGOTReloc(const GlobalValue *GV) const
SDValue splitUnaryVectorOp(SDValue Op, SelectionDAG &DAG) const
SDValue lowerGET_FPENV(SDValue Op, SelectionDAG &DAG) const
bool isCanonicalized(SelectionDAG &DAG, SDValue Op, SDNodeFlags UserFlags={}, unsigned MaxDepth=5) const
void allocateSpecialInputSGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
void allocateLDSKernelId(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
SDValue LowerSTACKSAVE(SDValue Op, SelectionDAG &DAG) const
bool isReassocProfitable(SelectionDAG &DAG, SDValue N0, SDValue N1) const override
void allocateHSAUserSGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
ArrayRef< MCPhysReg > getRoundingControlRegisters() const override
Returns a 0 terminated array of rounding control registers that can be attached into strict FP call.
ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent) const override
Return the register class that should be used for the specified value type.
void AddMemOpInit(MachineInstr &MI) const
MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const override
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
bool isLegalGlobalAddressingMode(const AddrMode &AM) const
bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override
Return true if it is beneficial to convert a load of a constant to just the constant itself.
InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const override
bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, unsigned *IsFast) const override
Return true if the target supports a memory access of this type for the given address space and align...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
void emitExpandAtomicStore(StoreInst *SI) const override
Perform a atomic store using a target-specific way.
Align computeKnownAlignForTargetInstr(GISelValueTracking &Analysis, Register R, const MachineRegisterInfo &MRI, unsigned Depth=0) const override
Determine the known alignment for the pointer value R.
bool getAsmOperandConstVal(SDValue Op, uint64_t &Val) const
bool isShuffleMaskLegal(ArrayRef< int >, EVT) const override
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
void emitExpandAtomicLoad(LoadInst *LI) const override
Perform a atomic load using a target-specific way.
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
void computeKnownBitsForStackObjectPointer(KnownBits &Known, const MachineFunction &MF, Align Alignment) const override
Determine known bits of a pointer to a known valid stack object.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
LLT getPreferredShiftAmountTy(LLT Ty) const override
Return the preferred type to use for a shift opcode, given the shifted amount type is ShiftValueTy.
ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const override
Return the cost of extracting a subvector of type ResVT from a vector of type SrcVT,...
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
Align getPrefLoopAlignment(MachineLoop *ML, const MachineBasicBlock *BlockToAlign) const override
Return the preferred loop alignment.
SDValue lowerSET_FPENV(SDValue Op, SelectionDAG &DAG) const
bool shouldPreservePtrArith(const Function &F, EVT PtrVT) const override
True if target has some particular form of dealing with pointer arithmetic semantics for pointers wit...
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &, const CallBase &, MachineFunction &MF, unsigned IntrinsicID) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
SDValue lowerSET_ROUNDING(SDValue Op, SelectionDAG &DAG) const
void allocateSpecialInputVGPRsFixed(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
Allocate implicit function VGPR arguments in fixed registers.
MachineBasicBlock * emitGWSMemViolTestLoop(MachineInstr &MI, MachineBasicBlock *BB) const
bool getAddrModeArguments(const IntrinsicInst *I, SmallVectorImpl< Value * > &Ops, Type *&AccessTy) const override
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
bool checkAsmConstraintValA(SDValue Op, uint64_t Val, unsigned MaxSize=64) const
bool shouldEmitFixup(const GlobalValue *GV) const
MachineBasicBlock * splitKillBlock(MachineInstr &MI, MachineBasicBlock *BB) const
void emitExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) const override
Perform a cmpxchg expansion using a target-specific method.
bool canTransformPtrArithOutOfBounds(const Function &F, EVT PtrVT) const override
True if the target allows transformations of in-bounds pointer arithmetic that cause out-of-bounds in...
bool hasMemSDNodeUser(SDNode *N) const
bool isSDNodeSourceOfDivergence(const SDNode *N, FunctionLoweringInfo *FLI, UniformityInfo *UA) const override
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
bool isEligibleForTailCallOptimization(SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SmallVectorImpl< ISD::InputArg > &Ins, SelectionDAG &DAG) const
bool isMemOpHasNoClobberedMemOperand(const SDNode *N) const
bool isLegalFlatAddressingMode(const AddrMode &AM, unsigned AddrSpace) const
SDValue LowerCallResult(SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals, bool isThisReturn, SDValue ThisVal) const
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, EVT DestVT, EVT SrcVT) const override
Return true if an fpext operation input to an Opcode operation is free (for instance,...
void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const override
Assign the register class depending on the number of bits set in the writemask.
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
void finalizeLowering(MachineFunction &MF) const override
Execute target specific actions to finalize target lowering.
static bool isNonGlobalAddrSpace(unsigned AS)
void emitExpandAtomicAddrSpacePredicate(Instruction *AI) const
MachineSDNode * buildRSRC(SelectionDAG &DAG, const SDLoc &DL, SDValue Ptr, uint32_t RsrcDword1, uint64_t RsrcDword2And3) const
Return a resource descriptor with the 'Add TID' bit enabled The TID (Thread ID) is multiplied by the ...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
bool mayBeEmittedAsTailCall(const CallInst *) const override
Return true if the target may be able emit the call instruction as a tail call.
AtomicExpansionKind shouldExpandAtomicStoreInIR(const StoreInst *SI) const override
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
void passSpecialInputs(CallLoweringInfo &CLI, CCState &CCInfo, const SIMachineFunctionInfo &Info, SmallVectorImpl< std::pair< unsigned, SDValue > > &RegsToPass, SmallVectorImpl< SDValue > &MemOpChains, SDValue Chain) const
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool checkAsmConstraintVal(SDValue Op, StringRef Constraint, uint64_t Val) const
AtomicExpansionKind shouldExpandAtomicLoadInIR(const LoadInst *LI) const override
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
bool isKnownNeverNaNForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, bool SNaN=false, unsigned Depth=0) const override
If SNaN is false,.
void emitExpandAtomicRMW(AtomicRMWInst *AI) const override
Perform a atomicrmw expansion using a target-specific way.
static bool shouldExpandVectorDynExt(unsigned EltSize, unsigned NumElem, bool IsDivergentIdx, const GCNSubtarget *Subtarget)
Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be expanded into a set of cmp...
bool shouldUseLDSConstAddress(const GlobalValue *GV) const
bool supportSplitCSR(MachineFunction *MF) const override
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
bool isExtractVecEltCheap(EVT VT, unsigned Index) const override
Return true if extraction of a scalar element from the given vector type at the given index is cheap.
SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
bool allowsMisalignedMemoryAccesses(LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *IsFast=nullptr) const override
LLT handling variant.
bool canMergeStoresTo(unsigned AS, EVT MemVT, const MachineFunction &MF) const override
Returns if it's reasonable to merge stores to MemVT size.
SDValue lowerPREFETCH(SDValue Op, SelectionDAG &DAG) const
SITargetLowering(const TargetMachine &tm, const GCNSubtarget &STI)
void computeKnownBitsForTargetInstr(GISelValueTracking &Analysis, Register R, KnownBits &Known, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool isFreeAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
bool shouldEmitPCReloc(const GlobalValue *GV) const
bool isUniformLoad(const LoadSDNode *Load) const
AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
void initializeSplitCSR(MachineBasicBlock *Entry) const override
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
void allocateSpecialEntryInputVGPRs(CCState &CCInfo, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
void allocatePreloadKernArgSGPRs(CCState &CCInfo, SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< ISD::InputArg > &Ins, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const
SDValue copyToM0(SelectionDAG &DAG, SDValue Chain, const SDLoc &DL, SDValue V) const
SDValue splitBinaryVectorOp(SDValue Op, SelectionDAG &DAG) const
MachinePointerInfo getKernargSegmentPtrInfo(MachineFunction &MF) const
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
MVT getPointerMemTy(const DataLayout &DL, unsigned AS) const override
Similarly, the in-memory representation of a p7 is {p8, i32}, aka v8i32 when padding is added.
void allocateSystemSGPRs(CCState &CCInfo, MachineFunction &MF, SIMachineFunctionInfo &Info, CallingConv::ID CallConv, bool IsShader) const
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
unsigned getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const override
Return the maximum amount of bytes allowed to be emitted when padding for alignment.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
std::pair< SDValue, SDValue > SplitVectorOperand(const SDNode *N, unsigned OpNo)
Split the node's operand with EXTRACT_SUBVECTOR and return the low/high part.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
const TargetMachine & getTarget() const
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFreeze(SDValue V, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison)
Return a freeze of V using the SDLoc of the value operand.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getErrorMergeValues(ArrayRef< EVT > ResultTypes, SDValue Chain, const SDLoc &dl)
Return poison values for each of ResultTypes, substituting Chain for any result of type MVT::Other,...
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Information about stack frame layout on the target.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
TargetInstrInfo - Interface to description of machine instruction set.
Type * Ty
Same as OrigTy, or partially legalized for soft float libcalls.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual void finalizeLowering(MachineFunction &MF) const
Execute target specific actions to finalize target lowering.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr, const MachineBasicBlock *BlockToAlign=nullptr) const
Return the preferred loop alignment.
virtual unsigned getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const
Return the maximum amount of bytes allowed to be emitted when padding for alignment.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
Convenience method to set an operation to Promote and specify the type in a single call.
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
void setHasExtractBitsInsn(bool hasExtractInsn=true)
Tells the code generator that the target has BitExtract instructions.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of a boolean value from i1 to a wider type.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
bool allowsMemoryAccessForAlignment(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
This function returns true if the memory access is aligned or if the target allows this specific unal...
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimumnum/fmaximumnum into multiple comparison with selects.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
virtual void computeKnownBitsForStackObjectPointer(KnownBits &Known, const MachineFunction &MF, Align Alignment) const
Determine known bits of a pointer to a known valid stack object.
std::pair< SDValue, SDValue > scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Turn load of vector type into a load of the individual elements.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
TargetLowering(const TargetLowering &)=delete
virtual MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
SDValue expandRoundInexactToOdd(EVT ResultVT, SDValue Op, const SDLoc &DL, SelectionDAG &DAG) const
Truncate Op to ResultVT.
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG, const SDLoc &DL, Align Alignment) const
Annotate a stack object pointer with known-bits assertions.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
const Triple & getTargetTriple() const
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
OSType getOS() const
Get the parsed operating system type of this triple.
Definition Triple.h:527
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
const Use & getOperandUse(unsigned i) const
Definition User.h:220
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isKnownEven() const
A return value of true indicates we know at compile time that the number of elements (vscale * Min) i...
Definition TypeSize.h:177
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS_32BIT
Address space for 32-bit constant memory.
@ BUFFER_STRIDED_POINTER
Address space for 192-bit fat buffer pointers with an additional index.
@ BARRIER
Address space for modeling barrier IDs as addresses.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ STREAMOUT_REGISTER
Internal address spaces. Can be freely renumbered.
@ VGPR
Address space for VGPRs.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ BUFFER_FAT_POINTER
Address space for 160-bit buffer fat pointers.
@ PRIVATE_ADDRESS
Address space for private memory.
@ BUFFER_RESOURCE
Address space for 128-bit buffer resources.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char NumVGPRs[]
Key for Kernel::CodeProps::Metadata::mNumVGPRs.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
APInt getExponentOnlyScaleDemandedBits()
LLVM_READONLY const MIMGG16MappingInfo * getMIMGG16MappingInfo(unsigned G)
bool isInlinableLiteralFP16(int16_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool isShader(CallingConv::ID CC)
bool shouldEmitConstantsToTextSection(const Triple &TT)
bool isFlatGlobalAddrSpace(unsigned AS)
const uint64_t FltRoundToHWConversionTable
bool isGFX12Plus(const MCSubtargetInfo &STI)
unsigned getNSAMaxSize(const MCSubtargetInfo &STI, bool HasSampler)
std::optional< unsigned > getExponentOnlyScaleArgIdx(unsigned IntrID)
constexpr int64_t getNullPointerValue(unsigned AS)
Get the null pointer value for the given address space.
bool isGFX11(const MCSubtargetInfo &STI)
bool isGFX13(const MCSubtargetInfo &STI)
bool hasValueInRangeLikeMetadata(const MDNode &MD, int64_t Val)
Checks if Val is inside MD, a !range-like metadata.
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
LLVM_READNONE bool isLegalDPALU_DPPControl(const MCSubtargetInfo &ST, unsigned DC)
LLVM_READNONE constexpr bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
unsigned getAMDHSACodeObjectVersion(const Module &M)
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
int getMIMGOpcode(unsigned BaseOpcode, unsigned MIMGEncoding, unsigned VDataDwords, unsigned VAddrDwords, bool IndexedRsrc, bool IndexedSamp)
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool isCompute(CallingConv::ID CC)
const BufferIntrinsicInfo * lookupBufferIntrinsic(unsigned Intr)
bool isIntrinsicSourceOfDivergence(unsigned IntrID)
LLVM_READNONE bool isInlinableIntLiteral(int64_t Literal)
Is this literal inlinable, and not one of the values intended for floating point values.
bool getMUBUFTfe(unsigned Opc)
bool isInlinableLiteralBF16(int16_t Literal, bool HasInv2Pi, bool *IsBF16)
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
LLVM_READONLY int32_t getGlobalSaddrOp(uint32_t Opcode)
bool isGFX11Plus(const MCSubtargetInfo &STI)
std::optional< unsigned > getInlineEncodingV2F16(uint32_t Literal)
std::tuple< char, unsigned, unsigned > parseAsmConstraintPhysReg(StringRef Constraint)
Returns a valid charcode or 0 in the first entry if this is a valid physical register constraint.
bool isGFX10Plus(const MCSubtargetInfo &STI)
bool isValidWMMAScaleFmtCombination(unsigned AFmt, unsigned AScale, unsigned BFmt, unsigned BScale)
bool isUniformMMO(const MachineMemOperand *MMO)
std::optional< unsigned > getInlineEncodingV2I16(uint32_t Literal)
uint32_t decodeFltRoundToHWConversionTable(uint32_t FltRounds)
Read the hardware rounding mode equivalent of a AMDGPUFltRounds value.
bool isExtendedGlobalAddrSpace(unsigned AS)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfo(unsigned DimEnum)
unsigned getBarrierMemberCountBitMask(const IsaVersion &Version)
std::optional< unsigned > getInlineEncodingV2BF16(uint32_t Literal)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
unsigned getSyntheticApertureNumber(unsigned AS)
LLVM_READNONE constexpr bool isChainCC(CallingConv::ID CC)
constexpr unsigned getSDOperandIdx(unsigned Arg, bool HasChain=true)
Convert IR argument index Arg of an intrinsic into an operand index of the INTRINSIC_* SelectionDAG n...
int getMaskedMIMGOp(unsigned Opc, unsigned NewChannels)
const ImageDimIntrinsicInfo * getImageDimIntrinsicInfo(unsigned Intr)
bool isInlinableLiteralI16(int32_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool canGuaranteeTCO(CallingConv::ID CC)
LLVM_READNONE constexpr bool isGraphics(CallingConv::ID CC)
bool isInlinableLiteral64(int64_t Literal, bool HasInv2Pi)
Is this literal inlinable.
const RsrcIntrinsic * lookupRsrcIntrinsic(unsigned Intr)
const uint64_t FltRoundConversionTable
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ MaxID
The highest possible ID. Must be some 2^k - 1.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ SET_FPENV
Sets the current floating-point environment.
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ CONVERT_FROM_ARBITRARY_FP
CONVERT_FROM_ARBITRARY_FP - This operator converts from an arbitrary floating-point represented as an...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ SET_ROUNDING
Set rounding mode.
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ BR
Control flow instructions. These all have token chains.
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:824
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ GET_FPMODE
Reads the current dynamic floating-point control modes.
@ GET_FPENV
Gets the current floating-point environment.
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ ATOMIC_LOAD_UDEC_WRAP
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ ExternalSymbol
Definition ISDOpcodes.h:95
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:124
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ BRCOND
BRCOND - Conditional branch.
@ CONVERT_TO_ARBITRARY_FP
CONVERT_TO_ARBITRARY_FP - Converts a native FP value to an arbitrary floating-point format,...
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
CondCode getUnsignedSetCC(CondCode Code)
Convert a signed integer condition code to unsigned.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI AttributeSet getFnAttributes(LLVMContext &C, ID id)
Return the function attributes for an intrinsic.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
LLVM_ABI FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > OverloadTys={})
Return the function type for an intrinsic.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
GFCstOrSplatGFCstMatch m_GFCstOrSplat(std::optional< FPValueAndVReg > &FPValReg)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_IntrinsicWOChain(const OpndPreds &...Opnds)
bool sd_match(SDValue N, Pattern &&P)
ConstantInt_match m_ConstInt()
Match any integer constants or splat of an integer constant.
Offsets
Offsets in bytes from the start of the input buffer.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
constexpr double inv_pi
constexpr double log2e
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition MathExtras.h:224
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
SDValue peekFPSignOps(SDValue Val)
Strip fabs/fneg/fcopysign from a value to get the underlying source.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
static const MachineMemOperand::Flags MOCFSB1
Definition SIInstrInfo.h:75
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
static void reportUnsupported(MachineIRBuilder &MIRBuilder, const Twine &Msg)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
static const MachineMemOperand::Flags MONoClobber
Mark the MMO of a uniform load if there are no potentially clobbering stores on any path from the sta...
Definition SIInstrInfo.h:49
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
AtomicOrderingCABI
Atomic ordering for C11 / C++11's memory models.
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
bool isBoolSGPR(SDValue V)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static const MachineMemOperand::Flags MOCooperative
Mark the MMO of cooperative load/store atomics.
Definition SIInstrInfo.h:57
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI Value * buildAtomicRMWValue(AtomicRMWInst::BinOp Op, IRBuilderBase &Builder, Value *Loaded, Value *Val)
Emit IR to implement the given atomicrmw operation on values in registers, returning the new value.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ AfterLegalizeDAG
Definition DAGCombine.h:19
@ AfterLegalizeVectorOps
Definition DAGCombine.h:18
@ AfterLegalizeTypes
Definition DAGCombine.h:17
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
@ NearestTiesToEven
roundTiesToEven.
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:233
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::pair< Value *, Value * > buildCmpXchgValue(IRBuilderBase &Builder, Value *Ptr, Value *Cmp, Value *Val, Align Alignment, bool IsVolatile=false)
Emit IR to implement the given cmpxchg operation on values in registers, returning the new value.
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:440
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
std::optional< StringRef > getAtomicScopeIRString(const Triple &T, AtomicScope S, bool IsSingleAddressSpace=false)
Returns the LLVM IR syncscope string that T uses to spell S.
Definition AtomicScope.h:34
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
static const MachineMemOperand::Flags MOLastUse
Mark the MMO of a load as the last use.
Definition SIInstrInfo.h:53
static const MachineMemOperand::Flags MOCFSB0
Use two MMO flags to encode the 2-bit cache fill size field for GFX13+.
Definition SIInstrInfo.h:72
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
constexpr RegState getUndefRegState(bool B)
@ Custom
The result value requires a custom uniformity check.
Definition Uniformity.h:31
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
int64_t DWordOffset
int64_t PermMask
std::tuple< const ArgDescriptor *, const TargetRegisterClass *, LLT > getPreloadedValue(PreloadedValue Value) const
static MCRegister getPrivateSegmentBufferReg(CallingConv::ID CC)
Returns the register a non-entry function with calling convention CC expects the private segment buff...
static const AMDGPUFunctionArgInfo FixedABIFunctionInfo
The argument layout of a buffer intrinsic.
std::optional< unsigned > getSizeArg() const
The access size of loads to LDS and prefetches.
std::optional< unsigned > getImmOffsetArg() const
The immediate offset of loads to LDS.
std::optional< unsigned > getAuxArg() const
The auxiliary (cache policy) argument.
std::optional< unsigned > getLDSPtrArg() const
The LDS destination of loads to LDS.
static constexpr uint64_t encode(Fields... Values)
static std::tuple< typename Fields::ValueType... > decode(uint64_t Encoded)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
MCRegister getRegister() const
static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask)
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
Helper struct shared between Function Specialization and SCCP Solver.
Definition SCCPSolver.h:42
Represents the full denormal controls for a function, including the default mode and the f32 specific...
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ Dynamic
Denormals have unknown treatment.
static constexpr DenormalMode getPreserveSign()
static constexpr DenormalMode getIEEE()
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:144
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:281
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:516
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
Definition ValueTypes.h:450
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:136
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:196
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
unsigned getPointerAddrSpace() const
unsigned getByValSize() const
Align getNonZeroMemAlign() const
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
MVT VT
Legalized type of this argument part.
unsigned getOrigArgIndex() const
OutputArg - This struct carries flags and a value for a single outgoing (actual) argument or outgoing...
static LLVM_ABI std::optional< bool > eq(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_EQ result.
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
These are IR-level optimization flags that may be propagated to SDNodes.
bool hasNoUnsignedWrap() const
bool hasAllowContract() const
bool hasNoSignedWrap() const
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
unsigned int NumVTs
DenormalMode FP64FP16Denormals
If this is set, neither input or output denormals are flushed for both f64 and f16/v2f16 instructions...
DenormalMode FP32Denormals
If this is set, neither input or output denormals are flushed for most f32 instructions.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
std::optional< unsigned > fallbackAddressSpace
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs